diff --git a/apps/server/package.json b/apps/server/package.json index 3a6797d90da28..6f50e0dd24a45 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -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": { diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index fc8fa38e6e165..295686128bdc0 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -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; readonly orgs: ( identities: ReadonlyArray, ) => Effect.Effect; @@ -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; @@ -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, diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index 1c8c5d3d9a5ab..9087030e5699d 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -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"), }), diff --git a/apps/server/src/kin/lead/layer.test.ts b/apps/server/src/kin/lead/layer.test.ts index 21c669120637d..62b54d3d8a6d1 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -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"), }); diff --git a/apps/server/src/kin/memory/Memory.test.ts b/apps/server/src/kin/memory/Memory.test.ts index fb48bf9091937..02f6a25184f36 100644 --- a/apps/server/src/kin/memory/Memory.test.ts +++ b/apps/server/src/kin/memory/Memory.test.ts @@ -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); diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index fdb05b0ab5aaa..5a1531675c9ee 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -123,6 +123,10 @@ export class Memory extends Context.Service< orgId: KinOrgId, id: KinMemoryItemId, ) => Effect.Effect; + readonly readItemQuietly: ( + orgId: KinOrgId, + id: KinMemoryItemId, + ) => Effect.Effect; readonly query: ( orgId: KinOrgId, query: MemoryQuery, @@ -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; }); @@ -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)), ), diff --git a/apps/server/src/kin/memory/frontMatter.test.ts b/apps/server/src/kin/memory/frontMatter.test.ts index fc7af6477723a..1f11f63f4b8dd 100644 --- a/apps/server/src/kin/memory/frontMatter.test.ts +++ b/apps/server/src/kin/memory/frontMatter.test.ts @@ -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", @@ -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"); diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 5e2ac3b487004..41fedbd37fd51 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -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", @@ -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), @@ -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`, [ @@ -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" }, @@ -192,6 +199,7 @@ describe("Kin migrations", () => { [3, "Triggers"], [4, "MemoryReads"], [5, "OneChatOwner"], + [6, "Pings"], ]); const before = yield* kinSchema; assert.deepStrictEqual( @@ -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" }], @@ -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(), []); diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index 23c3373697ad9..845fce8d48d04 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -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({ @@ -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* () { diff --git a/apps/server/src/kin/persistence/migrations/K006_Pings.ts b/apps/server/src/kin/persistence/migrations/K006_Pings.ts new file mode 100644 index 0000000000000..f592804686ab2 --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K006_Pings.ts @@ -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) + )`; +}); diff --git a/apps/server/src/kin/triggers/pings.test.ts b/apps/server/src/kin/triggers/pings.test.ts new file mode 100644 index 0000000000000..499ba4ec9ae9d --- /dev/null +++ b/apps/server/src/kin/triggers/pings.test.ts @@ -0,0 +1,690 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + KinChatId, + KinMemoryItemId, + KinMessageId, + KinOrgId, + KinPersonId, + MemoryItemHead, +} from "@t3tools/contracts"; +import remarkParse from "remark-parse"; +import remarkGfm from "remark-gfm"; +import { unified } from "unified"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Statement from "effect/sql/Statement"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as Chat from "../chat/KinChatService.ts"; +import * as Hub from "../chat/KinChatHub.ts"; +import * as Repo from "../chat/KinChatRepository.ts"; +import * as Memory from "../memory/Memory.ts"; +import * as Cache from "../memory/MemoryCache.ts"; +import * as Persistence from "../persistence/KinPersistence.ts"; +import * as Pings from "./pings.ts"; + +const decodePerson = Schema.decodeEffect(KinPersonId); +const decodeItem = Schema.decodeEffect(KinMemoryItemId); +const decodeMessage = Schema.decodeEffect(KinMessageId); +const profileId = Schema.decodeSync(KinMemoryItemId)("person-profile"); +const orgId = Schema.decodeSync(KinOrgId)("org"); +const person = Schema.decodeSync(KinPersonId)("person"); +const owner = Schema.decodeSync(KinPersonId)("owner"); +const chatId = Schema.decodeSync(KinChatId)("chat"); +const ownerChatId = Schema.decodeSync(KinChatId)("owner-chat"); +const request = { + orgId, + person, + owner, + chatId, + ownerChatId, + itemId: Schema.decodeSync(KinMemoryItemId)("item"), + nextStep: "Send the review", +}; +const head = Schema.decodeSync(MemoryItemHead)({ + id: "item", + orgId, + path: "commitments/item.md", + kind: "commitment", + title: "Review", + status: "open", + due: null, + recorded_at: "2026-01-01", + valid_from: "2026-01-01", + invalid_at: null, + superseded_by: null, + review_by: null, + source: "fixture", + said_by: "owner", + trust: "owner", + links: [], +}); +const database = Persistence.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)); +function layer( + profile?: { tz?: string; quiet_hours?: { from: string; to: string } }, + readHead: ( + id: KinMemoryItemId, + ) => Effect.Effect = () => + Effect.succeed(head), + hubLayer = Hub.layer, +) { + const dependencies = Chat.layer.pipe( + Layer.provideMerge(hubLayer), + Layer.provideMerge(Repo.layer), + Layer.provideMerge(Cache.layer), + Layer.provideMerge(database), + ); + return Pings.layer.pipe( + Layer.provideMerge(dependencies), + Layer.provideMerge( + Layer.unwrap( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return Layer.mock(Memory.Memory)({ + readItemQuietly: (_org, id) => + Effect.gen(function* () { + assert.strictEqual( + (yield* Effect.serviceOption(sql.transactionService))._tag, + "None", + ); + const current = yield* readHead(id); + return { head: { ...current, id }, body: "" }; + }), + query: () => + Effect.gen(function* () { + assert.strictEqual( + (yield* Effect.serviceOption(sql.transactionService))._tag, + "None", + ); + return profile === undefined + ? [] + : [ + { + ...head, + id: profileId, + kind: "person", + path: "people/reviewer.md", + ...profile, + duplicate: false, + }, + ]; + }), + }); + }), + ).pipe(Layer.provide(dependencies)), + ), + ); +} +const seed = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES (${orgId}, 'Fixture', '2026-01-01T00:00:00.000Z')`; + for (const [id, handle] of [ + [person, "reviewer"], + [owner, "owner"], + ]) + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES (${id}, ${orgId}, ${handle}, ${handle}, '2026-01-01T00:00:00.000Z')`; + for (const [id, personId] of [ + [chatId, person], + [ownerChatId, owner], + ]) { + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at) VALUES (${id}, ${orgId}, 'project_group', 'Fixture', 0, '2026-01-01T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES (${id + "-member"}, ${orgId}, ${id}, 'person', ${personId}, 'owner', '2026-01-01T00:00:00.000Z')`; + } + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at) + VALUES ('lead', ${orgId}, 'Lead', 'lead', ${owner}, '2026-01-01T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) + VALUES ('lead', ${orgId}, 'Lead', 0, '{}', '[]', ${ownerChatId})`; + yield* sql`INSERT INTO kin_trigger_settings VALUES (${orgId}, 'America/New_York', '08:30', '18:30', '03:00', 0, 1, '09:00', '{"from":"22:00","to":"07:00"}')`; +}); + +describe("KinPings", () => { + it.effect("rolls back a batch without publishing its first notice", () => + Effect.gen(function* () { + const published = yield* Ref.make>([]); + yield* Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + yield* pings.put(request); + yield* sql`CREATE TEMP TRIGGER fail_ping BEFORE INSERT ON kin_ping_ledger BEGIN SELECT RAISE(ABORT, 'fixture failure'); END`; + assert.strictEqual((yield* Effect.flip(pings.sweep(orgId)))._tag, "PersistenceSqlError"); + assert.deepStrictEqual(yield* Ref.get(published), []); + assert.lengthOf( + yield* sql`SELECT message_id FROM kin_messages WHERE org_id = ${orgId} ORDER BY seq`, + 0, + ); + yield* sql`DROP TRIGGER fail_ping`; + yield* pings.sweep(orgId); + assert.lengthOf(yield* Ref.get(published), 1); + }).pipe( + Effect.provide( + layer( + undefined, + undefined, + Layer.mock(Hub.KinChatHub)({ + publish: (event) => Ref.update(published, (events) => [...events, event]), + }), + ), + ), + ); + }), + ); + + it.effect("answers only the recipient and only a reply to a multi-item ping", () => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const chat = yield* Chat.KinChatService; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + yield* pings.put(request); + yield* pings.put({ ...request, itemId: yield* decodeItem("second") }); + yield* pings.put({ ...request, person: owner, chatId: ownerChatId }); + yield* pings.sweep(orgId); + yield* chat.send( + { _tag: "person", orgId, personId: person }, + { chatId, clientMessageId: "unrelated", body: "Other topic" }, + ); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_items WHERE org_id = ${orgId} AND stopped_at IS NOT NULL ORDER BY person, item_id`, + 0, + ); + const ping = yield* sql<{ + message_id: KinMessageId; + }>`SELECT message_id FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${chatId} AND author_kind = 'system' ORDER BY seq LIMIT 1`; + yield* chat.send( + { _tag: "person", orgId, personId: person }, + { chatId, clientMessageId: "reply", body: "Done", replyTo: ping[0]!.message_id }, + ); + yield* pings.sweep(orgId).pipe( + Effect.provideService(Statement.CurrentTransformer, (statement) => + Effect.gen(function* () { + if (statement.compile()[0].includes("JOIN kin_ping_deliveries")) + assert.strictEqual( + (yield* Effect.serviceOption(sql.transactionService))._tag, + "Some", + ); + return statement; + }), + ), + ); + assert.deepStrictEqual( + yield* sql`SELECT person, item_id FROM kin_ping_items WHERE org_id = ${orgId} AND stopped_at IS NOT NULL ORDER BY person, item_id`, + [ + { person, item_id: "item" }, + { person, item_id: "second" }, + ], + ); + yield* TestClock.setTime(Date.parse("2026-11-02T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} AND day = '2026-11-02' ORDER BY person, item_id`, + 1, + ); + yield* chat.send( + { _tag: "person", orgId, personId: owner }, + { chatId: ownerChatId, clientMessageId: "single-answer", body: "Sent" }, + ); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_items WHERE org_id = ${orgId} AND stopped_at IS NULL ORDER BY person, item_id`, + 0, + ); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} AND resolved_at IS NULL ORDER BY waiting_id`, + 0, + ); + yield* pings.put(request); + yield* pings.sweep(orgId); + yield* chat.send( + { _tag: "person", orgId, personId: person }, + { chatId, clientMessageId: "reopened-answer", body: "Done again" }, + ); + yield* pings.sweep(orgId); + yield* pings.put(request); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} AND person = ${person} ORDER BY item_id`, + 3, + ); + yield* TestClock.setTime(Date.parse("2026-11-03T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} AND person = ${person} ORDER BY item_id`, + 4, + ); + }).pipe(Effect.provide(layer())), + ); + + it.effect.each(["deleted", "duplicate", "departed", "mismatch", "owner"] as const)( + "isolates $0 rows", + (scenario) => + Effect.gen(function* () { + const bad = yield* decodeItem("z-bad"); + const removed = yield* Ref.make(false); + yield* Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + yield* pings.put(request); + const other = yield* decodePerson("other"); + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES (${other}, ${orgId}, 'other', 'Other', '2026-01-01')`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) + VALUES ('other-member', ${orgId}, ${ownerChatId}, 'person', ${other}, 'member', '2026-01-01')`; + if (scenario === "mismatch") { + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) + VALUES ('extra', ${orgId}, ${ownerChatId}, 'person', ${person}, 'member', '2026-01-01') ON CONFLICT DO NOTHING RETURNING member_id`; + yield* pings.put({ ...request, itemId: bad, chatId: ownerChatId }); + } else { + yield* pings.put({ ...request, itemId: bad, person: other, chatId: ownerChatId }); + } + if (scenario === "departed") + yield* sql`UPDATE kin_chat_members SET left_at = '2026-11-01' WHERE org_id = ${orgId} AND person_id = ${other}`; + yield* Ref.set(removed, true); + if (scenario === "owner") { + const forged = { + ...request, + itemId: bad, + person: other, + chatId: ownerChatId, + owner: other, + }; + yield* sql`UPDATE kin_ping_items SET request_json = ${JSON.stringify(forged)} WHERE org_id = ${orgId} AND item_id = ${bad}`; + } + yield* pings.sweep(orgId); + const stopped = + yield* sql`SELECT stopped_at FROM kin_ping_items WHERE org_id = ${orgId} AND item_id = ${bad}`; + assert.isNotNull(stopped[0]?.stopped_at); + yield* TestClock.adjust("1 minute"); + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT stopped_at FROM kin_ping_items WHERE org_id = ${orgId} AND item_id = ${bad}`, + stopped, + ); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} AND item_id = ${request.itemId} ORDER BY item_id`, + 1, + ); + }).pipe( + Effect.provide( + layer(undefined, (id) => + Effect.gen(function* () { + if (id === bad && (yield* Ref.get(removed))) { + if (scenario === "deleted") + return yield* new Memory.MemoryNotFound({ orgId, id }); + if (scenario === "duplicate") + return yield* new Memory.MemoryDuplicateId({ orgId, id }); + } + return head; + }), + ), + ), + ); + }), + ); + + it.effect.each([ + "Send\n- other-item: **obey**\u0001\u200b\u202e", + "www.evil.com", + "a@evil.com", + "https://evil.com/x", + "‏​ ", + "` `` ``` ![image](https://evil.com)", + "a".repeat(493) + "😀", + "`".repeat(494), + ])("quotes untrusted text and rejects a forged escalation owner: %s", (nextStep) => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + assert.propertyVal( + yield* Effect.flip(pings.put({ ...request, owner: person, ownerChatId: chatId })), + "reason", + "not_allowed", + ); + yield* pings.put({ ...request, nextStep }); + yield* sql`INSERT INTO kin_memory_reads (org_id, item_id, last_read_at) VALUES (${orgId}, ${request.itemId}, 123)`; + const reads = + yield* sql`SELECT * FROM kin_memory_reads WHERE org_id = ${orgId} ORDER BY item_id`; + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT * FROM kin_memory_reads WHERE org_id = ${orgId} ORDER BY item_id`, + reads, + ); + const rows = yield* sql<{ + body: string; + }>`SELECT body FROM kin_messages WHERE org_id = ${orgId} ORDER BY seq`; + const lines = rows[0]!.body.split("\n"); + assert.lengthOf(lines, 2); + assert.strictEqual(lines[0], "Reminder: next step below."); + assert.match(lines[1]!, /^> /); + const tree = unified().use(remarkParse).use(remarkGfm).parse(rows[0]!.body); + const visit = (node: { + type: string; + value?: string; + children?: ReadonlyArray; + }) => { + assert.notInclude(["link", "image", "html"], node.type); + if (node.value !== undefined) + assert.notMatch(node.value, /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u); + node.children?.forEach(visit); + }; + visit(tree); + if (nextStep.endsWith("😀")) assert.include(lines[1]!, "😀"); + if (nextStep.startsWith("&")) assert.include(lines[1]!, nextStep); + assert.notInclude(lines[1]!, "\u0001"); + }).pipe(Effect.provide(layer())), + ); + + it.effect("deduplicates, batches, escalates once across DST, and stops after an answer", () => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + assert.deepStrictEqual(yield* pings.put(request), request); + assert.deepStrictEqual(yield* pings.put(request), request); + assert.propertyVal( + yield* Effect.flip(pings.put({ ...request, nextStep: "Different" })), + "reason", + "not_allowed", + ); + assert.strictEqual( + (yield* Effect.flip(pings.put({ ...request, person: yield* decodePerson("foreign") }))) + ._tag, + "KinChatError", + ); + assert.strictEqual( + (yield* Effect.flip(pings.put({ ...request, nextStep: " " })))._tag, + "KinChatError", + ); + const chat = yield* Chat.KinChatService; + yield* chat.send( + { _tag: "person", orgId, personId: person }, + { chatId, clientMessageId: "before", body: "Earlier unrelated message" }, + ); + yield* pings.put({ + ...request, + itemId: yield* decodeItem("item-2"), + }); + yield* Effect.all([pings.sweep(orgId), pings.sweep(orgId)], { concurrency: "unbounded" }); + const messages = yield* sql<{ + body: string; + author_kind: string; + }>`SELECT body, author_kind FROM kin_messages WHERE org_id = ${orgId} AND author_kind = 'system' ORDER BY seq`; + assert.strictEqual(messages.length, 1); + assert.strictEqual(messages[0]?.author_kind, "system"); + assert.include(messages[0]?.body ?? "", "item-2"); + const noticeRequest = { + messageId: yield* decodeMessage("activity"), + orgId, + chatId, + body: "System activity is not an answer", + }; + const notice = yield* chat.notice(noticeRequest); + assert.deepStrictEqual(yield* chat.notice(noticeRequest), notice); + assert.strictEqual( + (yield* Effect.flip(chat.notice({ ...noticeRequest, body: "Changed" })))._tag, + "KinChatError", + ); + yield* TestClock.setTime(Date.parse("2026-11-02T15:00:00Z")); + yield* pings.sweep(orgId); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 2, + ); + yield* TestClock.setTime(Date.parse("2026-11-03T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 2, + ); + yield* chat.send( + { _tag: "person", orgId, personId: person }, + { + chatId, + clientMessageId: "answer", + body: "Review sent", + replyTo: (yield* sql<{ + message_id: KinMessageId; + }>`SELECT message_id FROM kin_messages WHERE org_id = ${orgId} AND author_kind = 'system' AND chat_id = ${chatId} ORDER BY seq LIMIT 1`)[0]! + .message_id, + }, + ); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} AND resolved_at IS NULL ORDER BY waiting_id`, + 0, + ); + yield* TestClock.setTime(Date.parse("2026-11-04T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day, item_id`, + 6, + ); + }).pipe(Effect.provide(layer())), + ); + + it.effect("bounds batches and delivers the remainder on the next sweep", () => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + for (let i = 0; i < 40; i++) { + yield* pings.put({ + ...request, + itemId: yield* decodeItem(`batch-${String(i).padStart(2, "0")}`), + nextStep: "`".repeat(1000), + }); + } + yield* pings.sweep(orgId); + const first = yield* sql<{ + body: string; + }>`SELECT body FROM kin_messages WHERE org_id = ${orgId} ORDER BY seq`; + assert.lengthOf(first, 1); + assert.isAtMost(first[0]!.body.length, 16_000); + const delivered = + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY item_id`; + assert.isAbove(delivered.length, 0); + assert.isBelow(delivered.length, 40); + for (let i = 0; i < 4; i++) yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY item_id`, + 40, + ); + const messages = yield* sql<{ + body: string; + }>`SELECT body FROM kin_messages WHERE org_id = ${orgId} ORDER BY seq`; + for (const message of messages) assert.isAtMost(message.body.length, 16_000); + }).pipe(Effect.provide(layer())), + ); + + it.effect("escalates once per item across recipients and resolves on closure", () => + Effect.gen(function* () { + const current = yield* Ref.make(head); + yield* Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-10-31T14:00:00Z")); + yield* pings.put(request); + yield* pings.put({ ...request, person: owner, chatId: ownerChatId }); + yield* pings.sweep(orgId); + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 1, + ); + yield* Ref.set(current, { ...head, status: "done" as const }); + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT resolution FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + [{ resolution: "closed" }], + ); + yield* TestClock.setTime(Date.parse("2026-11-02T15:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day, person`, + 4, + ); + yield* Ref.set(current, head); + yield* pings.put(request); + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT day FROM kin_ping_ledger WHERE org_id = ${orgId} AND person = ${person} ORDER BY day`, + [{ day: "2026-10-31" }, { day: "2026-11-01" }, { day: "2026-11-02" }], + ); + }).pipe(Effect.provide(layer(undefined, () => Ref.get(current)))); + }), + ); + + it.effect("escalates passively through quiet hours and closes deleted items", () => + Effect.gen(function* () { + const deleted = yield* Ref.make(false); + yield* Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse("2026-11-01T15:00:00Z")); + yield* pings.put(request); + yield* pings.sweep(orgId); + yield* TestClock.setTime(Date.parse("2026-11-02T04:00:00Z")); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 0, + ); + yield* TestClock.setTime(Date.parse("2026-11-02T05:00:00Z")); + yield* pings.sweep(orgId); + const notices = yield* sql<{ + body: string; + }>`SELECT body FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${ownerChatId} ORDER BY seq`; + assert.lengthOf(notices, 1); + assert.include(notices[0]!.body, "reviewer:"); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day`, + 1, + ); + yield* Ref.set(deleted, true); + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT resolution FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + [{ resolution: "closed" }], + ); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_items WHERE org_id = ${orgId} AND stopped_at IS NULL ORDER BY item_id`, + 0, + ); + }).pipe( + Effect.provide( + layer(undefined, (id) => + Effect.gen(function* () { + if (yield* Ref.get(deleted)) return yield* new Memory.MemoryNotFound({ orgId, id }); + return head; + }), + ), + ), + ); + }), + ); + + it.effect("uses owner dates, not UTC dates or 24-hour intervals, across fall-back", () => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* pings.put(request); + for (const time of ["2026-11-01T04:30:00Z", "2026-11-02T04:30:00Z"]) { + yield* TestClock.setTime(Date.parse(time)); + yield* pings.sweep(orgId); + } + assert.deepStrictEqual( + yield* sql`SELECT day FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day`, + [{ day: "2026-11-01" }], + ); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 0, + ); + yield* TestClock.setTime(Date.parse("2026-11-02T05:00:00Z")); + yield* pings.sweep(orgId); + assert.deepStrictEqual( + yield* sql`SELECT day FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day`, + [{ day: "2026-11-01" }, { day: "2026-11-02" }], + ); + assert.lengthOf( + yield* sql`SELECT waiting_id FROM kin_waiting WHERE org_id = ${orgId} ORDER BY waiting_id`, + 1, + ); + }).pipe(Effect.provide(layer({ quiet_hours: { from: "00:00", to: "00:00" } }))), + ); + + it.effect.each([ + { + name: "overnight start", + time: "2026-03-08T03:00:00Z", + quiet: true, + profile: { tz: "America/New_York", quiet_hours: { from: "22:00", to: "07:00" } }, + }, + { name: "overnight before end", time: "2026-03-08T10:59:00Z", quiet: true, profile: undefined }, + { + name: "daytime quiet window", + time: "2026-03-08T13:00:00Z", + quiet: true, + profile: { quiet_hours: { from: "08:00", to: "10:00" } }, + }, + { + name: "equal bounds disable quiet hours", + time: "2026-03-08T03:00:00Z", + quiet: false, + profile: { quiet_hours: { from: "00:00", to: "00:00" } }, + }, + { + name: "DST quiet end", + time: "2026-03-08T11:00:00Z", + quiet: false, + profile: { tz: "America/New_York", quiet_hours: { from: "22:00", to: "07:00" } }, + }, + { + name: "invalid zone falls back", + time: "2026-03-08T01:00:00Z", + quiet: false, + profile: { tz: "Invalid/Zone" }, + }, + { name: "missing person file", time: "2026-03-08T03:00:00Z", quiet: true, profile: undefined }, + ])("$name", (scenario) => + Effect.gen(function* () { + yield* seed; + const pings = yield* Pings.KinPings; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(Date.parse(scenario.time)); + yield* pings.put(request); + yield* pings.sweep(orgId); + assert.lengthOf( + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY item_id`, + scenario.quiet ? 0 : 1, + ); + if (scenario.quiet) { + // Reconstruct the service against the same durable database, as after restart. + yield* TestClock.setTime(Date.parse("2026-03-08T14:00:00Z")); + yield* Effect.gen(function* () { + yield* (yield* Pings.KinPings).sweep(orgId); + }).pipe(Effect.provide(Pings.layer)); + const ledger = yield* sql<{ + day: string; + }>`SELECT day FROM kin_ping_ledger WHERE org_id = ${orgId} ORDER BY day`; + assert.deepStrictEqual(ledger, [{ day: "2026-03-08" }]); + } + }).pipe(Effect.provide(layer(scenario.profile))), + ); +}); diff --git a/apps/server/src/kin/triggers/pings.ts b/apps/server/src/kin/triggers/pings.ts new file mode 100644 index 0000000000000..aff49b6764027 --- /dev/null +++ b/apps/server/src/kin/triggers/pings.ts @@ -0,0 +1,387 @@ +import { + KIN_MESSAGE_BODY_MAX_LENGTH, + KinChatError, + KinChatId, + KinMemoryItemId, + KinMessageId, + KinOrgId, + KinPersonId, + KinTriggerSettings, + KinWaitingId, +} from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlError from "effect/sql/SqlError"; +import { PersistenceSqlError, toPersistenceSqlError } from "../../persistence/Errors.ts"; +import * as Chat from "../chat/KinChatService.ts"; +import * as Memory from "../memory/Memory.ts"; +import * as Cache from "../memory/MemoryCache.ts"; + +const text = Schema.String.check( + Schema.isTrimmed(), + Schema.isMinLength(1), + Schema.isMaxLength(2000), +); +const Request = Schema.Struct({ + orgId: KinOrgId, + person: KinPersonId, + itemId: KinMemoryItemId, + chatId: KinChatId, + owner: KinPersonId, + ownerChatId: KinChatId, + nextStep: text, +}); +type Request = typeof Request.Type; +const decodeRequest = Schema.decodeUnknownEffect(Request); +const encodeRequest = Schema.encodeEffect(Schema.fromJsonString(Request)); +const decodeStored = Schema.decodeUnknownEffect(Schema.fromJsonString(Request)); +const decodeQuiet = Schema.decodeUnknownOption(KinTriggerSettings.fields.quietHours); +const decodeJsonQuiet = Schema.decodeUnknownOption( + Schema.fromJsonString(KinTriggerSettings.fields.quietHours), +); +const decodeMessageId = Schema.decodeUnknownEffect(KinMessageId); +const decodeWaitingId = Schema.decodeUnknownEffect(KinWaitingId); +const missing = new KinChatError({ reason: "not_found", message: "Kin record not found." }); +const conflict = new KinChatError({ reason: "not_allowed", message: "Ping retry conflict." }); +const ownerMismatch = new KinChatError({ + reason: "not_allowed", + message: "Ping owner does not match the active lead.", +}); +const invalid = new KinChatError({ reason: "invalid_state", message: "Invalid ping input." }); +type Error = + | PersistenceSqlError + | Effect.Error> + | Effect.Error> + | Effect.Error>; + +export class KinPings extends Context.Service< + KinPings, + { + readonly put: (input: Request) => Effect.Effect; + readonly sweep: (orgId: KinOrgId) => Effect.Effect; + } +>()("t3/kin/triggers/pings/KinPings") {} + +type Row = { + person: string; + item_id: string; + request_json: string; + first_day: string | null; + first_seq: number | null; + stopped_at: number | null; +}; + +function localParts(now: number, zone: string) { + return DateTime.toParts(DateTime.makeZonedUnsafe(now, { timeZone: zone })); +} +function ownerDay(now: number, zone: string) { + const p = localParts(now, zone); + return `${p.year}-${String(p.month).padStart(2, "0")}-${String(p.day).padStart(2, "0")}`; +} +function validZone(zone: string | undefined, fallback: string) { + if (zone === undefined) return fallback; + try { + DateTime.makeZonedUnsafe(0, { timeZone: zone }); + return zone; + } catch { + return fallback; + } +} +function isQuiet(now: number, zone: string, hours: { readonly from: string; readonly to: string }) { + const p = localParts(now, zone); + const time = `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}`; + return hours.from < hours.to + ? time >= hours.from && time < hours.to + : hours.from > hours.to && (time >= hours.from || time < hours.to); +} + +function quoted(value: string) { + const content = Array.from(value.replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/gu, " ")) + .slice(0, 500) + .join(""); + const longestRun = Math.max( + 0, + ...Array.from(content.matchAll(/`+/g), (match) => match[0].length), + ); + const fence = "`".repeat(longestRun + 1); + return `> ${fence} ${content} ${fence}`; +} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const chat = yield* Chat.KinChatService; + const memory = yield* Memory.Memory; + const cache = yield* Cache.MemoryCache; + const transaction = (effect: Effect.Effect) => + sql + .withTransaction(effect) + .pipe( + Effect.mapError((cause) => + SqlError.isSqlError(cause) ? toPersistenceSqlError("KinPings.transaction")(cause) : cause, + ), + ); + const validate = Effect.fn("KinPings.validate")(function* (r: Request) { + for (const [person, chatId] of [ + [r.person, r.chatId], + [r.owner, r.ownerChatId], + ] as const) { + const rows = + yield* sql`SELECT p.person_id FROM kin_people p JOIN kin_chat_members m ON m.org_id = p.org_id AND m.person_id = p.person_id + WHERE p.org_id = ${r.orgId} AND p.person_id = ${person} AND m.chat_id = ${chatId} AND m.left_at IS NULL ORDER BY m.member_id`; + if (rows.length === 0) return yield* missing; + } + }); + const checkOwner = Effect.fn("KinPings.checkOwner")(function* (r: Request) { + const owners = yield* sql<{ owner_person_id: string; owner_chat_id: string }>` + SELECT a.owner_person_id, l.owner_chat_id FROM kin_leads l + JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id + WHERE l.org_id = ${r.orgId} AND a.retired_at IS NULL ORDER BY l.agent_id`; + if ( + owners.length !== 1 || + owners[0]?.owner_person_id !== r.owner || + owners[0]?.owner_chat_id !== r.ownerChatId + ) + return yield* ownerMismatch; + }); + const stop = Effect.fn("KinPings.stop")(function* ( + r: Request, + now: number, + closed: boolean, + resolution: "closed" | "answered" = closed ? "closed" : "answered", + ) { + yield* sql`UPDATE kin_ping_items SET stopped_at = ${now} WHERE org_id = ${r.orgId} AND item_id = ${r.itemId} + AND (${closed ? 1 : 0} OR person = ${r.person})`; + const pending = + yield* sql`SELECT person FROM kin_ping_items WHERE org_id = ${r.orgId} AND item_id = ${r.itemId} AND stopped_at IS NULL ORDER BY person`; + if (pending.length > 0) return; + const escalations = yield* sql<{ + waiting_id: string; + }>`SELECT waiting_id FROM kin_ping_escalations WHERE org_id = ${r.orgId} AND item_id = ${r.itemId} ORDER BY item_id`; + if (escalations[0]) + yield* chat.resolveNotice({ + orgId: r.orgId, + waitingId: yield* decodeWaitingId(escalations[0].waiting_id).pipe( + Effect.mapError(() => invalid), + ), + resolution, + }); + }); + return KinPings.of({ + put: Effect.fn("KinPings.put")(function* (input) { + const r = yield* decodeRequest(input).pipe(Effect.mapError(() => invalid)); + const item = yield* memory + .readItemQuietly(r.orgId, r.itemId) + .pipe(Effect.catchTags({ MemoryNotFound: () => missing })); + const json = yield* encodeRequest(r).pipe(Effect.mapError(() => invalid)); + return yield* transaction( + Effect.gen(function* () { + yield* checkOwner(r); + yield* validate(r); + const rows = + yield* sql`SELECT * FROM kin_ping_items WHERE org_id = ${r.orgId} AND person = ${r.person} AND item_id = ${r.itemId} ORDER BY item_id`; + const previous = rows[0]; + if ( + previous?.stopped_at != null && + item.head.status === "open" && + item.head.invalid_at === null + ) { + yield* sql`DELETE FROM kin_ping_deliveries WHERE org_id = ${r.orgId} AND person = ${r.person} AND item_id = ${r.itemId}`; + yield* sql`DELETE FROM kin_ping_escalations WHERE org_id = ${r.orgId} AND item_id = ${r.itemId} AND waiting_id IN + (SELECT waiting_id FROM kin_waiting WHERE org_id = ${r.orgId} AND resolved_at IS NOT NULL ORDER BY waiting_id)`; + yield* sql`UPDATE kin_ping_items SET request_json = ${json}, stopped_at = NULL, first_day = NULL, first_seq = NULL + WHERE org_id = ${r.orgId} AND person = ${r.person} AND item_id = ${r.itemId}`; + } else { + if (previous && previous.request_json !== json) return yield* conflict; + yield* sql`INSERT INTO kin_ping_items (org_id, person, item_id, request_json) + VALUES (${r.orgId}, ${r.person}, ${r.itemId}, ${json}) ON CONFLICT DO NOTHING RETURNING item_id`; + } + return r; + }), + ); + }), + sweep: Effect.fn("KinPings.sweep")( + function* (orgId) { + const now = yield* Clock.currentTimeMillis; + const zone = yield* cache.ownerTimeZone(orgId); + const day = ownerDay(now, zone); + const settings = yield* sql<{ + quiet_hours_json: string; + }>`SELECT quiet_hours_json FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id`; + const defaultHours = decodeJsonQuiet(settings[0]?.quiet_hours_json); + const hours = + defaultHours._tag === "Some" ? defaultHours.value : { from: "21:00", to: "08:00" }; + const people = yield* memory.query(orgId, { kind: "person", excludeInvalid: true }); + const rows = + yield* sql`SELECT * FROM kin_ping_items WHERE org_id = ${orgId} AND stopped_at IS NULL ORDER BY person, item_id`; + const candidates: Array<{ + row: Row; + request: Request; + closed: boolean; + handle: string; + quiet: boolean; + }> = []; + for (const row of rows) { + const result = yield* Effect.gen(function* () { + const r = yield* decodeStored(row.request_json).pipe(Effect.mapError(() => invalid)); + if (r.orgId !== orgId || r.person !== row.person || r.itemId !== row.item_id) + return yield* invalid; + const item = yield* memory + .readItemQuietly(orgId, r.itemId) + .pipe(Effect.catchTags({ MemoryNotFound: () => Effect.succeed(null) })); + const person = yield* sql<{ + handle: string; + }>`SELECT handle FROM kin_people WHERE org_id = ${orgId} AND person_id = ${r.person} ORDER BY person_id`; + const profile = people.find( + (p) => !p.duplicate && p.path === `people/${person[0]?.handle}.md`, + ); + const personalHours = decodeQuiet(profile?.quiet_hours); + return { + row, + request: r, + closed: item === null || item.head.status !== "open" || item.head.invalid_at !== null, + handle: person[0]?.handle ?? "member", + quiet: isQuiet( + now, + validZone(profile?.tz, zone), + personalHours._tag === "Some" ? personalHours.value : hours, + ), + }; + }).pipe(Effect.result); + if (result._tag === "Failure") { + if ( + result.failure._tag === "MemoryDuplicateId" || + result.failure._tag === "KinChatError" + ) { + const stopped = + yield* sql`UPDATE kin_ping_items SET stopped_at = ${now} WHERE org_id = ${orgId} AND person = ${row.person} AND item_id = ${row.item_id} AND stopped_at IS NULL AND request_json = ${row.request_json} AND first_seq IS ${row.first_seq} RETURNING item_id`; + if (stopped.length === 0) continue; + } + yield* Effect.logWarning("Kin ping row skipped", { + orgId, + person: row.person, + itemId: row.item_id, + reason: result.failure._tag, + }); + continue; + } + candidates.push(result.success); + } + yield* transaction( + Effect.gen(function* () { + const batches = new Map(); + for (const candidate of candidates) { + const { row, request: r, closed } = candidate; + const current = + yield* sql`SELECT * FROM kin_ping_items WHERE org_id = ${orgId} AND person = ${r.person} AND item_id = ${r.itemId} AND stopped_at IS NULL ORDER BY item_id`; + if ( + !current[0] || + current[0].request_json !== row.request_json || + current[0].first_seq !== row.first_seq + ) + continue; + const replies = + yield* sql`SELECT m.message_id FROM kin_messages m JOIN kin_ping_deliveries d + ON d.org_id = m.org_id AND d.person = ${r.person} AND d.item_id = ${r.itemId} + WHERE m.org_id = ${orgId} AND m.chat_id = ${r.chatId} AND m.author_person_id = ${r.person} + AND m.author_kind = 'human' AND m.status = 'posted' AND m.seq > d.seq + AND (m.reply_to = d.message_id OR d.item_count = 1) ORDER BY m.seq LIMIT 1`; + + if (closed || replies.length > 0) { + yield* stop(r, now, closed); + continue; + } + const valid = yield* checkOwner(r).pipe(Effect.andThen(validate(r)), Effect.result); + if (valid._tag === "Failure") { + if (valid.failure._tag === "KinChatError") yield* stop(r, now, false, "closed"); + yield* Effect.logWarning("Kin ping destination skipped", { + orgId, + person: r.person, + itemId: r.itemId, + reason: valid.failure._tag, + }); + continue; + } + const batch = batches.get(r.person) ?? []; + if (batch[0] && batch[0].request.chatId !== r.chatId) { + yield* stop(r, now, false, "closed"); + yield* Effect.logWarning("Kin ping chat mismatch", { + orgId, + person: r.person, + itemId: r.itemId, + reason: "chat_mismatch", + }); + continue; + } + batch.push(candidate); + batches.set(r.person, batch); + } + for (const candidates of batches.values()) { + const batch = []; + let body = "Reminder: next step below."; + for (const candidate of candidates) { + const { row, request: r, handle } = candidate; + const pending = + yield* sql`SELECT person FROM kin_ping_items WHERE org_id = ${orgId} AND person = ${r.person} AND item_id = ${r.itemId} AND stopped_at IS NULL ORDER BY person`; + if (!pending.length) continue; + let escalatedAt: number | null = null; + const escalation = + yield* sql`SELECT waiting_id FROM kin_ping_escalations WHERE org_id = ${orgId} AND item_id = ${r.itemId} ORDER BY item_id`; + if (row.first_day !== null && row.first_day < day && !escalation.length) { + const notice = yield* chat.notice({ + messageId: yield* decodeMessageId(SecureRandom.uuidV4Unsafe()).pipe( + Effect.orDie, + ), + orgId, + chatId: r.ownerChatId, + waitingFor: r.owner, + body: `Waiting for a reply: next step below.\n${quoted(`${handle}: ${r.itemId}: ${r.nextStep}`)}`, + }); + if (!notice.waiting) return yield* invalid; + escalatedAt = now; + yield* sql`INSERT INTO kin_ping_escalations (org_id, item_id, waiting_id, escalated_at) VALUES (${orgId}, ${r.itemId}, ${notice.waiting.waitingId}, ${now}) ON CONFLICT DO NOTHING RETURNING item_id`; + } + if (candidate.quiet) continue; + const sent = + yield* sql`SELECT item_id FROM kin_ping_ledger WHERE org_id = ${orgId} AND person = ${r.person} AND item_id = ${r.itemId} AND day = ${day} ORDER BY item_id`; + if (!sent.length) { + const line = `\n${quoted(`${r.itemId}: ${r.nextStep}`)}`; + if (body.length + line.length > KIN_MESSAGE_BODY_MAX_LENGTH) continue; + body += line; + batch.push({ ...candidate, escalatedAt }); + } + } + const first = batch[0]; + if (!first) continue; + const { message } = yield* chat.notice({ + messageId: yield* decodeMessageId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie), + orgId, + chatId: first.request.chatId, + body, + }); + for (const { request: r, escalatedAt } of batch) { + yield* sql`INSERT INTO kin_ping_deliveries (org_id, person, item_id, message_id, seq, item_count) + VALUES (${orgId}, ${r.person}, ${r.itemId}, ${message.messageId}, ${message.seq}, ${batch.length}) ON CONFLICT DO NOTHING RETURNING item_id`; + yield* sql`INSERT INTO kin_ping_ledger (org_id, person, item_id, day, pinged_at, escalated_at) VALUES (${orgId}, ${r.person}, ${r.itemId}, ${day}, ${now}, ${escalatedAt}) ON CONFLICT DO NOTHING RETURNING item_id`; + yield* sql`UPDATE kin_ping_items SET first_day = COALESCE(first_day, ${day}), first_seq = COALESCE(first_seq, ${message.seq}) WHERE org_id = ${orgId} AND person = ${r.person} AND item_id = ${r.itemId}`; + } + } + }), + ); + }, + (effect) => + effect.pipe( + Effect.mapError((cause) => + SqlError.isSqlError(cause) ? toPersistenceSqlError("KinPings.sweep")(cause) : cause, + ), + ), + ), + }); +}); + +export const layer = Layer.effect(KinPings, make); diff --git a/docs/kin/specs/chat.md b/docs/kin/specs/chat.md index 5cc4550881f78..7ff4be15d1f4d 100644 --- a/docs/kin/specs/chat.md +++ b/docs/kin/specs/chat.md @@ -162,6 +162,7 @@ export const KinMessage = Schema.Struct({ - **Mentions:** each mentioned member must still be active in the same org and chat, checked inside the send transaction; mentions of members who have left are refused. - **Idempotency:** unique `(chat_id, author_member_id, client_message_id)`. An identical retry returns the first insert; a changed retry (body, mentions, replyTo, or intent) fails `not_allowed`. - **Agent posts** come only through the Kin MCP tool `kin_chat_post` (CHAT-7). The author is built from `KinIdentity.resolveAgent`. Agent text is never trusted as a claim about authority (section 9.3); that rule lives in the approvals spec, but the chat never offers a way to make agent text look human. +- **System-authored notices:** server-only code templates, not model-authored instructions. Untrusted item text appears only as a single quoted line per item: remove newlines and control characters, strip bidi and zero-width characters, truncate by code point, and quote in a padded inline code span with a backtick fence longer than any backtick run in the text. Never interpolate untrusted text into the template instructions. - **Citable link:** `kinMessageLink({ orgId, chatId, messageId })` returns `kin-chat:////`. kin-memory items use it as `source`. - **Deletion** sets `status: "deleted"` and clears `body`. Purge and retention are phase 5 (org policy). diff --git a/docs/kin/specs/triggers.md b/docs/kin/specs/triggers.md index 3c1a796e700aa..c60e8a88e4621 100644 --- a/docs/kin/specs/triggers.md +++ b/docs/kin/specs/triggers.md @@ -228,11 +228,15 @@ armed ──heads_up fire──▶ recheck ──changed──▶ asked (decis - **Idempotent start.** Starting is a Work-class action keyed by `fireId`, so a replay can't start two workers. - **Bring it up early.** When a message touches the topic before the due time, the lead mentions it (LEAD, using the cache). The Monday morning brief lists deferrals due this week. -**Follow-ups.** A ping with no answer creates a follow-up trigger (`followup`, `once`, next working morning at the owner's brief time). That is the "follow-up = a deferral created by a ping" row of section 6. +**Follow-ups (deferred to TRIG-8/10; not implemented by TRIG-11).** A ping with no answer creates a follow-up trigger (`followup`, `once`, next working morning at the owner's brief time). That is the "follow-up = a deferral created by a ping" row of section 6. ### Pings -`kin_ping_ledger(org_id, person, item_id, day)` carries a unique key, so a person is pinged at most once per item per owner day. Pings to one person within one sweep are batched into one message. Quiet hours come from `people/.md` (`tz`, `quiet_hours`) or the org default; a ping due in quiet hours waits for its end. Every ping names a next step. A second day without an answer escalates once to the owner's **Waiting on you**. Delivery goes through the chat service (CHAT). +`kin_ping_ledger(org_id, person, item_id, day)` carries a unique key, so a person is pinged at most once per item per owner day. Pings to one person within one sweep are batched into one message, up to the 16,000-character body limit; overflow goes out on later sweeps. Quiet hours come from `people/.md` (`tz`, `quiet_hours`) or the org default; a ping due in quiet hours waits for its end. Every ping names a next step. A second day without an answer escalates once to the owner's **Waiting on you**, ignoring quiet hours because Waiting on you is passive. Delivery goes through the chat service (CHAT). + +TRIG-11 persists requests in `kin_ping_items` before delivery; quiet sweeps leave them pending, with no sent ledger row. Each later sweep rechecks the current owner day, item state and person settings. Delivery and the sent ledger commit in one SQLite transaction, so restart retries cannot duplicate a committed batch. Equal quiet-hour bounds disable quiet hours; windows include the start and exclude the end. Missing or invalid person zones use the org zone; missing or invalid windows use the org quiet hours (21:00–08:00 before settings exist). + +An answer is a posted human message by that recipient replying (`reply_to`) to a ping containing the item, or any later message by that recipient in the chat when that ping contained exactly one item. Reads, system notices and agent messages are not answers. Answering stops only that recipient's item; other recipients stop through their own answers or item closure. A non-open, invalid or deleted item stops all recipients. The escalation resolves when the item closes or no recipients remain pending. A new `put` for a stopped, open item starts a fresh lifecycle for that recipient, resetting delivery membership but preserving the daily ledger: at most once per item per owner day; resolved escalation anchors can then be replaced. Day two means a later owner-calendar date, not 24 elapsed hours. Notices are server-only `KinChatService.notice` system messages, never model-authored or human-impersonated posts. Watchdog and deferral callers will compose the ping service with Memory; TRIG-11 starts no background sweeper. ### Routines (`fixed_time` in the owner's zone) diff --git a/packages/contracts/src/kinChat.ts b/packages/contracts/src/kinChat.ts index b482c6ad1d4c2..7804928709471 100644 --- a/packages/contracts/src/kinChat.ts +++ b/packages/contracts/src/kinChat.ts @@ -308,10 +308,11 @@ export const KinChatHistoryResult = Schema.Struct({ hasMore: Schema.Boolean, }); export type KinChatHistoryResult = typeof KinChatHistoryResult.Type; +export const KIN_MESSAGE_BODY_MAX_LENGTH = 16_000; export const KinMessagesSendInput = Schema.Struct({ chatId: KinChatId, clientMessageId: TrimmedNonEmptyString, - body: MessageBody.check(isNonBlankBody, Schema.isMaxLength(16_000)), + body: MessageBody.check(isNonBlankBody, Schema.isMaxLength(KIN_MESSAGE_BODY_MAX_LENGTH)), mentions: Schema.optional(Schema.Array(KinMemberId)), replyTo: Schema.optional(KinMessageId), }); diff --git a/packages/contracts/src/kinLead.ts b/packages/contracts/src/kinLead.ts index bb00eb5676a31..c3ec57063bcd5 100644 --- a/packages/contracts/src/kinLead.ts +++ b/packages/contracts/src/kinLead.ts @@ -1,3 +1,4 @@ +import * as Effect from "effect/Effect"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -17,6 +18,7 @@ import { KinOrgId, KinPersonId, } from "./kinChat.ts"; +import { TimeOfDay, TimeZone } from "./kinTime.ts"; import { ModelSelection } from "./modelSelection.ts"; import { ScheduledTaskWebhookDeliveryId } from "./scheduledTask.ts"; @@ -78,6 +80,14 @@ export const MemoryItemFrontMatter = Schema.Struct({ due: Schema.NullOr(Schema.String), on_due: Schema.optional(Schema.Literals(["remind", "start", "ask", "chase"])), owner: Schema.optional(TrimmedNonEmptyString), + tz: Schema.optional( + Schema.UndefinedOr(TimeZone).pipe(Schema.catchDecoding(() => Effect.succeedSome(undefined))), + ), + quiet_hours: Schema.optional( + Schema.UndefinedOr(Schema.Struct({ from: TimeOfDay, to: TimeOfDay })).pipe( + Schema.catchDecoding(() => Effect.succeedSome(undefined)), + ), + ), recorded_at: Schema.String, valid_from: Schema.String, invalid_at: Schema.NullOr(Schema.String), diff --git a/packages/contracts/src/kinTime.ts b/packages/contracts/src/kinTime.ts new file mode 100644 index 0000000000000..7e18db7d99d63 --- /dev/null +++ b/packages/contracts/src/kinTime.ts @@ -0,0 +1,16 @@ +import * as Schema from "effect/Schema"; +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ScheduledTaskUpsertSchedule } from "./scheduledTask.ts"; + +export const TimeOfDay = ScheduledTaskUpsertSchedule.members[1].fields.timeOfDay; + +export const TimeZone = TrimmedNonEmptyString.check( + Schema.makeFilter((timeZone) => { + try { + const resolved = new Intl.DateTimeFormat("en", { timeZone }).resolvedOptions().timeZone; + return !/^[+-]/.test(resolved) || "Expected an IANA time zone."; + } catch { + return "Expected an IANA time zone."; + } + }), +); diff --git a/packages/contracts/src/kinTriggers.ts b/packages/contracts/src/kinTriggers.ts index 98c6eabc94daa..afdeaae9e589a 100644 --- a/packages/contracts/src/kinTriggers.ts +++ b/packages/contracts/src/kinTriggers.ts @@ -5,21 +5,11 @@ import { KinOrgId, KinPersonId } from "./kinChat.ts"; import { CanonicalUtcTimestamp, KinMemoryItemId } from "./kinLead.ts"; import { ScheduledTaskUpsertSchedule, ScheduledTaskWebhookDeliveryId } from "./scheduledTask.ts"; +import { TimeOfDay, TimeZone } from "./kinTime.ts"; + const [interval, fixedTime, once] = ScheduledTaskUpsertSchedule.members; -const TimeOfDay = fixedTime.fields.timeOfDay; const Weekday = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 6 })); -const TimeZone = TrimmedNonEmptyString.check( - Schema.makeFilter((timeZone) => { - try { - const resolved = new Intl.DateTimeFormat("en", { timeZone }).resolvedOptions().timeZone; - return !/^[+-]/.test(resolved) || "Expected an IANA time zone."; - } catch { - return "Expected an IANA time zone."; - } - }), -); - export const KinTriggerFireId = TrimmedNonEmptyString.pipe(Schema.brand("KinTriggerFireId")); export type KinTriggerFireId = typeof KinTriggerFireId.Type; export const KinWebhookSourceId = TrimmedNonEmptyString.pipe(Schema.brand("KinWebhookSourceId")); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 697191c410823..ca3e277e64900 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1007,6 +1007,15 @@ importers: graphql: specifier: 16.14.1 version: 16.14.1 + remark-gfm: + specifier: 'catalog:' + version: 4.0.1(supports-color@8.1.1) + remark-parse: + specifier: 'catalog:' + version: 11.0.0(supports-color@8.1.1) + unified: + specifier: 'catalog:' + version: 11.0.5 vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)