From 9785307845930a6dd1c8beba83ffa739bdafc632 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:49:22 +0530 Subject: [PATCH] =?UTF-8?q?fix(kin):=20save=20a=20join=20failure=20line=20?= =?UTF-8?q?with=20the=20unanswered=20message=E2=80=99s=20expiry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A join can expire an unanswered ask below the history floor. Write its plain notice in that transaction and publish after commit. Never replay the hidden text or add a notice to an already answered ask. People-change: When a new reader cannot see an interrupted ask, Kin tells the asker to send it again without showing its words. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/chat/KinGroups.test.ts | 80 ++++++++++--- apps/server/src/kin/lead/ChatSharing.ts | 87 +++++++------- apps/server/src/kin/lead/WakeupRunner.test.ts | 72 ++++++++++-- apps/server/src/kin/people/KinPeople.test.ts | 2 +- apps/server/src/kin/people/KinPeople.ts | 2 +- .../src/kin/reply/KinReplyBridge.test.ts | 14 +-- apps/server/src/kin/reply/KinReplyBridge.ts | 2 +- apps/server/src/kin/team/KinTeam.test.ts | 108 ++++++++++++++---- verification/kin/reply/README.md | 2 + verification/kin/reply/Reply.tla | 8 +- verification/kin/reply/view.ts | 23 +++- 11 files changed, 283 insertions(+), 117 deletions(-) diff --git a/apps/server/src/kin/chat/KinGroups.test.ts b/apps/server/src/kin/chat/KinGroups.test.ts index ce483c062a165..846066600933a 100644 --- a/apps/server/src/kin/chat/KinGroups.test.ts +++ b/apps/server/src/kin/chat/KinGroups.test.ts @@ -854,27 +854,26 @@ it.effect( ["expired"], ); // What it was asked goes unanswered, and the chat hears it once, where Sam reads too. - const told = "Tech lead didn't reply: someone joined before it answered. Send it again."; + const told = "A message sent just before someone joined went unanswered. Send it again."; const lines = sql<{ messageId: KinMessageId; body: string }>`SELECT message_id AS "messageId", body FROM kin_messages WHERE chat_id = ${chatId} AND author_kind = 'system' ORDER BY seq`; assert.deepStrictEqual( (yield* lines).map((row) => row.body), - [told], + [told, told, told], ); assert.deepStrictEqual( (yield* chats.history([sam], { chatId, beforeSeq: 1000, limit: 50 })).messages.map( (message) => message.body, ), - [told], + [told, told, told], ); // The join handled again, or its line retried, posts nothing more. const again = yield* sql.withTransaction( ChatSharing.onPersonJoined({ orgId, chatId, personId: sam.personId }), ); assert.deepStrictEqual(again.stopped, []); - yield* ChatSharing.tellStopped({ orgId, chatId, lines: yield* lines }); - assert.lengthOf(yield* lines, 1); + assert.lengthOf(yield* lines, 3); yield* queue.finish({ orgId, wakeupId: running.wakeupId, status: "completed" }); // Said after Sam joined, and a tap there on the card from before: only the first is his. const after = yield* say(sam, chatId, "Invented-sam-question"); @@ -883,7 +882,7 @@ it.effect( WHERE message_id = ${tap.messageId}`; const turn = yield* wake(tech); yield* sql`UPDATE kin_wakeups SET audience = 'shared' WHERE wakeup_id = ${turn.wakeupId}`; - assert.deepStrictEqual(yield* seen(turn), [told, "Invented-sam-question"]); + assert.deepStrictEqual(yield* seen(turn), [told, told, told, "Invented-sam-question"]); assert.deepStrictEqual( (yield* chats.read(turn, { chatId, afterSeq: after.seq - 1, limit: 1 })).map( (message) => message.messageId, @@ -899,19 +898,19 @@ it.effect.each([ joiner: "member", before: "a tool call", lines: [ - "Tech lead didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.", + "A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.", ], }, { joiner: "member", before: "still queued", - lines: ["Tech lead didn't reply: someone joined before it answered. Send it again."], + lines: ["A message sent just before someone joined went unanswered. Send it again."], }, // `historyFloor` exempts only the chat's own owner member: a co-owner's join moves it too. { joiner: "co_owner", before: "nothing", - lines: ["Tech lead didn't reply: someone joined before it answered. Send it again."], + lines: ["A message sent just before someone joined went unanswered. Send it again."], }, ] as const)( "a join that leaves a person's question unanswered says so in the chat once ($joiner, $before)", @@ -930,14 +929,18 @@ it.effect.each([ if (before === "a tool call" && running !== undefined) yield* sql`INSERT INTO kin_lead_tool_calls (org_id, wakeup_id, call_key, request_hash) VALUES (${orgId}, ${running.wakeupId}, 'item:task-1', 'fixture-hash')`; - yield* groups.addMember([owner], { - chatId, - principal: { _tag: "person", personId: priya.personId }, - }); - assert.deepStrictEqual( - yield* sql`SELECT body FROM kin_messages WHERE chat_id = ${chatId} + yield* sql.withTransaction( + Effect.gen(function* () { + yield* groups.addMember([owner], { + chatId, + principal: { _tag: "person", personId: priya.personId }, + }); + assert.deepStrictEqual( + yield* sql`SELECT body FROM kin_messages WHERE chat_id = ${chatId} AND author_kind = 'system' ORDER BY seq`, - lines.map((body) => ({ body })), + lines.map((body) => ({ body })), + ); + }), ); // After the line, the stopped run failing or a restart neither answers nor tells it again. if (running !== undefined && before === "a tool call") @@ -958,13 +961,53 @@ it.effect.each([ }).pipe(Effect.provide(layer)), ); +it.effect.each([false, true])( + "one join handles a message sent to two leads (already answered: %s)", + (answered) => + Effect.gen(function* () { + const { sql, groups, queue, owner, orgId, tech, growth, priya, say, wake, events } = + yield* seed; + const { chatId } = yield* groups.create([owner], { + orgId, + title: "Planning", + agentIds: [tech, growth], + personIds: [], + }); + const { members } = yield* groups.members([owner], { chatId }); + const mentions = members + .filter((member) => member.principal._tag === "agent") + .map(({ memberId }) => memberId); + const ask = yield* say(owner, chatId, "What goes on the launch board?", mentions); + const running = yield* wake(tech); + if (answered) { + const earlier = yield* wake(growth); + yield* sql`UPDATE kin_events SET replied_at = 1 WHERE wakeup_id = ${earlier.wakeupId}`; + yield* queue.finish({ orgId, wakeupId: earlier.wakeupId, status: "completed" }); + } + yield* groups.addMember([owner], { + chatId, + principal: { _tag: "person", personId: priya.personId }, + }); + yield* queue.finish({ orgId, wakeupId: running.wakeupId, status: "interrupted" }); + assert.sameMembers( + (yield* events).filter((row) => row.messageId === ask.messageId).map(({ state }) => state), + answered ? ["expired", "done"] : ["expired", "expired"], + ); + assert.lengthOf( + yield* sql`SELECT 1 FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${chatId} + AND kind = 'system'`, + answered ? 0 : 1, + ); + }).pipe(Effect.provide(layer)), +); + // Reply model of 25 Nov: a join after the reply posted, mid-run, told the asker to ask again. it.effect.each([ { unanswered: false, lines: [] }, { unanswered: true, lines: [ - "Tech lead didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.", + "A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.", ], }, ] as const)( @@ -1081,7 +1124,8 @@ it.effect( (message) => message.body, ), [ - "Tech lead didn't reply: someone joined before it answered. Send it again.", + "A message sent just before someone joined went unanswered. Send it again.", + "A message sent just before someone joined went unanswered. Send it again.", "Invented-priya-is-back", ], ); diff --git a/apps/server/src/kin/lead/ChatSharing.ts b/apps/server/src/kin/lead/ChatSharing.ts index c7e3507938248..f9a7a11674ef3 100644 --- a/apps/server/src/kin/lead/ChatSharing.ts +++ b/apps/server/src/kin/lead/ChatSharing.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- a synchronous notice id that does not expose the fenced message id. +import * as NodeCrypto from "node:crypto"; + import { KinCardAsker, KinChatId, @@ -38,10 +41,10 @@ const PERSON_ASK_TAGS = ["chat.message", "widget.action"] as const; * The line a chat hears when a join stopped an agent before it answered a person, on every path * that stops it (`onPersonJoined`, `KinReplyBridge`). `partway`: the turn did something visible. */ -export const stoppedByJoinNotice = (leadName: string, partway: boolean) => +export const stoppedByJoinNotice = (partway: boolean) => partway - ? `${leadName} didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.` - : `${leadName} didn't reply: someone joined before it answered. Send it again.`; + ? "A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer." + : "A message sent just before someone joined went unanswered. Send it again."; /** The fixed line a delegated task's card in a shared chat shows instead of its own. */ const movedCardTitle = (lead: string) => `Moved to your private chat with ${lead}`; @@ -65,8 +68,8 @@ const endChatThreads = Effect.fnUntraced(function* ( /** * In every join's transaction, after `recordJoin`: aborts the running turns there and ends the * chat's lead threads; expires waiting events below the history floor; names the tasks agents - * delegated there, whose cards the caller freezes, as only owner-only turns delegate. Returns what - * runs after commit, the chat's lines for asks it left unanswered (`tellStopped`) included. + * delegated there, whose cards the caller freezes. The caller must run `finishPersonJoin` before + * committing, so event expiry and failure lines are durable together. */ export const onPersonJoined = Effect.fn("KinChatSharing.onPersonJoined")(function* (input: { readonly orgId: KinOrgId; @@ -102,10 +105,16 @@ export const onPersonJoined = Effect.fn("KinChatSharing.onPersonJoined")(functio UPDATE kin_events AS e SET state = 'expired' WHERE ${asked} AND (e.state = 'queued' OR (${heldByAborted})) RETURNING agent_id AS "agentId", event_id AS "eventId"`; - return { turns, threads, expired, moved, stopped: yield* stoppedLines(sql, input, expired) }; + return { + turns, + threads, + expired, + moved, + stopped: yield* stoppedLines(sql, input.orgId, expired), + }; }); -/** Commit the live effects only after the reader and the transcript fence have committed. */ +/** Make the failure line durable with the expiry. Publish it and stop the old run after commit. */ export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(function* ( chat: { readonly orgId: KinOrgId; readonly chatId: string }, join: Effect.Success>, @@ -119,6 +128,11 @@ export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(fun ) { const sql = yield* SqlClient.SqlClient; const { identity, stop, presence, repo, hub } = services; + if (join.stopped.length > 0) + yield* tellStopped({ ...chat, lines: join.stopped }).pipe( + Effect.provideService(KinChatRepository, repo), + Effect.provideService(KinChatHub, hub), + ); yield* sql.afterCommit( Effect.gen(function* () { if (identity !== undefined) @@ -134,65 +148,50 @@ export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(fun yield* syncQueued(presence, chat.orgId, agentId).pipe( Effect.provideService(SqlClient.SqlClient, sql), ); - if (join.stopped.length > 0) - yield* tellStopped({ ...chat, lines: join.stopped }).pipe( - Effect.provideService(KinChatRepository, repo), - Effect.provideService(KinChatHub, hub), - Effect.ignore({ log: "Warn", message: "KinChatSharing.tellStopped" }), - ); }), ); }); -/** - * One line per agent whose person's ask this join expired, its id from the join so a retry - * posts it once. Read in the join's transaction: the aborted turn does nothing after it. - */ +/** One line per unanswered human message, even when it woke several leads. */ const stoppedLines = Effect.fnUntraced(function* ( sql: SqlClient.SqlClient, - input: { readonly orgId: KinOrgId; readonly chatId: string; readonly personId: string }, + orgId: KinOrgId, expired: ReadonlyArray<{ readonly eventId: string }>, ) { if (expired.length === 0) return []; - const [join] = yield* sql<{ memberId: string; joinedSeq: number | null }>` - SELECT member_id AS "memberId", joined_seq AS "joinedSeq" FROM kin_chat_members - WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND principal_kind = 'person' - AND person_id = ${input.personId} AND left_at IS NULL - ORDER BY member_id LIMIT 1`; - if (join === undefined) return []; - const asked = yield* sql<{ agentId: KinAgentId; leadName: string; wakeupId: string | null }>` - SELECT DISTINCT e.agent_id AS "agentId", l.name AS "leadName", e.wakeup_id AS "wakeupId" - FROM kin_events e JOIN kin_leads l ON l.org_id = e.org_id AND l.agent_id = e.agent_id - JOIN kin_messages m ON m.org_id = e.org_id + const asked = yield* sql<{ messageId: string; wakeupId: string | null }>` + SELECT DISTINCT m.message_id AS "messageId", e.wakeup_id AS "wakeupId" + FROM kin_events e JOIN kin_messages m ON m.org_id = e.org_id AND m.message_id = json_extract(e.json, '$.messageId') - WHERE e.org_id = ${input.orgId} AND e.event_id IN ${sql.in(expired.map((row) => row.eventId))} + WHERE e.org_id = ${orgId} AND e.event_id IN ${sql.in(expired.map((row) => row.eventId))} AND e.tag IN ${sql.in(PERSON_ASK_TAGS)} AND m.author_kind = 'human' - ORDER BY 1, 3`; - const lines = new Map(); + AND NOT EXISTS (SELECT 1 FROM kin_events answered + WHERE answered.org_id = m.org_id AND answered.replied_at IS NOT NULL + AND answered.tag IN ${sql.in(PERSON_ASK_TAGS)} + AND json_extract(answered.json, '$.messageId') = m.message_id) + ORDER BY m.seq, m.message_id, e.wakeup_id`; + const lines = new Map(); for (const row of asked) { const partway = - row.wakeupId !== null && - (yield* didVisibleWork({ orgId: input.orgId, wakeupId: KinWakeupId.make(row.wakeupId) })); - const line = lines.get(row.agentId); - lines.set(row.agentId, { - leadName: row.leadName, - partway: partway || line?.partway === true, - }); + lines.get(row.messageId) === true || + (row.wakeupId !== null && + (yield* didVisibleWork({ orgId, wakeupId: KinWakeupId.make(row.wakeupId) }))); + lines.set(row.messageId, partway); } - return [...lines].map(([agentId, line]) => ({ + return [...lines].map(([messageId, partway]) => ({ messageId: KinMessageId.make( - `kin-join-stopped:${join.memberId}:${join.joinedSeq ?? 0}:${agentId}`, + `kin-join-stopped:${NodeCrypto.createHash("sha256").update(messageId).digest("hex")}`, ), - body: stoppedByJoinNotice(line.leadName, line.partway), + body: stoppedByJoinNotice(partway), })); }); -/** After the join commits: posts its `stoppedLines` where everyone in the chat now reads. */ -export const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (input: { +const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (input: { readonly orgId: KinOrgId; readonly chatId: string; readonly lines: ReadonlyArray<{ readonly messageId: KinMessageId; readonly body: string }>; }) { + const sql = yield* SqlClient.SqlClient; const repo = yield* KinChatRepository; const hub = yield* KinChatHub; for (const line of input.lines) { @@ -217,7 +216,7 @@ export const tellStopped = Effect.fn("KinChatSharing.tellStopped")(function* (in createdAt: DateTime.formatIso(DateTime.makeUnsafe(yield* Clock.currentTimeMillis)), editedAt: null, }); - yield* hub.publish({ type: "message.posted", orgId: input.orgId, message }); + yield* sql.afterCommit(hub.publish({ type: "message.posted", orgId: input.orgId, message })); } }); diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 4f43141b026de..aa659e8a65179 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -92,6 +92,7 @@ import { SESSION_REFUSAL, SHARED_THREAD_PREFIX, abortChatTurns } from "./Audienc import { fullSessionRefusal } from "./AgentSession.ts"; import { inheritOutside, markOutside, outsideRead, outsideStamp } from "./OutsideContent.ts"; import { onPersonJoined } from "./ChatSharing.ts"; +import { wakeEvent } from "./ChatWake.ts"; import { recordJoin } from "../chat/sharing.ts"; import { socialSeatThread } from "../social/seat.ts"; import * as TaskWake from "./TaskWake.ts"; @@ -1231,7 +1232,7 @@ describe("WakeupRunner", () => { const notices = sql<{ body: string }>`SELECT body FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${chatId} AND author_kind = 'system' ORDER BY seq`; const expected = joinFirst - ? "Lead didn't reply: someone joined before it answered. Send it again." + ? "A message sent just before someone joined went unanswered. Send it again." : "Lead took too long and was stopped. Nothing it hadn't finished was sent. Ask again to start fresh."; if (joinFirst) { yield* join; @@ -4178,13 +4179,17 @@ describe("WakeupRunner", () => { ); it.effect( - "the first group wake after a real return cannot continue the in-flight owner session", + "an in-flight ask above a returning reader’s floor is answered once on a fresh session", () => Effect.gen(function* () { const hold = yield* Deferred.make(); + const privateRule = "Invented owner-only dispatch rule."; + const reply = "The dispatch plan is ready."; yield* Effect.gen(function* () { const sql = yield* seedCarry; const queue = yield* KinEventQueue.KinEventQueue; + const chats = yield* ChatService.KinChatService; + const chatId = KinChatId.make("private"); const identity = yield* KinIdentity.KinIdentity; const owner = { _tag: "person" as const, orgId, personId: KinPersonId.make("owner") }; const meera = KinPersonId.make("meera"); @@ -4225,17 +4230,29 @@ describe("WakeupRunner", () => { ); yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at) VALUES ('private', ${orgId}, 'team_group', 'Dispatch', 0, '2026-11-26')`; - yield* ownerSays("dispatch-before-removal", "private"); + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, + person_id, role, joined_at) VALUES ('private-owner', ${orgId}, ${chatId}, + 'person', ${owner.personId}, 'owner', '2026-11-26')`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, + agent_id, role, joined_at) VALUES ('private-lead', ${orgId}, ${chatId}, + 'agent', ${agentId}, 'member', '2026-11-26')`; + const say = (clientMessageId: string, body = "Invented dispatch question.") => + chats.send(owner, { chatId, body, clientMessageId }); + yield* say("dispatch-before-removal"); yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('private-meera', ${orgId}, 'private', 'person', ${meera}, 'member', '2026-11-26')`; yield* recordJoin(sql, { orgId, chatId: "private", memberId: "private-meera" }); yield* people.removeAccess(ownerSession, { orgId, personId: meera }); - yield* wake("dispatch-owner-alone", "private"); - yield* wake("dispatch-owner-continued", "private"); + for (const id of ["dispatch-owner-alone", "dispatch-owner-continued"]) { + yield* queue.enqueue(wakeEvent(yield* say(id), agentId, undefined)); + yield* Fiber.join(yield* run()); + } const prior = (yield* carryRows).at(-1)!; assert.include(prior, { sent: "carried" }); - yield* queue.enqueue(yield* ownerSays("dispatch-in-flight", "private")); + const ask = yield* say("dispatch-in-flight"); + const event = wakeEvent(ask, agentId, undefined); + yield* queue.enqueue(event); const threads = yield* ThreadManagement.ThreadManagementService; const running = yield* threads.streamDomainEvents.pipe( Stream.filter( @@ -4260,6 +4277,14 @@ describe("WakeupRunner", () => { personId: meera, }); yield* people.accept({ secret: invite.secret }); + const history = yield* chats.history( + { ...owner, personId: meera }, + { chatId, beforeSeq: ask.seq + 1, limit: 1 }, + ); + assert.deepStrictEqual( + history.messages.map(({ messageId }) => messageId), + [ask.messageId], + ); const [fenced] = yield* sql<{ ended_at: string | null; aborted_at: number | null }>` SELECT t.ended_at, w.aborted_at FROM kin_wakeups w JOIN kin_agent_threads t USING (org_id, agent_id, thread_id) WHERE w.org_id = ${orgId} AND w.wakeup_id = ${inflight.wakeupId}`; @@ -4267,16 +4292,39 @@ describe("WakeupRunner", () => { yield* Fiber.join(active); assert.isString(fenced?.ended_at); assert.isNumber(fenced?.aborted_at); - yield* wake("dispatch-after-return", "private"); + assert.include((yield* carryRows).at(-1), { status: "released" }); + const eventState = sql`SELECT state, wakeup_id, replied_at IS NOT NULL AS replied + FROM kin_events WHERE org_id = ${orgId} AND event_id = ${event.eventId}`; + assert.deepStrictEqual(yield* eventState, [ + { state: "queued", wakeup_id: null, replied: 0 }, + ]); + yield* Fiber.join(yield* run()); const next = (yield* carryRows).at(-1)!; - assert.include(next, { sent: "fresh", reason: "members" }); + assert.include(next, { sent: "fresh", reason: "members", status: "completed" }); assert.notEqual(next.threadId, prior.threadId); + assert.notInclude(carriedSend(yield* carryProjection).text, privateRule); + assert.notInclude(carriedSend(yield* carryProjection).text, CARRIED_TURN_NOTE); + assert.deepStrictEqual(yield* eventState, [ + { state: "done", wakeup_id: next.wakeupId, replied: 1 }, + ]); + assert.deepStrictEqual( + yield* sql`SELECT author_kind, body, source_wakeup_id FROM kin_messages + WHERE org_id = ${orgId} AND chat_id = ${chatId} AND seq > ${ask.seq} ORDER BY seq`, + [{ author_kind: "agent", body: reply, source_wakeup_id: next.wakeupId }], + ); }).pipe( Effect.provide( - carryHarness({ - beforeTurn: ({ threadId }) => readCarryHook(threadId).pipe(Effect.asVoid), - holdRunning: (ordinal) => (ordinal === 3 ? hold : undefined), - }), + harnessWith( + { + settings: { kinSessionCarry: true }, + beforeTurn: ({ threadId }) => readCarryHook(threadId).pipe(Effect.asVoid), + holdRunning: (ordinal) => (ordinal === 3 ? hold : undefined), + includeRulebook: true, + standingRules: () => privateRule, + replyText: reply, + }, + Layer.merge(carryServices(), ReplyBridge.layer.pipe(Layer.provideMerge(chatLayers))), + ), ), ); }).pipe(provideDeterministicTestRuntime), diff --git a/apps/server/src/kin/people/KinPeople.test.ts b/apps/server/src/kin/people/KinPeople.test.ts index bb054de34f1bd..a4349514bf690 100644 --- a/apps/server/src/kin/people/KinPeople.test.ts +++ b/apps/server/src/kin/people/KinPeople.test.ts @@ -1642,7 +1642,7 @@ it.effect( // Leaving lowers the group's floor only to what Tomas, still there, could always read; each // join said once that it left a question unanswered. const unanswered = - "Tech lead didn't reply: someone joined before it answered. Send it again."; + "A message sent just before someone joined went unanswered. Send it again."; const turn = yield* wake(); assert.deepStrictEqual( (yield* chats.read(turn, { chatId: group.chatId, afterSeq: 0, limit: 100 })).map( diff --git a/apps/server/src/kin/people/KinPeople.ts b/apps/server/src/kin/people/KinPeople.ts index b2aaf6da8feaf..b8f126118d9c4 100644 --- a/apps/server/src/kin/people/KinPeople.ts +++ b/apps/server/src/kin/people/KinPeople.ts @@ -519,7 +519,7 @@ export const make = Effect.gen(function* () { hub, ...(Option.isSome(stop) ? { stop: stop.value } : {}), ...(Option.isSome(presence) ? { presence: presence.value } : {}), - }).pipe(provideSql); + }).pipe(provideSql, Effect.mapError(sqlError("KinPeople.gainedChatNotice"))); }); /** * The same person let back in: the level, places, leads and chats their access was removed diff --git a/apps/server/src/kin/reply/KinReplyBridge.test.ts b/apps/server/src/kin/reply/KinReplyBridge.test.ts index efbe970468cdf..cf4259dde1d6b 100644 --- a/apps/server/src/kin/reply/KinReplyBridge.test.ts +++ b/apps/server/src/kin/reply/KinReplyBridge.test.ts @@ -2249,7 +2249,7 @@ it.effect.each([ before: "a tool call", then: "completed", expected: [ - "system:Ada didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.", + "system:A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.", ], }, { @@ -2257,7 +2257,7 @@ it.effect.each([ before: "a tool call", then: "failed", expected: [ - "system:Ada didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.", + "system:A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.", ], }, { @@ -2265,33 +2265,33 @@ it.effect.each([ before: "a tool call", then: "restart", expected: [ - "system:Ada didn't finish its reply: someone joined while it was working. What it had already done stays; ask again for the answer.", + "system:A reply was interrupted when someone joined. Work already done stays. Send the message again for an answer.", ], }, { access: "member", before: "a join already", then: "completed", - expected: ["system:Ada didn't reply: someone joined before it answered. Send it again."], + expected: ["system:A message sent just before someone joined went unanswered. Send it again."], }, { access: "member", before: "a join already", then: "failed", - expected: ["system:Ada didn't reply: someone joined before it answered. Send it again."], + expected: ["system:A message sent just before someone joined went unanswered. Send it again."], }, // The join through Add says it, and the turn it aborted says nothing more. { access: "member", before: "a join through Add", then: "completed", - expected: ["system:Ada didn't reply: someone joined before it answered. Send it again."], + expected: ["system:A message sent just before someone joined went unanswered. Send it again."], }, { access: "member", before: "a join through Add", then: "timed_out", - expected: ["system:Ada didn't reply: someone joined before it answered. Send it again."], + expected: ["system:A message sent just before someone joined went unanswered. Send it again."], }, ] as const)( "an owner-only reply posts where everyone reading is owner-level, never silently held ($access, $before, $then)", diff --git a/apps/server/src/kin/reply/KinReplyBridge.ts b/apps/server/src/kin/reply/KinReplyBridge.ts index 91dcf8d821e62..558fcc44d14d8 100644 --- a/apps/server/src/kin/reply/KinReplyBridge.ts +++ b/apps/server/src/kin/reply/KinReplyBridge.ts @@ -1134,7 +1134,7 @@ const make = Effect.gen(function* () { orgId: wake.orgId, chatId: wake.lane.chatId, audience: "chat", - body: stoppedByJoinNotice(wake.lane.leadName, partway), + body: stoppedByJoinNotice(partway), }); }), ); diff --git a/apps/server/src/kin/team/KinTeam.test.ts b/apps/server/src/kin/team/KinTeam.test.ts index 9a7f5ea668c25..5134296bcf60a 100644 --- a/apps/server/src/kin/team/KinTeam.test.ts +++ b/apps/server/src/kin/team/KinTeam.test.ts @@ -25,6 +25,7 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { McpSchema, McpServer } from "effect/ai"; +import { SessionStore } from "../../auth/SessionStore.ts"; import { McpInvocationContext, type McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; import * as McpHttpServer from "../../mcp/McpHttpServer.ts"; import { liveThreadShell } from "../../mcp/McpToolAccess.testkit.ts"; @@ -48,6 +49,7 @@ import type { KinDecision } from "../memory/MemoryWriter.ts"; import { handlers as leadHandlers } from "../lead/mcp/handlers.ts"; import { KinLeadToolkit } from "../lead/mcp/tools.ts"; import { laneFor } from "../reply/replyLane.ts"; +import * as People from "../people/KinPeople.ts"; import * as Team from "./KinTeam.ts"; import { teamTurnFacts } from "./prompt.ts"; @@ -81,9 +83,16 @@ const scopeOf = (agent: string): McpInvocationScope => ({ const kinServices = Layer.unwrap( Effect.gen(function* () { const services = Option.getOrThrow((yield* Kin.KinServer).services); - return Layer.mergeAll(Handoff.layer, Team.layer, Layer.mock(LeadMemory)({})).pipe( - Layer.provideMerge(Layer.succeedContext(services)), - ); + return Layer.mergeAll( + Handoff.layer, + Team.layer, + People.layer.pipe( + Layer.provide( + Layer.mock(SessionStore)({ cookieName: "fixture-session", legacyCookieName: undefined }), + ), + ), + Layer.mock(LeadMemory)({}), + ).pipe(Layer.provideMerge(Layer.succeedContext(services))); }), ); const layer = Layer.mergeAll( @@ -510,29 +519,80 @@ it.effect("a discussion the owner asked for runs its turns, ends, and is told on ), ); -it.effect("adding a co-owner to the Team room retires its old owner-only thread", () => - Effect.gen(function* () { - const { sql, orgId } = yield* ambermill; - const team = yield* Team.KinTeam; - const identity = Context.get(Option.getOrThrow((yield* Kin.KinServer).services), KinIdentity); - yield* sql`UPDATE kin_people SET access = 'member' WHERE org_id = ${orgId} AND person_id = 'meera'`; - const room = yield* team.ensureRoom(orgId); - const threadId = ThreadId.make("kin:owner-chat:team-fixture"); - yield* identity.registerAgentThread({ - orgId, - agentId: KinAgentId.make("chief"), - threadId, - chatId: room.chatId, - }); - assert.isTrue(identity.isLeadThread(threadId)); +it.effect.each(["admission", "promotion"] as const)( + "Team %s settles the in-flight owner ask in the join transaction without sharing its words", + (road) => + Effect.gen(function* () { + const { sql, orgId, chats, owner, person } = yield* ambermill; + const team = yield* Team.KinTeam; + const services = Option.getOrThrow((yield* Kin.KinServer).services); + const identity = Context.get(services, KinIdentity); + const people = yield* People.KinPeople; + const ownerSession = { + sessionId: AuthSessionId.make("owner"), + subject: "browser", + method: "browser-session-cookie" as const, + scopes: AuthStandardClientScopes, + }; + if (road === "admission") + yield* sql`UPDATE kin_people SET access = 'member' WHERE org_id = ${orgId} AND person_id = 'meera'`; + const room = yield* team.ensureRoom(orgId); + if (road === "promotion") + yield* people.setAccess(ownerSession, { ...person("meera"), access: "member" }); + const audience = road === "admission" ? "owner_only" : "shared"; + const threadId = ThreadId.make( + road === "admission" ? "kin:owner-chat:team-fixture" : "kin-shared:team-fixture", + ); + const agentId = KinAgentId.make("chief"); + yield* identity.registerAgentThread({ orgId, agentId, threadId, chatId: room.chatId }); + const ask = yield* chats.send(owner, { + chatId: room.chatId, + clientMessageId: "asked-before-admission", + body: "Find the amber ledger.", + }); + const wakeupId = yield* startAgentWakeup({ orgId, agentId, threadId, message: ask }); + const readWake = sql<{ status: string; aborted: number; audience: string | null }>` + SELECT status, aborted_at IS NOT NULL AS aborted, audience FROM kin_wakeups + WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId}`; + assert.deepStrictEqual(yield* readWake, [{ status: "running", aborted: 0, audience }]); + assert.isTrue(identity.isLeadThread(threadId)); - yield* sql`UPDATE kin_people SET access = 'co_owner' WHERE org_id = ${orgId} AND person_id = 'meera'`; - yield* team.ensureRoom(orgId); - const [old] = yield* sql<{ ended_at: string | null }>`SELECT ended_at FROM kin_agent_threads + const failure = "A message sent just before someone joined went unanswered. Send it again."; + yield* sql.withTransaction( + Effect.gen(function* () { + if (road === "admission") { + yield* sql`UPDATE kin_people SET access = 'co_owner' WHERE org_id = ${orgId} AND person_id = 'meera'`; + yield* team.ensureRoom(orgId); + } else { + yield* people.setAccess(ownerSession, { ...person("meera"), access: "co_owner" }); + } + assert.deepStrictEqual( + yield* sql`SELECT body FROM kin_messages WHERE org_id = ${orgId} AND chat_id = ${room.chatId} AND kind = 'system'`, + [{ body: failure }], + ); + }), + ); + yield* team.ensureRoom(orgId); + assert.isFalse(identity.isLeadThread(threadId)); + const [old] = yield* sql<{ ended_at: string | null }>`SELECT ended_at FROM kin_agent_threads WHERE org_id = ${orgId} AND thread_id = ${threadId}`; - assert.isString(old?.ended_at); - assert.isFalse(identity.isLeadThread(threadId)); - }).pipe(Effect.provide(layer)), + assert.isString(old?.ended_at); + assert.deepStrictEqual(yield* readWake, [{ status: "running", aborted: 1, audience }]); + + const queue = Context.get(services, KinEventQueue); + yield* queue.finish({ orgId, wakeupId, status: "interrupted" }); + assert.deepStrictEqual(yield* readWake, [{ status: "released", aborted: 1, audience }]); + assert.deepStrictEqual( + yield* sql`SELECT state FROM kin_events WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId}`, + [{ state: "expired" }], + ); + const history = (reader: typeof owner) => + chats.history(reader, { chatId: room.chatId, beforeSeq: 1_000, limit: 20 }); + const owned = (yield* history(owner)).messages.map(({ body }) => body); + const admitted = (yield* history(person("meera"))).messages.map(({ body }) => body); + assert.sameMembers(owned, [ask.body, failure]); + assert.deepStrictEqual(admitted, [failure]); + }).pipe(Effect.provide(layer)), ); // Rhea names Finance and the Chief of staff in the Team room: Kin opens their discussion once, diff --git a/verification/kin/reply/README.md b/verification/kin/reply/README.md index 8a75711472455..1b80fe535bfba 100644 --- a/verification/kin/reply/README.md +++ b/verification/kin/reply/README.md @@ -184,3 +184,5 @@ TLC 1.7.4, one worker per run; wall times reflect concurrent checks on the same **Re-checked 2026-11-29** for the train 19 A fix round: all 18 rules hold over 1,794,442 distinct states (658,714 ms); 44/44 mutations are caught (75,550 ms). The new `return-without-abort` variant gives the private group’s former reader access while a carried turn is in flight. The model records disclosure at completion: Ben would receive an answer containing retained text he was not entitled to. The sound return interrupts that turn, using the same transition as a join. **Re-confirmed 2026-11-29** on train 19 of 29 Nov (each owner chat keeps its own session, the owner's rules editor with the turn-start memory check, the rules screens, and keep-warm from day one, four steps joined on kin `3c0ea045dde`; no spec change, all 18 rules hold over 1,794,442 distinct states in 695 s; 44/44 variants caught in 77 s). The covered files the line changes are `lead/WakeupRunner.ts`, `lead/ChatSharing.ts`, `lead/Audience.ts`, `lead/sessionCarry.ts`, `chat/KinGroups.ts` and `people/KinPeople.ts`. They give each owner-only chat its own thread, which continues only while its readers stay the same. A mixed wake runs on a one-shot thread and is never stored. A join or a return stops the private turn. The rules editor's save and a refused journal push change only which rules revision a turn reads, and whether a finished turn counts as completed. + +**Checked 2026-11-30** for train 19 step 7. A join that advances the history floor must store the failure line in the same transaction that expires an unanswered ask; a return that preserves the floor can still hand a visible ask to a fresh wake. `join-drops-running-ask` omits the line only for a claimed ask and is caught by `EveryMessageAnswered`. The good model's transitions and properties are unchanged; 45/45 broken variants caught. diff --git a/verification/kin/reply/Reply.tla b/verification/kin/reply/Reply.tla index 16ddd0033e458..a51ba3de111a1 100644 --- a/verification/kin/reply/Reply.tla +++ b/verification/kin/reply/Reply.tla @@ -384,9 +384,10 @@ Owed == {m \in Claimed : ~covered[m]} (* Every join, in its transaction (chat/KinGroups.ts shareWith → lead/ChatSharing.ts onPersonJoined): each ask waiting in the chat, or claimed unanswered by a turn aborted for its - audience, expires, and stoppedLines gives the chat one line per agent ("didn't reply" / "didn't - finish its reply"), which tellStopped posts after commit. The model counts that line on each - expired ask. *) + audience, expires if it is below the new reader's history floor. The same transaction stores + the plain failure line once for each unanswered message; tellStopped publishes after commit. + In this reply branch the join advances the floor; a return that preserves the floor can requeue + an eligible event. *) Expire(exp) == /\ Ev([m \in Msgs |-> IF m \in exp THEN "expired" ELSE ev[m]]) /\ fails' = [m \in Msgs |-> IF m \in exp /\ Broken # "join-expires-silently" THEN fails[m] + 1 @@ -419,6 +420,7 @@ JoinStops == IN /\ Ev([m \in Msgs |-> IF m \in exp THEN "expired" ELSE IF ev[m] = "claimed" THEN "done" ELSE ev[m]]) /\ fails' = [m \in Msgs |-> IF m \in exp /\ Broken # "join-expires-silently" + /\ ~(Broken = "join-drops-running-ask" /\ ev[m] = "claimed") THEN fails[m] + 1 ELSE fails[m]] /\ IF wake = "running" THEN joined' = TRUE /\ aborted' = TRUE ELSE UNCHANGED <> /\ UNCHANGED < { return "The floor closes"; case "SomeoneJoins": return "Someone joins the chat while the agent works"; - case "JoinStops": - return from["wake"] === "running" - ? "Someone else joins; the agent's turn is stopped and the chat is told once" - : "Someone else joins; the chat is told once your waiting message won't be answered"; + case "JoinStops": { + const stopped = from["wake"] === "running" ? "; the agent's turn is stopped" : ""; + const notice = + Number(first(to, "fails")) > Number(first(from, "fails")) ? "; the chat is told once" : ""; + return `Someone else joins${stopped}${notice}`; + } case "MadeMember": return "You are made a member while the agent works; its turn is stopped"; case "ReplyHeldBack": @@ -383,7 +390,9 @@ export const step = (action: string, from: Vars, to: Vars) => { : "Its reply is held back for the join; the chat is told once"; case "RunCompletes": if (from["aborted"] === true) - return "The turn ends; a message it had not answered goes to a fresh turn"; + return first(from, "ev") === "claimed" && first(to, "ev") === "queued" + ? "The turn ends; the unanswered message goes to a fresh turn" + : "The aborted turn ends; nothing more is said"; if (from["noticed"] === true) return "The turn ends; nothing more is said"; return Number(first(to, "fails")) > Number(first(from, "fails")) ? "The turn ends; asked once more, no reply: “didn't reply”" @@ -394,7 +403,9 @@ export const step = (action: string, from: Vars, to: Vars) => { : "The turn ends"; case "RunFails": if (from["aborted"] === true) - return "The turn fails; a message it had not answered goes to a fresh turn"; + return first(from, "ev") === "claimed" && first(to, "ev") === "queued" + ? "The turn fails; the unanswered message goes to a fresh turn" + : "The aborted turn fails; nothing more is said"; if (Number(first(to, "notes")) > Number(first(from, "notes"))) return "The turn fails before what the reply promised: one line names it"; if (first(to, "ev") === "done")