Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"graphql": "16.14.1",
"remark-gfm": "catalog:",
"remark-parse": "catalog:",
"unified": "catalog:",
"vite-plus": "catalog:"
},
"engines": {
Expand Down
108 changes: 107 additions & 1 deletion apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,21 @@ type WaitingInput = Pick<
export class KinChatService extends Context.Service<
KinChatService,
{
readonly notice: (input: {
readonly messageId: KinMessageId;
readonly orgId: KinOrgId;
readonly chatId: KinChatId;
readonly body: string;
readonly waitingFor?: KinPersonId;
}) => Effect.Effect<
{ readonly message: KinMessage; readonly waiting: KinWaitingItem | null },
ServiceError
>;
readonly resolveNotice: (input: {
readonly orgId: KinOrgId;
readonly waitingId: KinWaitingId;
readonly resolution: "answered" | "closed";
}) => Effect.Effect<void, ServiceError>;
readonly orgs: (
identities: ReadonlyArray<PersonIdentity>,
) => Effect.Effect<KinOrgsListResult, ServiceError>;
Expand Down Expand Up @@ -264,7 +279,9 @@ const make = Effect.gen(function* () {
) {
if (yield* repo.resolveWaiting({ ...item, resolution, resolvedAt: yield* now })) {
const updated = yield* requireRecord(repo.getWaiting(item));
yield* hub.publish({ type: "waiting.updated", orgId: item.orgId, item: updated });
yield* sql.afterCommit(
hub.publish({ type: "waiting.updated", orgId: item.orgId, item: updated }),
);
return updated;
}
return item;
Expand Down Expand Up @@ -394,6 +411,95 @@ const make = Effect.gen(function* () {
(effect) => transaction(effect).pipe(NodeSqliteClient.readOnly),
);
return KinChatService.of({
// Trusted server callers only; deliberately absent from RPC and MCP.
notice: Effect.fn("KinChatService.notice")(function* (input) {
yield* requireRecord(repo.getChat(input));
if (input.waitingFor !== undefined)
yield* requireRecord(
repo.activeMember({
...input,
principal: { _tag: "person", personId: input.waitingFor },
}),
);
const messageId = yield* decodeMessageId(input.messageId).pipe(
Effect.mapError(() => invalidState),
);
const previous = yield* repo.getMessage({ orgId: input.orgId, messageId });
if (Option.isSome(previous)) {
const message = previous.value;
const rows = yield* sql<{ waiting_id: string }>`SELECT waiting_id FROM kin_waiting
WHERE org_id = ${input.orgId} AND message_id = ${messageId} ORDER BY waiting_id`.pipe(
Effect.mapError(toPersistenceSqlError("KinChatService.notice")),
);
const waiting =
rows[0] === undefined
? null
: yield* requireRecord(
repo.getWaiting({
orgId: input.orgId,
waitingId: yield* decodeWaitingId(rows[0].waiting_id).pipe(
Effect.mapError(() => invalidState),
),
}),
);
if (
message.author._tag !== "system" ||
message.chatId !== input.chatId ||
message.body !== input.body ||
(waiting?.personId ?? undefined) !== input.waitingFor
)
return yield* notAllowed;
return { message, waiting };
}
const message = yield* repo.insertMessage({
orgId: input.orgId,
chatId: input.chatId,
messageId,
author: { _tag: "system" },
kind: "system",
body: input.body,
intent: null,
mentions: [],
replyTo: null,
widgetId: null,
floorRunId: null,
status: "posted",
sentBy: null,
clientMessageId: null,
createdAt: yield* now,
editedAt: null,
});
yield* sql.afterCommit(hub.publish({ type: "message.posted", orgId: input.orgId, message }));
let waiting: KinWaitingItem | null = null;
if (input.waitingFor !== undefined) {
waiting = {
orgId: input.orgId,
chatId: input.chatId,
waitingId: yield* decodeWaitingId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie),
personId: input.waitingFor,
messageId: message.messageId,
widgetId: null,
reason: "question",
createdAt: yield* now,
resolvedAt: null,
resolution: null,
};
yield* repo.addWaiting(waiting);
yield* sql.afterCommit(
hub.publish({ type: "waiting.updated", orgId: input.orgId, item: waiting }),
);
}
return { message, waiting };
}, transaction),
resolveNotice: Effect.fn("KinChatService.resolveNotice")(function* (input) {
const item = yield* requireRecord(repo.getWaiting(input));
if (item.reason !== "question" || item.messageId === null) return yield* notAllowed;
const message = yield* requireRecord(
repo.getMessage({ orgId: input.orgId, messageId: item.messageId }),
);
if (message.author._tag !== "system") return yield* notAllowed;
yield* resolve(item, input.resolution);
}, transaction),
orgs: Effect.fn("KinChatService.orgs")(function* (identities) {
const orgs = yield* Effect.forEach(
identities,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/kin/lead/LeadPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const memory = Layer.succeed(
readRules: () => Effect.die("Unused"),
query: () => Effect.die("Unused"),
readItem: () => Effect.die("Unused"),
readItemQuietly: () => Effect.die("Unused"),
rebuildIndex: () => Effect.die("Unused"),
rebuildCache: () => Effect.die("Unused"),
}),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/kin/lead/layer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ vi.mock("../memory/Memory.ts", async (importOriginal) => {
readRules: () => Effect.die("unused"),
query: () => Effect.die("unused"),
readItem: () => Effect.die("unused"),
readItemQuietly: () => Effect.die("unused"),
rebuildIndex: () => Effect.die("unused"),
rebuildCache: () => Effect.die("unused"),
});
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/kin/memory/Memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,16 @@ it.effect(
expect(yield* memory.readIndex(orgA)).toContain("⚠ review");
const counts = repository.counts();
yield* memory.query(orgA, {});
const reads =
yield* sql`SELECT * FROM kin_memory_reads WHERE org_id = ${orgA} ORDER BY item_id`;
yield* memory.readItemQuietly(orgA, itemId);
expect(
yield* sql`SELECT * FROM kin_memory_reads WHERE org_id = ${orgA} ORDER BY item_id`,
).toEqual(reads);
yield* memory.readItem(orgA, itemId);
expect(
yield* sql`SELECT * FROM kin_memory_reads WHERE org_id = ${orgA} ORDER BY item_id`,
).toHaveLength(1);
expect(repository.counts()).toEqual(counts);
yield* TestClock.adjust("7 weeks");
yield* memory.readItem(orgA, itemId);
Expand Down
29 changes: 22 additions & 7 deletions apps/server/src/kin/memory/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ export class Memory extends Context.Service<
orgId: KinOrgId,
id: KinMemoryItemId,
) => Effect.Effect<MemoryCache.MemoryItem, MemoryFailure | MemoryNotFound | MemoryDuplicateId>;
readonly readItemQuietly: (
orgId: KinOrgId,
id: KinMemoryItemId,
) => Effect.Effect<MemoryCache.MemoryItem, MemoryFailure | MemoryNotFound | MemoryDuplicateId>;
readonly query: (
orgId: KinOrgId,
query: MemoryQuery,
Expand Down Expand Up @@ -653,17 +657,23 @@ const make = Effect.gen(function* () {
.slice(0, q.limit === undefined ? undefined : Math.max(0, Math.floor(q.limit)));
});

const readItem = Effect.fn("Memory.readItem")(function* (orgId: KinOrgId, id: KinMemoryItemId) {
const readItem = Effect.fn("Memory.readItem")(function* (
orgId: KinOrgId,
id: KinMemoryItemId,
recordRead: boolean,
) {
const { items } = yield* load(orgId);
const matches = items.filter((item) => item.head.id === id);
const item = matches[0];
if (!item) return yield* new MemoryNotFound({ orgId, id });
if (matches.length > 1) return yield* new MemoryDuplicateId({ orgId, id });
yield* cache.read(orgId, id).pipe(
Effect.catchTags({
MemoryHistoryError: () => Effect.logWarning("Could not record memory read", { orgId, id }),
}),
);
if (recordRead)
yield* cache.read(orgId, id).pipe(
Effect.catchTags({
MemoryHistoryError: () =>
Effect.logWarning("Could not record memory read", { orgId, id }),
}),
);
return item;
});

Expand Down Expand Up @@ -826,7 +836,12 @@ const make = Effect.gen(function* () {
readIndex: Effect.fn("Memory.readIndex")((orgId) => locked(orgId, readFile(orgId, "INDEX.md"))),
readRules: Effect.fn("Memory.readRules")((orgId) => locked(orgId, readFile(orgId, "rules.md"))),
query: Effect.fn("Memory.queryLocked")((orgId, q) => locked(orgId, query(orgId, q))),
readItem: Effect.fn("Memory.readItemLocked")((orgId, id) => locked(orgId, readItem(orgId, id))),
readItem: Effect.fn("Memory.readItemLocked")((orgId, id) =>
locked(orgId, readItem(orgId, id, true)),
),
readItemQuietly: Effect.fn("Memory.readItemQuietly")((orgId, id) =>
locked(orgId, readItem(orgId, id, false)),
),
rebuildIndex: Effect.fn("Memory.rebuildIndexLocked")((orgId) =>
locked(orgId, rebuildIndex(orgId)),
),
Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/kin/memory/frontMatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ it.effect.each([
text: fixtureItem().replace("---\nInvented", "broken: [\n---\nInvented"),
valid: false,
},
{
name: "person settings",
text: fixtureItem({ tz: "America/New_York", quiet_hours: { from: "22:00", to: "07:00" } }),
valid: true,
},
{ name: "invalid person zone", text: fixtureItem({ tz: "Invalid/Zone" }), valid: true },
{
name: "invalid person hours",
text: fixtureItem({ quiet_hours: { from: "25:99", to: "morning" } }),
valid: true,
},
{ name: "invalid schema", text: fixtureItem({ trust: "administrator" }), valid: false },
{
name: "duplicate key",
Expand All @@ -68,6 +79,12 @@ it.effect.each([
expect(result._tag === "Success").toBe(valid);
if (result._tag === "Success") {
expect(result.success.frontMatter.review_by).toBe("2026-11-13");
if (text.includes("America/New_York")) {
expect(result.success.frontMatter.tz).toBe("America/New_York");
expect(result.success.frontMatter.quiet_hours).toEqual({ from: "22:00", to: "07:00" });
}
if (text.includes("Invalid/Zone")) expect(result.success.frontMatter.tz).toBeUndefined();
if (text.includes("25:99")) expect(result.success.frontMatter.quiet_hours).toBeUndefined();
expect(result.success.body).toBe("Invented fixture body.\n");
} else {
expect(result.failure._tag).toBe("MemoryItemError");
Expand Down
18 changes: 17 additions & 1 deletion apps/server/src/kin/persistence/KinMigrations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const tableNames = [
"kin_org_state",
"kin_orgs",
"kin_people",
"kin_ping_deliveries",
"kin_ping_escalations",
"kin_ping_items",
"kin_ping_ledger",
"kin_read_state",
"kin_session_bindings",
Expand Down Expand Up @@ -83,6 +86,7 @@ describe("Kin migrations", () => {
{ migration_id: 3, name: "Triggers" },
{ migration_id: 4, name: "MemoryReads" },
{ migration_id: 5, name: "OneChatOwner" },
{ migration_id: 6, name: "Pings" },
]);
assert.deepStrictEqual(
upstreamBefore.map((row) => [row.migration_id, row.name] as const),
Expand Down Expand Up @@ -127,6 +131,7 @@ describe("Kin migrations", () => {
{ migration_id: 3, name: "Triggers" },
{ migration_id: 4, name: "MemoryReads" },
{ migration_id: 5, name: "OneChatOwner" },
{ migration_id: 6, name: "Pings" },
]);
assert.deepStrictEqual(yield* upstreamHistory, upstreamBefore);
assert.deepStrictEqual(yield* sql`SELECT * FROM kin_orgs`, [
Expand All @@ -148,6 +153,8 @@ describe("Kin migrations", () => {
{ name: "idx_kin_events_queue" },
{ name: "idx_kin_events_wakeup" },
{ name: "idx_kin_people_org_person" },
{ name: "idx_kin_ping_items_item" },
{ name: "idx_kin_ping_items_pending" },
{ name: "idx_kin_shadow_entries_promotion" },
{ name: "idx_kin_shadow_entries_review" },
{ name: "idx_kin_trigger_fires_retention" },
Expand Down Expand Up @@ -192,6 +199,7 @@ describe("Kin migrations", () => {
[3, "Triggers"],
[4, "MemoryReads"],
[5, "OneChatOwner"],
[6, "Pings"],
]);
const before = yield* kinSchema;
assert.deepStrictEqual(
Expand All @@ -209,9 +217,16 @@ describe("Kin migrations", () => {
VALUES ('existing-chat', 'org', 'project_group', 0, ${timestamp})`;
yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at)
VALUES ('existing-owner', 'org', 'existing-chat', 'person', 'owner', 'owner', ${timestamp})`;
yield* sql`DROP TABLE kin_ping_deliveries`;
yield* sql`DROP TABLE kin_ping_escalations`;
yield* sql`DROP TABLE kin_ping_items`;
yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 6`;
yield* sql`DROP INDEX kin_chat_members_one_owner`;
yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 5`;
assert.deepStrictEqual(yield* runKinMigrations(), [[5, "OneChatOwner"]]);
assert.deepStrictEqual(yield* runKinMigrations(), [
[5, "OneChatOwner"],
[6, "Pings"],
]);
assert.deepStrictEqual(
yield* sql`SELECT member_id FROM kin_chat_members WHERE org_id = 'org' ORDER BY member_id`,
[{ member_id: "existing-owner" }],
Expand All @@ -228,6 +243,7 @@ describe("Kin migrations", () => {
{ migration_id: 3, name: "Triggers" },
{ migration_id: 4, name: "MemoryReads" },
{ migration_id: 5, name: "OneChatOwner" },
{ migration_id: 6, name: "Pings" },
]);
assert.deepStrictEqual(yield* runKinMigrations(), []);
assert.deepStrictEqual(yield* runMigrations(), []);
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/kin/persistence/KinMigrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Lead from "./migrations/K002_Lead.ts";
import Triggers from "./migrations/K003_Triggers.ts";
import MemoryReads from "./migrations/K004_MemoryReads.ts";
import OneChatOwner from "./migrations/K005_OneChatOwner.ts";
import Pings from "./migrations/K006_Pings.ts";

const run = Migrator.make({});
const loader = Migrator.fromRecord({
Expand All @@ -14,6 +15,7 @@ const loader = Migrator.fromRecord({
"3_Triggers": Triggers,
"4_MemoryReads": MemoryReads,
"5_OneChatOwner": OneChatOwner,
"6_Pings": Pings,
});

export const runKinMigrations = Effect.fn("KinMigrations.run")(function* () {
Expand Down
38 changes: 38 additions & 0 deletions apps/server/src/kin/persistence/migrations/K006_Pings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE kin_ping_items (
org_id TEXT NOT NULL REFERENCES kin_orgs(org_id),
person TEXT NOT NULL,
item_id TEXT NOT NULL,
request_json TEXT NOT NULL,
first_day TEXT,
first_seq INTEGER,
stopped_at INTEGER,
PRIMARY KEY (org_id, person, item_id)
)
`;
yield* sql`
CREATE TABLE kin_ping_escalations (
org_id TEXT NOT NULL REFERENCES kin_orgs(org_id),
item_id TEXT NOT NULL,
waiting_id TEXT NOT NULL REFERENCES kin_waiting(waiting_id),
escalated_at INTEGER NOT NULL,
PRIMARY KEY (org_id, item_id)
)
`;
yield* sql`CREATE INDEX idx_kin_ping_items_item ON kin_ping_items(org_id, item_id)`;
yield* sql`CREATE INDEX idx_kin_ping_items_pending ON kin_ping_items(org_id, person, item_id) WHERE stopped_at IS NULL`;
yield* sql`CREATE TABLE kin_ping_deliveries (
org_id TEXT NOT NULL REFERENCES kin_orgs(org_id),
person TEXT NOT NULL,
item_id TEXT NOT NULL,
message_id TEXT NOT NULL REFERENCES kin_messages(message_id),
seq INTEGER NOT NULL,
item_count INTEGER NOT NULL,
PRIMARY KEY (org_id, person, item_id, message_id)
)`;
});
Loading