From c8a98eef727d01931c77ab9eddfafd2e32d6dd6d Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:03:53 +0530 Subject: [PATCH 1/8] fix(kin): continue each owner-only chat in its own session The owner thread previously mixed direct, group and Team wakes, causing resets and making the transcript unsafe to reuse across chats. Bind a session to one proved owner-only chat, and retire or isolate it when the audience or event origin no longer matches. People-change: The owner can return to a private chat or the Team room without starting the agent conversation over. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/host/sessionCompaction.ts | 30 ++- apps/server/src/kin/lead/Audience.ts | 5 +- apps/server/src/kin/lead/TaskWake.ts | 10 +- apps/server/src/kin/lead/WakeupRunner.test.ts | 246 ++++++++++++++++-- apps/server/src/kin/lead/WakeupRunner.ts | 169 +++++++++--- apps/server/src/kin/lead/sessionAudience.ts | 95 +++++++ apps/server/src/kin/lead/sessionCarry.ts | 27 +- apps/server/src/kin/lead/sessionChanges.ts | 15 +- apps/server/src/kin/team/KinTeam.test.ts | 25 ++ apps/server/src/kin/team/KinTeam.ts | 24 +- verification/kin/reply/README.md | 8 +- verification/kin/reply/Reply.tla | 43 ++- verification/kin/reply/view.ts | 15 ++ 13 files changed, 613 insertions(+), 99 deletions(-) diff --git a/apps/server/src/kin/host/sessionCompaction.ts b/apps/server/src/kin/host/sessionCompaction.ts index 12ea9ee06aad..4759d6b53499 100644 --- a/apps/server/src/kin/host/sessionCompaction.ts +++ b/apps/server/src/kin/host/sessionCompaction.ts @@ -24,6 +24,12 @@ import { WARM_SESSION_MS, warmSession, } from "../lead/sessionCarry.ts"; +import { + OWNER_CHAT_THREAD_PREFIX, + ownerSessionAudience, + ownerSessionWake, +} from "../lead/sessionAudience.ts"; +import { laneFor } from "../reply/replyLane.ts"; import { KinSessionContext, type SeenSession } from "../lead/turn/sessionContext.ts"; import { leadThreadInstructions } from "../lead/turn/session.ts"; import { KinCacheSessions } from "./cacheSessions.ts"; @@ -76,7 +82,8 @@ export const check = Effect.fn("KinSessionCompaction.check")(function* (input: C JOIN kin_wakeups w ON w.org_id = s.org_id AND w.wakeup_id = s.wakeup_id AND w.kind = 'turn' JOIN kin_cache_parts p ON p.fingerprint = w.cache_part AND p.org_id = s.org_id AND p.agent_id = s.agent_id JOIN kin_leads l ON l.org_id = s.org_id AND l.agent_id = s.agent_id - WHERE s.compaction_started_at IS NULL AND p.seat = 'owner' AND w.status = 'completed' + WHERE substr(s.thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) = ${OWNER_CHAT_THREAD_PREFIX} + AND s.compaction_started_at IS NULL AND p.seat = 'owner' AND w.status = 'completed' AND w.last_request_at > ${now - WARM_SESSION_MS} AND w.last_request_at <= ${now - COMPACT_AT_MS} AND w.context_tokens > ${SMALL_CONVERSATION_TOKENS} ORDER BY w.last_request_at, s.thread_id`; @@ -109,11 +116,19 @@ export const check = Effect.fn("KinSessionCompaction.check")(function* (input: C JOIN kin_leads l USING (org_id, agent_id) LEFT JOIN kin_org_state o USING (org_id) WHERE a.org_id = ${orgId} AND a.agent_id = ${agentId} AND t.thread_id = ${threadId} - AND a.paused_at IS NULL AND a.retired_at IS NULL AND t.ended_at IS NULL + AND a.paused_at IS NULL AND a.retired_at IS NULL AND t.ended_at IS NULL AND t.chat_id = ${prior.chatId} AND l.models_json = ${candidate.modelsJson} AND COALESCE(o.paused, 0) = 0 AND NOT EXISTS (SELECT 1 FROM kin_wakeups WHERE org_id = ${orgId} AND agent_id = ${agentId} AND kind = 'turn' AND status = 'running')`; if (idle === undefined || (yield* budget.admit(orgId, "P1")).atLimit) return false; + const previousTurn = { orgId, agentId, wakeupId: prior.wakeupId }; + const scope = yield* ownerSessionAudience(previousTurn, prior.chatId); + if ( + scope === undefined || + scope.audience !== (prior.audience ?? null) || + !(yield* ownerSessionWake(previousTurn, prior.chatId, scope)) + ) + return false; const own = Option.getOrUndefined(decodeModel(candidate.modelsJson)); if (own === undefined || prior.standing === undefined) return false; const model = (yield* turnModel(orgId, own)).model; @@ -131,7 +146,12 @@ export const check = Effect.fn("KinSessionCompaction.check")(function* (input: C standing: prior.standing, seenStanding: { wakeupId: prior.wakeupId, key: prior.standing }, enabled: true, - idleChat: prior.chatId, + ownerChat: { + chatId: prior.chatId, + audience: scope.audience, + ...(prior.audience === undefined ? {} : { seenAudience: prior.audience }), + authorized: true, + }, now: time, wallNow: time, stopRevision: refresh?.stopRevision(orgId) ?? 0, @@ -151,13 +171,15 @@ export const check = Effect.fn("KinSessionCompaction.check")(function* (input: C return false; const memoryHead = facts.previousCursor.memoryHead; if (memoryHead === null) return false; + const lane = Option.getOrUndefined(yield* laneFor(previousTurn)); + if (lane?.chatId !== prior.chatId) return false; const standing = yield* prompt .inspectStanding({ orgId, agentId, wakeupId: prior.wakeupId, memoryHead, - lane: { chatId: prior.chatId, mode: "reply" }, + lane, }) .pipe(Effect.orElseSucceed(() => null)); if (standing !== prior.standing) return false; diff --git a/apps/server/src/kin/lead/Audience.ts b/apps/server/src/kin/lead/Audience.ts index 8f0c5c3baeb0..cd52dc52f01f 100644 --- a/apps/server/src/kin/lead/Audience.ts +++ b/apps/server/src/kin/lead/Audience.ts @@ -253,10 +253,7 @@ export const turnAsker = Effect.fn("KinAudience.turnAsker")(function* (turn: Tur return askers.length === 1 ? (askers[0] ?? null) : null; }); -/** - * Whether the lead's owner alone is behind the turn: then it runs on the lead's one owner thread. - * A co-owner's owner-tier turn runs on its chat's own, so the owner's chats stay his. - */ +/** Whether anyone besides the lead's owner reads or asks, including in the source chat. */ export const ownerAlone = Effect.fn("KinAudience.ownerAlone")(function* (turn: Turn) { const behind = yield* peopleBehind(turn); if (behind === undefined) return false; diff --git a/apps/server/src/kin/lead/TaskWake.ts b/apps/server/src/kin/lead/TaskWake.ts index fb78a7d4802c..ec9435c7218a 100644 --- a/apps/server/src/kin/lead/TaskWake.ts +++ b/apps/server/src/kin/lead/TaskWake.ts @@ -18,6 +18,7 @@ import { forkParked } from "../../serverActivation.ts"; import { SHARED_THREAD_PREFIX } from "./Audience.ts"; import { hashedEventId } from "./eventIds.ts"; import { KinEventQueue } from "./KinEventQueue.ts"; +import { OWNER_CHAT_THREAD_PREFIX } from "./sessionAudience.ts"; import { ownerLevelSql } from "../people/KinAccess.ts"; /** @@ -71,14 +72,17 @@ export const noticeState = ( }; /** - * The agent and chat a task delegated from `threadId` answers in: the chat it was asked from - * while only owner-level people ever were in it, else the agent's direct chat with its owner. + * A task's reporter goes to its original chat only while that chat can still hear the work. + * A retired owner-chat thread may have delegated before a new reader joined. */ export const taskChat = Effect.fn("KinTaskWake.taskChat")(function* (threadId: ThreadId) { const sql = yield* SqlClient.SqlClient; const [row] = yield* sql<{ orgId: KinOrgId; agentId: KinAgentId; chatId: string }>` SELECT t.org_id AS "orgId", t.agent_id AS "agentId", - CASE WHEN t.chat_id IS NULL OR EXISTS (SELECT 1 FROM kin_chat_members m + CASE WHEN t.chat_id IS NULL + OR (t.ended_at IS NOT NULL + AND substr(t.thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) = ${OWNER_CHAT_THREAD_PREFIX}) + OR EXISTS (SELECT 1 FROM kin_chat_members m WHERE m.org_id = t.org_id AND m.chat_id = t.chat_id AND m.principal_kind = 'person' AND NOT ${sql.literal(ownerLevelSql("m.org_id", "m.person_id"))}) THEN l.owner_chat_id ELSE t.chat_id END AS "chatId" diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index b5e45c7c068f..b6028fad6627 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -84,6 +84,7 @@ import * as KinStop from "./KinStop.ts"; import { SESSION_REFUSAL, SHARED_THREAD_PREFIX, abortChatTurns } from "./Audience.ts"; import { fullSessionRefusal } from "./AgentSession.ts"; import { inheritOutside, markOutside, outsideRead, outsideStamp } from "./OutsideContent.ts"; +import { onPersonJoined } from "./ChatSharing.ts"; import * as TaskWake from "./TaskWake.ts"; import { sensitiveShown, turnSensitive } from "../work/sensitiveReads.ts"; import { BILLS_THREAD_PREFIX } from "./billsOnly.ts"; @@ -880,15 +881,7 @@ describe("WakeupRunner", () => { const at = "2026-11-08T00:00:00.000Z"; yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES ('teammate', 'org', 'teammate', 'Teammate', ${at})`; - yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) - VALUES ('owner-member', 'org', 'owner-chat', 'person', 'owner', 'owner', ${at})`; - let seq = 0; const turn = Effect.fn("test.turn")(function* (id: string) { - seq++; - yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, author_person_id, - author_member_id, author_role, kind, body, mentions_json, status, created_at) - VALUES (${id}, 'org', 'owner-chat', ${seq}, 'human', 'owner', 'owner-member', 'owner', 'text', - 'Invented question', '[]', 'posted', ${at})`; yield* wake(id, "owner-chat"); const [lead] = yield* sql<{ threadId: string; @@ -921,10 +914,10 @@ describe("WakeupRunner", () => { assert.strictEqual(again.threadId, alone.threadId); assert.deepStrictEqual( yield* sql`SELECT thread_id, chat_id FROM kin_agent_threads WHERE ended_at IS NULL - ORDER BY chat_id IS NULL`, + ORDER BY thread_id`, [ { thread_id: shared.threadId, chat_id: "owner-chat" }, - { thread_id: alone.threadId, chat_id: null }, + { thread_id: alone.threadId, chat_id: "owner-chat" }, ], ); // The shared turn left no journal entry. @@ -1061,7 +1054,7 @@ describe("WakeupRunner", () => { yield* sql`SELECT thread_id, chat_id FROM kin_agent_threads WHERE ended_at IS NULL ORDER BY thread_id`, [ - { thread_id: owner, chat_id: null }, + { thread_id: owner, chat_id: "owner-chat" }, ...[ { thread_id: asha, chat_id: "dm-asha" }, { thread_id: ravi, chat_id: "dm-ravi" }, @@ -3397,6 +3390,7 @@ describe("WakeupRunner", () => { it.effect.each([ "worked", + "owner group", "other chat", "failed", "chat only", @@ -3416,9 +3410,14 @@ describe("WakeupRunner", () => { let standingPart = "Owner permission is active."; return Effect.gen(function* () { const room = scenario === "confined room"; + const group = scenario === "owner group"; const sql = room ? yield* seedCarryRoom : yield* seedCarry; - yield* wake("tidewater-first", room ? "room" : undefined); - yield* wake("tidewater-work", room ? "room" : undefined); + if (group) + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at) + VALUES ('room', ${orgId}, 'team_group', 'Tidewater dispatch', 0, '2026-11-26')`; + const chat = room || group ? "room" : "direct"; + yield* wake("tidewater-first", chat); + yield* wake("tidewater-work", chat); const [first, last] = yield* carryRows; const fingerprint = "fixed-part"; yield* sql`INSERT INTO kin_cache_parts VALUES (${fingerprint}, ${orgId}, ${room ? "confined" : "owner"}, ${agentId}, @@ -3429,7 +3428,8 @@ describe("WakeupRunner", () => { WHERE wakeup_id = ${last!.wakeupId}`; if (scenario === "standing changed while idle") standingPart = "Owner permission is gone."; if (scenario === "marked") yield* markOutside({ orgId, wakeupId: first!.wakeupId }, "file"); - if (scenario === "worked") yield* sensitiveShown({ orgId, wakeupId: first!.wakeupId }); + if (scenario === "worked" || group) + yield* sensitiveShown({ orgId, wakeupId: first!.wakeupId }); if (scenario === "org paused") yield* sql`INSERT INTO kin_org_state (org_id,paused,paused_at,paused_by) VALUES (${orgId},1,1,'owner')`; @@ -3467,7 +3467,7 @@ describe("WakeupRunner", () => { yield* runCompaction; const ledger = yield* sql`SELECT kind, thread_id, run_id, event_ids FROM kin_wakeups WHERE json_extract(carry_json, '$.action') = 'compaction'`; - if (scenario !== "worked" && scenario !== "other chat" && scenario !== "failed") { + if (scenario !== "worked" && scenario !== "other chat" && scenario !== "failed" && !group) { assert.strictEqual(requests, 0); assert.deepStrictEqual(ledger, []); return; @@ -3498,7 +3498,7 @@ describe("WakeupRunner", () => { return; } rules = newRule; - yield* wake("tidewater-restarted"); + yield* wake("tidewater-restarted", chat); const next = (yield* carryRows).findLast((one) => one.reason === "summary"); assert.isDefined(next, JSON.stringify(yield* carryRows)); const sent = carriedSend(yield* carryProjection); @@ -3698,6 +3698,202 @@ describe("WakeupRunner", () => { ); }); + it.effect.each([ + "interleave", + "join", + "outside", + "mixed", + "steer", + "restart", + "legacy", + "fallback", + ] as const)("isolates owner chat sessions: %s", (scenario) => + Effect.gen(function* () { + const hold = yield* Deferred.make(); + let current: KinSessionContext["Service"] | undefined; + let block = false; + const steers = yield* Queue.unbounded<{ runId: string; messageId: string }>(); + yield* Effect.gen(function* () { + current = yield* KinSessionContext; + const sql = yield* seedCarry; + const queue = yield* KinEventQueue.KinEventQueue; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at, team_id) + VALUES ('private', ${orgId}, 'team_group', 'Dispatch', 0, '2026-11-26', NULL), + ('team', ${orgId}, 'team_group', 'Team', 0, '2026-11-26', 'team-room')`; + const latest = carryRows.pipe(Effect.map((rows) => rows.at(-1)!)); + if (scenario === "legacy") { + yield* (yield* ThreadLaunch.ThreadLaunchService).launch({ + commandId: CommandId.make("legacy-thread"), + threadId: ThreadId.make("kin:legacy"), + projectId: ProjectId.make("kin:org"), + title: "Legacy lead", + modelSelection: selection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + createdBy: "system", + creationSource: "server", + }); + yield* sql`INSERT INTO kin_agent_threads (org_id, agent_id, thread_id, started_at) + VALUES (${orgId}, ${agentId}, 'kin:legacy', '2026-11-26')`; + } + yield* wake("dispatch-1"); + const direct = yield* latest; + yield* wake("dispatch-2", "private"); + const group = yield* latest; + if (scenario === "legacy") { + assert.notEqual(direct.threadId, "kin:legacy"); + assert.notEqual(group.threadId, "kin:legacy"); + return; + } + if (scenario === "outside") yield* markOutside({ orgId, wakeupId: group.wakeupId }, "file"); + if (scenario === "mixed") { + const mixed = yield* ownerSays("dispatch-mixed", "private"); + if (mixed._tag !== "chat.message") throw new Error("Expected a chat event"); + yield* queue.enqueue({ + ...mixed, + origin: { agentId, chatId: KinChatId.make("direct") }, + }); + yield* Fiber.join(yield* run()); + const row = yield* latest; + assert.include(row, { sent: "fresh", reason: "other_chat" }); + assert.notEqual(row.threadId, group.threadId); + assert.notEqual(row.threadId, direct.threadId); + } + if (scenario === "steer") { + assert.notEqual(direct.threadId, group.threadId); + block = true; + yield* queue.enqueue(yield* ownerSays("dispatch-live", "direct")); + const threads = yield* ThreadManagement.ThreadManagementService; + const running = yield* threads.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const fiber = yield* run(); + yield* Fiber.join(running); + yield* queue.enqueue(yield* ownerSays("dispatch-foreign", "private")); + yield* queue.enqueue(yield* ownerSays("dispatch-local", "direct")); + const steer = yield* Queue.take(steers); + yield* Deferred.succeed(hold, undefined); + yield* Fiber.join(fiber); + block = false; + const answered = yield* latest; + assert.include( + answered, + { sent: "carried", reason: null, threadId: direct.threadId }, + JSON.stringify(answered), + ); + const events = yield* sql<{ event_id: string }>`SELECT event_id FROM kin_events + WHERE wakeup_id = ${(yield* latest).wakeupId} ORDER BY event_id`; + assert.deepStrictEqual( + events.map((row) => row.event_id), + ["dispatch-live", "dispatch-local"], + ); + assert.include(steer.messageId, "kin-steer"); + yield* Fiber.join(yield* run()); + assert.include(yield* latest, { sent: "carried", threadId: group.threadId }); + return; + } + if (scenario === "fallback") { + yield* queue.enqueue(event("dispatch-routine")); + yield* Fiber.join(yield* run()); + assert.include(yield* latest, { sent: "carried", threadId: direct.threadId }); + yield* queue.enqueue({ + ...event("dispatch-crossed"), + _tag: "pulse", + factKeys: [], + origin: { agentId, chatId: KinChatId.make("private") }, + }); + yield* Fiber.join(yield* run()); + assert.include(yield* latest, { reason: "other_chat", sent: "fresh" }); + } + if (scenario === "restart") yield* wake("dispatch-team-before-restart", "team"); + if (scenario === "join") { + const chatId = KinChatId.make("private"); + const personId = KinPersonId.make("meera"); + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) + VALUES ('private-meera', ${orgId}, ${chatId}, 'person', ${personId}, 'member', '2026-11-26')`; + yield* onPersonJoined({ orgId, chatId, personId }); + }), + ); + } + const team = scenario === "restart" ? yield* latest : undefined; + const repeat = Effect.gen(function* () { + current = yield* KinSessionContext; + yield* wake("dispatch-3"); + assert.include(yield* latest, { sent: "carried", threadId: direct.threadId }); + if (scenario === "interleave" || scenario === "restart") { + yield* wake("dispatch-team", "team"); + if (team !== undefined) + assert.include(yield* latest, { sent: "carried", threadId: team.threadId }); + } + yield* wake("dispatch-4", "private"); + const next = yield* latest; + if (scenario === "join") { + assert.include(next, { sent: "fresh", reason: "members" }); + assert.notEqual(next.threadId, group.threadId); + yield* sql`UPDATE kin_chat_members SET left_at = '2026-11-29' WHERE member_id = 'private-meera'`; + yield* wake("dispatch-after-leave", "private"); + assert.notEqual((yield* latest).threadId, group.threadId); + return; + } + assert.include(next, { + threadId: group.threadId, + sent: scenario === "outside" ? "fresh" : "carried", + reason: scenario === "outside" ? "marked" : null, + }); + yield* wake("dispatch-5"); + assert.include(yield* latest, { sent: "carried", threadId: direct.threadId }); + }); + if (scenario === "join" || scenario === "restart") + yield* repeat.pipe( + Effect.provide( + Layer.fresh(WakeupRunner.layer).pipe( + Layer.provideMerge( + Layer.merge( + Layer.fresh(KinSessionContext.layer).pipe(Layer.provide(presentFixtureSession)), + Layer.succeed(KinBoot, "owner-chat-restart"), + ), + ), + ), + ), + ); + else yield* repeat; + assert.notEqual(direct.threadId, group.threadId); + if (scenario === "interleave") { + const saved = yield* sql<{ + chat_id: string; + native_session_id: string; + audience: string | null; + }>` + SELECT chat_id, native_session_id, json_extract(snapshot_json, '$.audience') AS audience FROM kin_session_seen ORDER BY chat_id`; + assert.deepStrictEqual( + saved.map(({ chat_id }) => chat_id), + ["direct", "private", "team"], + ); + assert.lengthOf(new Set(saved.map(({ native_session_id }) => native_session_id)), 3); + assert.isString(saved[1]?.audience); + assert.isString(saved[2]?.audience); + } + }).pipe( + Effect.provide( + carryHarness({ + beforeTurn: ({ threadId }) => readCarryHook(threadId, current).pipe(Effect.asVoid), + providerSteers: steers, + holdRunning: () => (block ? hold : undefined), + }), + ), + ); + }).pipe(provideDeterministicTestRuntime), + ); + it.effect( "teammates carry only their own chat; a co-owner seat with file tools starts fresh", () => @@ -4040,7 +4236,7 @@ describe("WakeupRunner", () => { }).pipe(Effect.provide(carryHarness({ beforeTurn })), provideDeterministicTestRuntime); }); - it.effect.each(["shared", "co_owner", "owner_other_chat", "codex"] as const)( + it.effect.each(["shared", "co_owner", "owner_first_elsewhere", "codex"] as const)( "a %s turn never builds a change list", (seat) => { let rules = "Invented standing"; @@ -4072,7 +4268,7 @@ describe("WakeupRunner", () => { yield* wake("tidewater-second", seat === "codex" ? "direct" : "other-direct"); const sent = carriedSend(yield* carryProjection); const [first, row] = yield* carryRows; - if (seat === "co_owner" || seat === "shared") { + if (seat !== "codex") { assert.notStrictEqual(row?.threadId, first?.threadId); } else { assert.isTrue(sent.run.freshContext); @@ -4086,13 +4282,14 @@ describe("WakeupRunner", () => { row?.reason, seat === "codex" ? "provider" - : seat === "owner_other_chat" - ? "chat" - : seat === "shared" - ? "ended" - : "thread", + : seat === "shared" || seat === "owner_first_elsewhere" + ? "ended" + : "thread", + ); + assert.strictEqual( + row?.lane, + seat === "codex" || seat === "owner_first_elsewhere" ? "owner" : seat, ); - assert.strictEqual(row?.lane, seat === "codex" ? "owner" : seat); if (seat === "shared") { yield* sql`UPDATE kin_registers SET name = 'Changed private dispatch list' WHERE register_id = 'dispatch'`; yield* wake("tidewater-third", "other-direct"); @@ -4359,6 +4556,7 @@ describe("WakeupRunner", () => { { threadId: second!.thread_id, ownerThread: true, + ownerChat: { chatId: "direct", audience: null, authorized: true }, driver: "claudeAgent", model: selection, instructionsSha: storedKey.instructions, diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 49c23630015e..bb1b6a25c906 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -174,7 +174,14 @@ import { type Cursor, } from "./sessionChanges.ts"; import { readSessionDefinitions, type SessionDefinitions } from "./sessionDefinitions.ts"; -import { sessionAudience, singleChatWake } from "./sessionAudience.ts"; +import { + MIXED_WAKE_THREAD_PREFIX, + OWNER_CHAT_THREAD_PREFIX, + ownerSessionAudience, + ownerSessionWake, + sessionAudience, + singleChatWake, +} from "./sessionAudience.ts"; import { KinSessionContext, type SessionSnapshot } from "./turn/sessionContext.ts"; import { claude } from "./turn/providers/claude.ts"; import { KinCacheSessions, recordTurn as recordCachePartTurn } from "../host/cacheSessions.ts"; @@ -978,7 +985,8 @@ const make = Effect.gen(function* () { yield* Effect.logWarning("Kin carried turn context not read", { wakeupId: row.wakeupId }); } const marked = snapshot !== undefined && (yield* outsideRead(row)); - if (marked && snapshot?.audience !== undefined && shadow?.sent === "carried") + const ownerScoped = threadId.startsWith(OWNER_CHAT_THREAD_PREFIX); + if (marked && !ownerScoped && snapshot?.audience !== undefined && shadow?.sent === "carried") yield* sessionContext?.forget(threadId).pipe(provideSql) ?? Effect.void; if (shadow?.chatId != null && shadow.chatSeq !== null && shadow.chatChangeSeq !== null) { const cursor = yield* captureChatCursor(row, { @@ -996,8 +1004,17 @@ const make = Effect.gen(function* () { completed && !unread && snapshot !== undefined && - (snapshot.seen !== undefined || - (snapshot.audience !== undefined && (yield* singleChatWake(row, shadow.chatId)))) && + (ownerScoped + ? snapshot.seen !== undefined && + (yield* ownerSessionAudience(row, shadow.chatId).pipe( + Effect.flatMap((scope) => + scope !== undefined && scope.audience === (snapshot.audience ?? null) + ? ownerSessionWake(row, shadow.chatId!, scope) + : Effect.succeed(false), + ), + provideSql, + )) + : snapshot.audience !== undefined && (yield* singleChatWake(row, shadow.chatId))) && sessionContext !== undefined && last?.providerThreadId != null && !marked @@ -1229,7 +1246,16 @@ const make = Effect.gen(function* () { // wake-up, and this one stops taking more. if ( (yield* isAborted(row)) || - (yield* audienceChanged({ orgId, agentId, wakeupId }).pipe(provideSql)) + (yield* audienceChanged({ orgId, agentId, wakeupId }).pipe(provideSql)) || + (threadId.startsWith(OWNER_CHAT_THREAD_PREFIX) && + !(yield* Effect.gen(function* () { + const [scope] = yield* sql<{ chatId: string }>`SELECT chat_id AS "chatId" + FROM kin_agent_threads WHERE org_id = ${orgId} AND thread_id = ${threadId} + AND chat_id IS NOT NULL AND ended_at IS NULL`; + if (scope === undefined) return false; + const owner = yield* ownerSessionAudience(row, scope.chatId); + return owner !== undefined && (yield* ownerSessionWake(row, scope.chatId, owner)); + }).pipe(provideSql))) ) { steering.open = false; yield* queue.release({ @@ -1725,10 +1751,12 @@ const make = Effect.gen(function* () { const ownerThreadOf = Effect.fn("WakeupRunner.ownerThreadOf")(function* ( orgId: KinOrgId, agentId: KinAgentId, + chatId: string, ) { const [live] = yield* sql<{ threadId: ThreadId }>`SELECT thread_id AS "threadId" FROM kin_agent_threads WHERE org_id = ${orgId} AND agent_id = ${agentId} - AND ended_at IS NULL AND chat_id IS NULL AND substr(thread_id, 1, 4) = 'kin:' + AND ended_at IS NULL AND chat_id = ${chatId} + AND substr(thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) = ${OWNER_CHAT_THREAD_PREFIX} ORDER BY started_at DESC, thread_id DESC LIMIT 1`; return live?.threadId; }); @@ -1763,6 +1791,9 @@ const make = Effect.gen(function* () { agentId: row.agentId, chatId, sessionWakeupIds: facts.sessionWakeupIds, + ...(row.threadId?.startsWith(OWNER_CHAT_THREAD_PREFIX) + ? { ownerWakeupId: row.wakeupId } + : {}), from, to: cursor, now: cursor.at, @@ -2236,12 +2267,26 @@ const make = Effect.gen(function* () { confinedCandidate && turnChatId !== null ? yield* sessionAudience(orgId, turnChatId).pipe(provideSql) : null; - const candidate = - claudeCarry && - (yield* ownerAlone(row).pipe(provideSql)) && + const bills = yield* billsOnly(row).pipe(provideSql); + const ownerReaders = initialAudience === "owner_only" && - !(yield* billsOnly(row).pipe(provideSql)); - const candidateThread = candidate ? yield* ownerThreadOf(orgId, agentId) : undefined; + !bills && + turnChatId !== null && + (yield* ownerAlone(row).pipe(provideSql)) + ? yield* ownerSessionAudience(row, turnChatId).pipe(provideSql) + : undefined; + const ownerAtBuild = + ownerReaders !== undefined && + turnChatId !== null && + (lane === undefined || lane.chatId === turnChatId) && + (yield* ownerSessionWake(row, turnChatId, ownerReaders).pipe(provideSql)) + ? ownerReaders + : undefined; + const candidate = claudeCarry && ownerAtBuild !== undefined; + const candidateThread = + candidate && turnChatId !== null + ? yield* ownerThreadOf(orgId, agentId, turnChatId) + : undefined; const previous = candidateThread === undefined || sessionContext === undefined ? undefined @@ -2254,7 +2299,7 @@ const make = Effect.gen(function* () { orgId, chatId, pinned.head, - confinedCandidate ? undefined : agentId, + candidate || confinedCandidate ? undefined : agentId, ); }).pipe( provideSql, @@ -2360,11 +2405,9 @@ const make = Effect.gen(function* () { orgName: record.orgName, name: record.name, }); - // The owner's own turns share one thread; any other, a co-owner's included, runs on - // its chat's own, so no model context crosses chats. Ended threads can't be - // registered again. - const alone = !shared && (yield* ownerAlone(row).pipe(provideSql)); - const chatId = alone ? null : ((yield* turnChat(row).pipe(provideSql))?.chatId ?? null); + const chatId = turnChatId; + const ownerScoped = !shared && ownerAtBuild !== undefined; + const mixed = !shared && ownerReaders !== undefined && !ownerScoped; // A stranger's pull request is reviewed, and bills are read, on a thread that lists // only that turn's tools. const review = shared && (yield* outsideReview(row).pipe(provideSql)) !== undefined; @@ -2381,20 +2424,31 @@ const make = Effect.gen(function* () { ? `${TRIAGE_THREAD_PREFIX}${issueHash}:` : review ? REVIEW_THREAD_PREFIX - : (yield* billsOnly(row).pipe(provideSql)) + : bills ? BILLS_THREAD_PREFIX : undefined; - const prefix = confined ?? (shared ? SHARED_THREAD_PREFIX : "kin:"); + const prefix = + confined ?? + (shared + ? SHARED_THREAD_PREFIX + : ownerScoped + ? OWNER_CHAT_THREAD_PREFIX + : mixed + ? MIXED_WAKE_THREAD_PREFIX + : "kin:"); const [live] = yield* sql<{ threadId: ThreadId }>`SELECT thread_id AS "threadId" FROM kin_agent_threads WHERE org_id = ${orgId} AND agent_id = ${agentId} AND ended_at IS NULL AND chat_id IS ${chatId} + AND (${prefix !== "kin:"} OR ( + substr(thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) <> ${OWNER_CHAT_THREAD_PREFIX} + AND substr(thread_id, 1, ${MIXED_WAKE_THREAD_PREFIX.length}) <> ${MIXED_WAKE_THREAD_PREFIX})) AND substr(thread_id, 1, ${prefix.length}) = ${prefix} AND (${confined === undefined ? 0 : 1} = 1 OR (substr(thread_id, 1, ${REVIEW_THREAD_PREFIX.length}) <> ${REVIEW_THREAD_PREFIX} AND substr(thread_id, 1, ${BILLS_THREAD_PREFIX.length}) <> ${BILLS_THREAD_PREFIX} AND substr(thread_id, 1, ${TRIAGE_THREAD_PREFIX.length}) <> ${TRIAGE_THREAD_PREFIX})) ORDER BY started_at DESC, thread_id DESC LIMIT 1`; - let existingThreadId = !alone && chatId === null ? null : (live?.threadId ?? null); + let existingThreadId = mixed || chatId === null ? null : (live?.threadId ?? null); if (existingThreadId !== null) { const existing = yield* threads .getThreadRecords(existingThreadId, []) @@ -2471,7 +2525,7 @@ const make = Effect.gen(function* () { }), ); row = claimed; - const ownerClaude = alone && confined === undefined && driver === claude.driver; + const ownerClaude = ownerScoped && driver === claude.driver; const confinedClaude = confinedCandidate && shared && @@ -2486,7 +2540,7 @@ const make = Effect.gen(function* () { sessionContext?.previous({ orgId, agentId, threadId }) ?? Effect.undefined ); const chatSnapshot = - !claudeCarry || turnChatId === null || alone || confined !== undefined + !claudeCarry || turnChatId === null || mixed || confined !== undefined ? undefined : yield* ( sessionContext?.previous({ @@ -2495,10 +2549,19 @@ const make = Effect.gen(function* () { chatId: KinChatId.make(turnChatId), }) ?? Effect.undefined ); + const ownerNow = + ownerClaude && chatId !== null + ? yield* ownerSessionAudience(row, chatId) + : undefined; + const expectedAudience = ownerClaude + ? (ownerAtBuild?.audience ?? null) + : audienceAtBuild; const audienceNow = - confinedClaude && chatId !== null ? yield* sessionAudience(orgId, chatId) : null; - const scopedAudience = audienceAtBuild === audienceNow ? audienceNow : null; - if (confinedClaude && scopedAudience !== null) capturedAudience = scopedAudience; + confinedClaude && chatId !== null + ? yield* sessionAudience(orgId, chatId) + : (ownerNow?.audience ?? null); + const scopedAudience = expectedAudience === audienceNow ? audienceNow : null; + capturedAudience = scopedAudience; const liveToolList = agentSessions?.lastToolList(threadId) ?? null; const toolListSha = liveToolList === null && @@ -2510,7 +2573,22 @@ const make = Effect.gen(function* () { : liveToolList; const facts = yield* carryFacts(row, { threadId, - ownerThread: alone && confined === undefined, + ownerThread: ownerScoped, + ...(ownerClaude && chatId !== null && ownerAtBuild !== undefined + ? { + ownerChat: { + chatId, + audience: scopedAudience, + ...(stored?.audience === undefined + ? {} + : { seenAudience: stored.audience }), + authorized: + ownerNow !== undefined && + expectedAudience === audienceNow && + (yield* ownerSessionWake(row, chatId, ownerNow)), + }, + } + : {}), ...(confinedClaude && chatId !== null ? { confined: { @@ -2564,7 +2642,12 @@ const make = Effect.gen(function* () { const shadowDecision = hostSettings.kinSessionCarry ? decision : decideCarry({ ...facts.facts, enabled: true }); - let reason: string | null = shadowDecision.carry ? null : shadowDecision.reason; + let reason: string | null = + mixed && claudeCarry + ? "other_chat" + : shadowDecision.carry + ? null + : shadowDecision.reason; let sent: "fresh" | "carried" | "refill" = "fresh"; let summarized = false; let text = full; @@ -2749,7 +2832,8 @@ const make = Effect.gen(function* () { ); const standing = confinedClaude ? confinedStanding : promptFingerprint.standing; if ( - (ownerClaude || (confinedClaude && capturedAudience !== null)) && + ((ownerClaude && (ownerAtBuild?.direct || capturedAudience !== null)) || + (confinedClaude && capturedAudience !== null)) && built !== undefined && (taken === undefined || !send.freshContext) ) @@ -2768,16 +2852,27 @@ const make = Effect.gen(function* () { billPhotos, offersBillsAdd: canAddBills, })); - if ( - confinedClaude && - !send.freshContext && - chatId !== null && - capturedAudience !== (yield* sessionAudience(orgId, chatId).pipe(provideSql)) - ) { - yield* sql`UPDATE kin_wakeups SET carry_json = - json_set(carry_json, '$.carry', json('false'), '$.sent', 'fresh', '$.reason', 'members') + if (chatId !== null && (ownerClaude || (confinedClaude && !send.freshContext))) { + const changed = ownerClaude + ? yield* ownerSessionAudience(row, chatId).pipe( + Effect.flatMap((audience) => + audience !== undefined && audience.audience === ownerAtBuild?.audience + ? ownerSessionWake(row, chatId, audience).pipe( + Effect.map((own) => (own ? null : "other_chat")), + ) + : Effect.succeed("members"), + ), + provideSql, + ) + : capturedAudience === (yield* sessionAudience(orgId, chatId).pipe(provideSql)) + ? null + : "members"; + if (changed !== null) { + yield* sql`UPDATE kin_wakeups SET carry_json = + json_set(carry_json, '$.carry', json('false'), '$.sent', 'fresh', '$.reason', ${changed}) WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId}`; - return yield* cleanup(row, "retry"); + return yield* cleanup(row, "retry"); + } } if (fileShown) yield* markFileRead(row, "file").pipe(provideSql); if (attachments.some(shownAsPicture)) diff --git a/apps/server/src/kin/lead/sessionAudience.ts b/apps/server/src/kin/lead/sessionAudience.ts index dfdc59c15b5e..301a022cb6d8 100644 --- a/apps/server/src/kin/lead/sessionAudience.ts +++ b/apps/server/src/kin/lead/sessionAudience.ts @@ -118,3 +118,98 @@ export const confinedTranscriptProven = Effect.fn("KinSessionAudience.transcript return changed === undefined; }, ); + +export const OWNER_CHAT_THREAD_PREFIX = "kin:owner-chat:"; +export const MIXED_WAKE_THREAD_PREFIX = "kin:mixed-wake:"; + +type Wake = { readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly wakeupId: string }; + +/** The owner is an active reader, and no other person can read the chat. */ +export const ownerSessionAudience = Effect.fn("KinSessionAudience.ownerChat")(function* ( + turn: Pick, + chatId: string, +) { + const sql = yield* SqlClient.SqlClient; + return yield* sql.withTransaction( + Effect.gen(function* () { + const [chat] = yield* sql<{ owner: string; direct: number }>` + SELECT a.owner_person_id AS owner, (l.owner_chat_id = c.chat_id) AS direct + FROM kin_chats c JOIN kin_leads l ON l.org_id = c.org_id AND l.agent_id = ${turn.agentId} + JOIN kin_agents a USING (org_id, agent_id) + WHERE c.org_id = ${turn.orgId} AND c.chat_id = ${chatId} AND c.archived_at IS NULL + AND a.retired_at IS NULL + AND EXISTS (SELECT 1 FROM kin_chat_members m JOIN kin_people p USING (org_id, person_id) + WHERE m.org_id = c.org_id AND m.chat_id = c.chat_id AND m.left_at IS NULL + AND m.principal_kind = 'person' AND m.person_id = a.owner_person_id AND p.removed_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM kin_chat_members m + WHERE m.org_id = c.org_id AND m.chat_id = c.chat_id AND m.left_at IS NULL + AND m.principal_kind = 'person' AND m.person_id IS NOT a.owner_person_id) + LIMIT 1`; + if (chat === undefined) return undefined; + const direct = chat.direct === 1; + const audience = direct ? null : yield* sessionAudience(turn.orgId, chatId); + return direct || audience !== null ? { owner: chat.owner, direct, audience } : undefined; + }), + ); +}); + +/** A missing event lane is not proof of origin: only known owner-side triggers default to direct. */ +export const ownerSessionWake = Effect.fn("KinSessionAudience.ownerWake")(function* ( + turn: Wake, + chatId: string, + scope: { readonly owner: string; readonly direct: boolean }, +) { + const sql = yield* SqlClient.SqlClient; + const [scopeProof] = yield* sql<{ total: number; allowed: number }>` + SELECT COUNT(*) AS total, SUM(CASE + WHEN json_extract(e.json, '$.chatId') IS NOT NULL AND json_extract(e.json, '$.chatId') <> ${chatId} THEN 0 + WHEN json_extract(e.json, '$.origin.chatId') IS NOT NULL AND json_extract(e.json, '$.origin.chatId') <> ${chatId} THEN 0 + WHEN json_extract(e.json, '$.origin.personId') IS NOT NULL AND json_extract(e.json, '$.origin.personId') <> ${scope.owner} THEN 0 + WHEN EXISTS (SELECT 1 FROM json_each(e.json, '$.askedIn') src LEFT JOIN kin_wakeups parent + ON parent.org_id = e.org_id AND parent.wakeup_id = src.value + LEFT JOIN kin_agent_threads t ON t.org_id = parent.org_id AND t.thread_id = parent.thread_id + WHERE t.chat_id IS NOT ${chatId} OR t.agent_id IS NOT e.agent_id + OR substr(t.thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) IS NOT ${OWNER_CHAT_THREAD_PREFIX}) THEN 0 + WHEN e.tag IN ('chat.message', 'widget.action', 'chat.reaction') THEN CASE WHEN + json_extract(e.json, '$.chatId') = ${chatId} AND json_type(e.json, '$.origin') IS NULL + AND m.chat_id = ${chatId} AND m.status = 'posted' AND m.origin_json IS NULL AND m.relay_json IS NULL + AND COALESCE(m.client_message_id, '') NOT LIKE 'send:private:%' AND ${visibleToPeople(sql, "m")} + AND (m.discussion_id IS NULL OR EXISTS (SELECT 1 FROM kin_discussions d + WHERE d.org_id = m.org_id AND d.discussion_id = m.discussion_id + AND d.chat_id = m.chat_id + AND (d.ask_chat_id = m.chat_id OR EXISTS (SELECT 1 FROM kin_messages asked + WHERE asked.org_id = d.org_id AND asked.chat_id = d.chat_id + AND d.open_key = 'message:' || asked.message_id + AND asked.discussion_id = d.discussion_id AND asked.author_kind = 'human' + AND asked.author_person_id = ${scope.owner} + AND asked.origin_json IS NULL AND asked.relay_json IS NULL)))) + AND ((json_extract(e.json, '$.provenance._tag') = 'human' + AND json_extract(e.json, '$.provenance.personId') = ${scope.owner} + AND EXISTS (SELECT 1 FROM kin_chat_members member + WHERE member.org_id = e.org_id AND member.chat_id = ${chatId} + AND member.principal_kind = 'person' AND member.left_at IS NULL + AND member.person_id = ${scope.owner} + AND member.member_id = json_extract(e.json, '$.provenance.memberId')) + AND (e.tag = 'chat.reaction' OR (m.author_kind = 'human' AND m.author_person_id = ${scope.owner}))) + OR (e.tag = 'chat.message' AND m.discussion_id IS NOT NULL AND m.author_kind = 'agent' + AND m.author_agent_id = json_extract(e.json, '$.provenance.agentId'))) + THEN 1 ELSE 0 END + WHEN e.tag = 'task.finished' AND EXISTS (SELECT 1 FROM kin_agent_threads t + WHERE t.org_id = e.org_id AND t.agent_id = e.agent_id AND t.chat_id = ${chatId} + AND t.ended_at IS NULL AND t.thread_id = json_extract(e.json, '$.threadId') + AND substr(t.thread_id, 1, ${OWNER_CHAT_THREAD_PREFIX.length}) = ${OWNER_CHAT_THREAD_PREFIX}) THEN 1 + WHEN (${scope.direct} OR json_extract(e.json, '$.chatId') = ${chatId}) + AND ((json_extract(e.json, '$.provenance._tag') = 'system' AND + (e.tag IN ('pulse', 'routine', 'watchdog', 'resume', 'action.resolved') + OR (e.tag = 'deferral.due' AND json_type(e.json, '$.subject.answered') IS NULL) + OR (e.tag = 'github' AND COALESCE(json_extract(e.json, '$.askedBy'), ${scope.owner}) = ${scope.owner}))) + OR (e.tag = 'record.changed' AND json_extract(e.json, '$.provenance._tag') = 'human' + AND json_extract(e.json, '$.provenance.personId') = ${scope.owner})) THEN 1 + ELSE 0 END) AS allowed + FROM kin_events e LEFT JOIN kin_messages m ON m.org_id = e.org_id + AND m.message_id = json_extract(e.json, '$.messageId') + WHERE e.org_id = ${turn.orgId} AND e.agent_id = ${turn.agentId} AND e.wakeup_id = ${turn.wakeupId}`; + return ( + scopeProof !== undefined && scopeProof.total > 0 && scopeProof.total === scopeProof.allowed + ); +}); diff --git a/apps/server/src/kin/lead/sessionCarry.ts b/apps/server/src/kin/lead/sessionCarry.ts index bd8bb1034f35..5a348653d247 100644 --- a/apps/server/src/kin/lead/sessionCarry.ts +++ b/apps/server/src/kin/lead/sessionCarry.ts @@ -211,7 +211,12 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( readonly driver: string | undefined; readonly model: ModelSelection; readonly instructionsSha: string | null; - readonly idleChat?: string; + readonly ownerChat?: { + readonly chatId: string; + readonly audience: string | null; + readonly seenAudience?: string; + readonly authorized: boolean; + }; readonly confined?: { readonly chatId: string; readonly audience: string | null; @@ -247,7 +252,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( FROM kin_leads l LEFT JOIN kin_agents a USING (org_id, agent_id) WHERE l.org_id = ${orgId} AND l.agent_id = ${agentId} LIMIT 1`; const chat = - input.confined?.chatId ?? input.idleChat ?? (yield* turnChat(wakeup))?.chatId ?? null; + input.confined?.chatId ?? input.ownerChat?.chatId ?? (yield* turnChat(wakeup))?.chatId ?? null; const members = chat === null ? [] @@ -262,7 +267,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( model: fingerprintJson(input.model), instructions: input.instructionsSha, lead: fingerprintJson(lead ?? null), - members: input.confined?.audience ?? fingerprintJson(members), + members: input.confined?.audience ?? input.ownerChat?.audience ?? fingerprintJson(members), standing: input.standing, stop: input.stopRevision, }; @@ -282,7 +287,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( w.standing_key AS fingerprint, w.started_at AS "startedAt", w.context_tokens AS "contextTokens", r.provider_thread_id AS "providerThreadId", w.aborted_at IS NOT NULL AS aborted, - CASE WHEN t.ended_at IS NOT NULL OR t.thread_id IS NULL OR t.chat_id IS NOT ${input.confined?.chatId ?? null} + CASE WHEN t.ended_at IS NOT NULL OR t.thread_id IS NULL OR t.chat_id IS NOT ${input.confined?.chatId ?? input.ownerChat?.chatId ?? null} THEN 1 ELSE 0 END AS ended FROM kin_wakeups w LEFT JOIN kin_agent_threads t USING (org_id, agent_id, thread_id) @@ -390,9 +395,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( ? "shared" : !ownerThread ? "co_owner" - : chat !== lead?.ownerChat - ? "owner_other_chat" - : "owner"; + : "owner"; const sessionExists = sessionStart !== undefined && history.some((member) => member.wakeupId === sessionStart); const endedDetail = @@ -450,12 +453,14 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( provider: input.driver, ownerThread, confined: confined !== undefined, - otherChatText, + otherChatText: otherChatText || input.ownerChat?.authorized === false, audienceChanged: - confined?.seenAudience !== undefined && confined.seenAudience !== confined.audience, + (confined?.seenAudience !== undefined && confined.seenAudience !== confined.audience) || + (input.ownerChat?.seenAudience !== undefined && + input.ownerChat.seenAudience !== input.ownerChat.audience), sameChat: chat !== null && - (confined !== undefined || chat === lead?.ownerChat) && + (confined !== undefined || input.ownerChat !== undefined || chat === lead?.ownerChat) && (priorFingerprint === undefined || chat === priorFingerprint.chat), previousCompleted: previous?.status === "completed" && @@ -484,6 +489,8 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( sameMembers: confined === undefined ? members.length <= FINGERPRINT_ROWS_LIMIT && + (input.ownerChat?.audience == null || + input.ownerChat.audience === input.ownerChat.seenAudience) && fingerprint.members === priorFingerprint?.members : confined.audience !== null && confined.audience === confined.seenAudience && diff --git a/apps/server/src/kin/lead/sessionChanges.ts b/apps/server/src/kin/lead/sessionChanges.ts index 9c26c38e0070..518c9895e825 100644 --- a/apps/server/src/kin/lead/sessionChanges.ts +++ b/apps/server/src/kin/lead/sessionChanges.ts @@ -1,3 +1,4 @@ +import { ownerSessionAudience, ownerSessionWake } from "./sessionAudience.ts"; import type { KinAgentId, KinOrgId, KinWakeupId } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; @@ -158,6 +159,7 @@ export const captureChatCursor = Effect.fn("KinSessionChanges.captureChatCursor" }); interface Input { + readonly ownerWakeupId?: string; readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly chatId: string; @@ -837,7 +839,18 @@ export const sessionChanges = Effect.fn("KinSessionChanges.since")(function* (in WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} AND owner_chat_id = ${input.chatId} LIMIT 1`, ); - if (owner === undefined) return yield* new SessionChangesNotOwnerChat({}); + if (owner === undefined) { + const scope = + input.ownerWakeupId === undefined + ? undefined + : yield* ownerSessionAudience(input, input.chatId); + if ( + scope === undefined || + input.ownerWakeupId === undefined || + !(yield* ownerSessionWake({ ...input, wakeupId: input.ownerWakeupId }, input.chatId, scope)) + ) + return yield* new SessionChangesNotOwnerChat({}); + } const notes = input.definitions === undefined ? [] diff --git a/apps/server/src/kin/team/KinTeam.test.ts b/apps/server/src/kin/team/KinTeam.test.ts index ff0d577c2a16..9a7f5ea668c2 100644 --- a/apps/server/src/kin/team/KinTeam.test.ts +++ b/apps/server/src/kin/team/KinTeam.test.ts @@ -510,6 +510,31 @@ 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)); + + 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 + WHERE org_id = ${orgId} AND thread_id = ${threadId}`; + assert.isString(old?.ended_at); + assert.isFalse(identity.isLeadThread(threadId)); + }).pipe(Effect.provide(layer)), +); + // Rhea names Finance and the Chief of staff in the Team room: Kin opens their discussion once, // however often the message is handled. Finance, named first, takes the first discussion turn on // her words; the Chief of staff, whose call it is, is next. One name or none, a teammate's words, diff --git a/apps/server/src/kin/team/KinTeam.ts b/apps/server/src/kin/team/KinTeam.ts index a05c229baab5..af20deee066b 100644 --- a/apps/server/src/kin/team/KinTeam.ts +++ b/apps/server/src/kin/team/KinTeam.ts @@ -38,6 +38,8 @@ import { KinChatService } from "../chat/KinChatService.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { SHARED_REFUSAL, aborted } from "../lead/Audience.ts"; import { KinEventQueue } from "../lead/KinEventQueue.ts"; +import { onPersonJoined, tellStopped } from "../lead/ChatSharing.ts"; +import { KinStop } from "../lead/KinStop.ts"; import { outsideStamp, stampEvent } from "../lead/OutsideContent.ts"; import { teamAgent } from "../lead/LeadAccess.ts"; import { resolveLead } from "../lead/LeadMemory.ts"; @@ -240,6 +242,7 @@ const make = Effect.gen(function* () { const memory = yield* Effect.serviceOption(KinMemoryChanges); const hub = yield* KinChatHub; const queue = yield* KinEventQueue; + const stop = yield* Effect.serviceOption(KinStop); const access = Effect.provideService(SqlClient.SqlClient, sql); const lead = (scope: McpInvocationScope) => resolveLead(scope).pipe( @@ -313,12 +316,31 @@ const make = Effect.gen(function* () { present.add(identity.owner.personId); } for (const personId of yield* ownerLevelPeople(orgId).pipe(access)) - if (!present.has(personId as KinPersonId)) + if (!present.has(personId as KinPersonId)) { yield* join( { _tag: "person", personId: personId as KinPersonId }, "member", TEAM_ROOM_MUTED, ); + const joined = yield* onPersonJoined({ orgId, chatId: room.chatId, personId }).pipe(access); + yield* sql.afterCommit( + Effect.gen(function* () { + for (const threadId of joined.threads) + yield* identity.endAgentThread({ orgId, threadId }).pipe(Effect.ignore); + if (Option.isSome(stop) && joined.turns.length > 0) + yield* stop.value.abortTurns( + orgId, + joined.turns.map((turn) => KinWakeupId.make(turn.wakeupId)), + ); + if (joined.stopped.length > 0) + yield* tellStopped({ orgId, chatId: room.chatId, lines: joined.stopped }).pipe( + Effect.provideService(KinChatRepository, repo), + Effect.provideService(KinChatHub, hub), + Effect.ignore({ log: "Warn", message: "KinTeam.tellStopped" }), + ); + }), + ); + } for (const agent of all) if ( !members.some((m) => m.principal._tag === "agent" && m.principal.agentId === agent.agentId) diff --git a/verification/kin/reply/README.md b/verification/kin/reply/README.md index 4de53c9d55b8..5c4b1c7fa2e5 100644 --- a/verification/kin/reply/README.md +++ b/verification/kin/reply/README.md @@ -126,11 +126,11 @@ The guard "Steer waits after a Stop" (rule 12) now rests on code, from kin's `15 A provider session remembers earlier prompts, tool results and the agent's own words. Fresh starts with an empty session and adds only the new wake's text. Carry sends the new request with the earlier text still there. In the model, each piece has a kind and the chat and audience entitled to it: readers and askers, their view, and the seat and tools. The kinds cover the instructions and briefing, recent and new chat lines, the change list, attachments and events, tool output, the agent's own words, hand-off answers and outside text. -**Rule.** At the request boundary, `SessionOnlyToEntitled` checks the transcript a request continues. That transcript must come from its own chat, have been built for readers and a view that authorize the retained text, and still match the seat and tool list. An aborted transcript may not continue. Outside text is scoped to the wake that saw it: an owner's mail check-in may continue a clean session and add that wake's mail, but the next wake must start fresh. A hand-off answer and another chat's lines are scoped the same way in the per-chat design: the wake that holds them starts fresh, and so does the next one, since a fresh start for the chat would not show them (hand-off rows are hidden from people). The invariant checks the previous transcript, not the new mail the current wake is allowed to see. +**Rule.** At the request boundary, `SessionOnlyToEntitled` checks the transcript a request continues. That transcript must come from its own chat, have been built for readers and a view that authorize the retained text, and still match the seat and tool list. An aborted transcript may not continue. Outside text is scoped to the wake that saw it: an owner's mail check-in may continue a clean session and add that wake's mail, but the next wake must start fresh. A wake carrying another chat’s text starts fresh. It cannot replace an owner chat’s clean slot; the next wake in that chat can continue the earlier clean session. The confined model separately rejects a predecessor that retained foreign text. The invariant checks the previous transcript, not the new mail the current wake is allowed to see. -**Settings.** `PerChat = TRUE` (default) checks per-chat carry, including Team and confined seats, with exact reader, role, visibility, view, seat and tool scope. This is the policy under a confined provider; product seats with native shell and file access (owner-tier Team, other owner-tier rooms and co-owner direct chats) are not enabled by J3c. Set `PerChat = FALSE` in a scratch checkout to check the older owner-only policy. Run `node scripts/kin-model.ts reply` or `node scripts/kin-model.ts reply --variants`. +**Settings.** `PerChat = TRUE` (default) checks per-chat carry, including Team and confined seats, with exact reader, role, visibility, view, seat and tool scope. The owner’s direct chat, private group and Team room are distinct scopes. A new reader ends the owner-only scope; co-owner direct and owner-tier rooms with another reader do not carry in the product. The shared room and confined fixtures continue to exercise the confined policy. Set `PerChat = FALSE` in a scratch checkout to check the older owner-only policy. Run `node scripts/kin-model.ts reply` or `node scripts/kin-model.ts reply --variants`. -**Bound.** One lead, at most three requests across the owner chat, two rooms with the same readers, a co-owner chat, the Team room and a confined chat. One join and one demotion change what can be read; either can interrupt a running turn. One visibility change can widen a room between requests. A restart leaves completed SQLite snapshots and their native session IDs in place. A large warm session may summarize; a large cold one cannot resume. A summary opens a new session for its original chat only, and a session that read outside text cannot make a summary. Independent reply-delivery and provider-session branches share the model but not their state products: whether a reply was delivered, how many bubbles it had and how often the wake retried do not authorize a provider transcript. The original reply liveness rules still range over the same reply transitions. +**Bound.** One lead, at most three requests across the owner chat, two confined rooms with the same readers, a co-owner chat, an owner-alone private group, the Team room and a confined direct chat. One join and one demotion change what can be read; either can interrupt a running turn. One visibility change can widen a room between requests. A restart leaves completed SQLite snapshots and their native session IDs in place. A large warm session may summarize; a large cold one cannot resume. A summary opens a new session for its original chat only, and a session that read outside text cannot make a summary. Independent reply-delivery and provider-session branches share the model but not their state products: whether a reply was delivered, how many bubbles it had and how often the wake retried do not authorize a provider transcript. The original reply liveness rules still range over the same reply transitions. **Where the carry decision gets its facts.** Source paths below are relative to `apps/server/src/kin/` at train 16's tip. The source table below describes the train 16 baseline; J3c uses `lead/sessionAudience.ts` for the per-chat scope and `lead/WakeupRunner.ts` for same-briefing carry admission. @@ -178,3 +178,5 @@ TLC 1.7.4, one worker per run; wall times reflect concurrent checks on the same **Checked 2026-11-29** for train 18 J3c: `PerChat = TRUE` by default, with Team and confined scopes, reader roles and visibility. All 18 rules hold over 1,719,959 distinct states in 622,154 ms; 40/40 broken variants caught in 60,915 ms, including join, room role demotion and visibility widening. This checks abstract entitlement, not that native provider tools are confined. **Re-confirmed 2026-11-29** on train 18 of 29 Nov (every cache lever: the shared first block, the eval placement runner, keep-warm, one stored session per chat with notes and Kin's compaction, the daily figure, the note wording and file margin, the summary wording, and the confined-status fix, joined on kin `de2553ba2c6`; no spec change, `PerChat = TRUE` as committed). All 18 rules hold over 1,719,959 states in 612 s; 40/40 variants caught in 61 s. The covered files the line changes are `lead/WakeupRunner.ts` and `lead/sessionCarry.ts`, as J3a, J3b and J3c describe above. The join adds nothing to them. Its fixes sit in keep-warm placement and its prompt, the daily figure and the Usage labels, none of which decides who a session may hold. + +**Checked 2026-11-29** for train 19 A: all 18 rules hold over 1,794,442 distinct states (674,893 ms), and 43/43 mutations are caught (69,955 ms). The three added mutations expose retained direct-chat words in a private group, owner-only words to a newcomer, and mixed-wake words to a later clean group request. `SessionOnlyToEntitled` rejects each at a request that would receive the forbidden text. diff --git a/verification/kin/reply/Reply.tla b/verification/kin/reply/Reply.tla index 98f4c39c4bf9..9601940cce39 100644 --- a/verification/kin/reply/Reply.tla +++ b/verification/kin/reply/Reply.tla @@ -618,8 +618,9 @@ Restart == reply rules observe delivery, not provider history, and the session rules observe requests, not bubbles or retries. Projecting away the other state avoids their Cartesian product. *) ReplyBranch == [checking |-> FALSE] -Chats == {"owner chat", "room A", "room B", "co-owner chat", "team room", "confined chat"} +Chats == {"owner chat", "room A", "room B", "co-owner chat", "team room", "private group", "confined chat"} Rooms == {"room A", "room B"} +OwnerChats == {"owner chat", "private group", "team room"} SessionTurnLimit == 3 PerChatPolicy == PerChat \/ Broken \in @@ -631,7 +632,7 @@ NoScope == [chat |-> "none", readers |-> {}, view |-> "none", seat |-> "none", r NoTurn == [scope |-> NoScope, tools |-> "none", carried |-> FALSE, kind |-> "none", outside |-> FALSE, summaryChat |-> "none"] NoTranscript == [status |-> "none", scope |-> NoScope, tools |-> "none", - outsideMarked |-> FALSE, approved |-> FALSE, labels |-> {}, + outsideMarked |-> FALSE, approved |-> FALSE, labels |-> {}, privateText |-> {}, heat |-> "warm", summarized |-> FALSE] SessionInit == [checking |-> TRUE, slots |-> [chat \in Chats |-> NoTranscript], @@ -639,24 +640,25 @@ SessionInit == [checking |-> TRUE, slots |-> [chat \in Chats |-> NoTranscript], Scope(chat) == [chat |-> chat, - readers |-> CASE chat = "owner chat" -> IF session.joinedChat = chat THEN {"Rhea", "Ben"} + readers |-> CASE chat \in OwnerChats -> IF session.joinedChat = chat THEN {"Rhea", "Ben"} ELSE {"Rhea"} [] chat = "co-owner chat" -> {"Meera"} [] OTHER -> IF session.joinedChat = chat THEN {"Rhea", "Asha", "Ben"} ELSE {"Rhea", "Asha"}, - view |-> CASE chat = "owner chat" /\ session.joinedChat # chat -> "owner" + view |-> CASE chat \in OwnerChats /\ session.joinedChat # chat -> "owner" [] chat = "co-owner chat" /\ ~session.demoted -> "owner facts" [] chat \in Rooms -> "room view" [] OTHER -> "shared", roles |-> IF chat = "room A" /\ session.demoted THEN "member" ELSE "original", visibility |-> IF chat = "room A" /\ session.widened THEN "wider" ELSE "original", - seat |-> CASE chat = "owner chat" /\ session.joinedChat # chat -> "owner" + seat |-> CASE chat \in OwnerChats /\ session.joinedChat # chat -> "owner" [] chat = "confined chat" -> "confined" [] OTHER -> "shared"] WakeKinds(chat) == CASE chat = "owner chat" -> {"chat", "mail", "approved draft"} [] chat \in Rooms -> {"chat", "hand-off answer", "mixed chats", "changed briefing"} + [] chat = "private group" -> {"chat", "mixed chats"} [] chat = "co-owner chat" -> {"chat", "narrow tools"} [] OTHER -> {"chat"} @@ -670,6 +672,7 @@ Briefing(scope) == (IF scope.seat # "owner" THEN {} ELSE {"standing rules and memory index", "work and changes", "schedules and check-ins", "entry points and declined asks", "feedback", "budget context"}) +OwnerText(chat) == <<"owner chat text", chat>> NewLabels(kind, outside) == {"new chat lines"} \cup (IF kind \in {"hand-off answer", "mixed chats", "approved draft"} THEN {kind} ELSE {}) \cup @@ -678,9 +681,12 @@ NewLabels(kind, outside) == \* Another chat's text, which a fresh start here would not show: like outside text, it ends the session. OtherChatText == {"hand-off answer", "mixed chats"} -Previous(chat) == session.slots[ThreadFor(chat)] +Previous(chat) == + IF Broken = "owner-cross-chat" /\ chat = "private group" + THEN session.slots["owner chat"] + ELSE session.slots[ThreadFor(chat)] PolicyAllows(scope) == - IF PerChatPolicy THEN scope.chat \in Chats + IF PerChatPolicy THEN scope.chat \in (Chats \ OwnerChats) \/ scope.seat = "owner" ELSE scope.chat = "owner chat" /\ scope.seat = "owner" /\ scope.readers = {"Rhea"} SameAudience(scope, prior) == @@ -692,13 +698,14 @@ SameAudience(scope, prior) == Entitled(scope, kind, prior) == /\ PolicyAllows(scope) /\ kind \notin {"hand-off answer", "mixed chats", "changed briefing", "approved draft"} - /\ ThreadFor(scope.chat) = ThreadFor(prior.scope.chat) + /\ (ThreadFor(scope.chat) = ThreadFor(prior.scope.chat) \/ Broken = "owner-cross-chat") /\ SameAudience(scope, prior) /\ scope.seat = prior.scope.seat /\ Tools(kind) = prior.tools /\ (prior.status = "completed" \/ (Broken = "carry-aborted" /\ prior.status = "aborted")) /\ ~prior.approved /\ (~prior.outsideMarked \/ Broken = "carry-after-outside") - /\ (prior.labels \cap OtherChatText = {} \/ Broken = "carry-after-handoff") + /\ (prior.labels \cap OtherChatText = {} \/ Broken = "carry-after-handoff" \/ + (Broken = "owner-reuse-mixed" /\ scope.chat = "private group")) MayCarry(scope, kind, prior) == /\ Entitled(scope, kind, prior) @@ -724,6 +731,9 @@ ClaimSession == IN CASE Broken = "summary-other-chat" /\ chat = "room A" /\ Previous("owner chat").summarized -> StartSession(scope, kind, FALSE, "owner chat") [] MayReadSummary(scope, kind, prior) -> StartSession(scope, kind, FALSE, chat) + [] Broken = "owner-join-retains-private" /\ chat = "private group" + /\ session.joinedChat = chat /\ prior.status = "completed" /\ prior.scope.seat = "owner" + -> StartSession(scope, kind, TRUE, "none") [] MayCarry(scope, kind, prior) -> StartSession(scope, kind, TRUE, "none") [] OTHER -> StartSession(scope, kind, FALSE, "none") @@ -760,10 +770,16 @@ ReadOutside == Close(request, status) == LET labels == CurrentText(request) \cup (IF status = "completed" THEN {"tool output", "agent words"} ELSE {}) - IN [session EXCEPT !.slots[ThreadFor(request.scope.chat)] = + IN IF request.scope.chat \in OwnerChats /\ request.kind \in OtherChatText + /\ Broken # "owner-reuse-mixed" + THEN [session EXCEPT !.active = NoTurn] + ELSE [session EXCEPT !.slots[ThreadFor(request.scope.chat)] = [status |-> status, scope |-> request.scope, tools |-> request.tools, outsideMarked |-> request.outside \/ (request.carried /\ Previous(request.scope.chat).outsideMarked), - approved |-> request.kind = "approved draft", labels |-> labels, heat |-> "warm", summarized |-> FALSE], + approved |-> request.kind = "approved draft", labels |-> labels, + privateText |-> (IF request.scope.seat = "owner" THEN {OwnerText(request.scope.chat)} ELSE {}) + \cup (IF request.carried THEN Previous(request.scope.chat).privateText ELSE {}), + heat |-> "warm", summarized |-> FALSE], !.active = NoTurn] CompleteSession == @@ -782,7 +798,7 @@ InterruptIn(chat) == JoinSessionChat == /\ SessionStep /\ session.joinedChat = "none" - /\ \E chat \in {"owner chat", "room A"} : + /\ \E chat \in {"owner chat", "room A", "private group", "team room"} : /\ (Previous(chat) # NoTranscript \/ session.active.scope.chat = chat) /\ session' = [InterruptIn(chat) EXCEPT !.joinedChat = chat] @@ -810,6 +826,9 @@ SessionOnlyToEntitled == /\ request.scope = prior.scope /\ prior.summarized /\ request.carried => + /\ \A piece \in prior.privateText : + /\ piece[2] = request.scope.chat + /\ request.scope.readers \subseteq {"Rhea"} /\ prior.heat # "cold large" /\ prior.status # "aborted" /\ \A label \in prior.labels : diff --git a/verification/kin/reply/view.ts b/verification/kin/reply/view.ts index 39bfb89ae66d..93253b290834 100644 --- a/verification/kin/reply/view.ts +++ b/verification/kin/reply/view.ts @@ -240,6 +240,21 @@ export const variants = [ breaks: "SessionOnlyToEntitled", what: "a chat reads a different chat's summary", }, + { + name: "owner-cross-chat", + breaks: "SessionOnlyToEntitled", + what: "a private group request retains words from the owner's direct chat", + }, + { + name: "owner-join-retains-private", + breaks: "SessionOnlyToEntitled", + what: "a new group reader gains the owner's previously private words", + }, + { + name: "owner-reuse-mixed", + breaks: "SessionOnlyToEntitled", + what: "an ordinary group request retains foreign text from an earlier mixed wake", + }, { name: "compact-marked", breaks: "SessionOnlyToEntitled", From 6ee746c3d85c09c2aa8699444d88ed1f6f6e40ab Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:11:16 +0530 Subject: [PATCH 2/8] test(kin): bind carry diagnostics to the stored owner chat The diagnostics fixture now names the concrete owner chat while retaining the same assertions for marks, upkeep and the actual predecessor. People-change: None; this keeps the session diagnostics coverage aligned with chat-scoped threads. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/lead/sessionCarry.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/server/src/kin/lead/sessionCarry.test.ts b/apps/server/src/kin/lead/sessionCarry.test.ts index d39ae48ff9f3..a7ee03831063 100644 --- a/apps/server/src/kin/lead/sessionCarry.test.ts +++ b/apps/server/src/kin/lead/sessionCarry.test.ts @@ -124,6 +124,7 @@ effectIt.effect("names the lane, mark source and ending behind a refusal", () => const input = { threadId: prior!.threadId, ownerThread: true, + ownerChat: { chatId: "direct", audience: null, authorized: true }, driver: "claudeAgent", model: selection, instructionsSha: null, From 13da8b7272c276c4bf2065e729ed2c4865278ea1 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:46:11 +0530 Subject: [PATCH 3/8] fix(kin): owner-chat threads keep a social lead's Social tools Owner turns now run on per-chat `kin:owner-chat:` threads that carry a chat id, but the social seat only counted threads with no chat, so a social or marketing lead lost social_read, social_draft and social_week in every chat with its owner. Owner-chat and mixed-wake threads now count as the owner's own, as their null-chat predecessor did. People-change: A social or marketing agent keeps its Social tools when the owner talks to it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/WakeupRunner.test.ts | 6 ++++++ apps/server/src/kin/social/seat.ts | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index b6028fad6627..8c54729b06a8 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -85,6 +85,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 { socialSeatThread } from "../social/seat.ts"; import * as TaskWake from "./TaskWake.ts"; import { sensitiveShown, turnSensitive } from "../work/sensitiveReads.ts"; import { BILLS_THREAD_PREFIX } from "./billsOnly.ts"; @@ -900,6 +901,11 @@ describe("WakeupRunner", () => { const alone = yield* turn("alone"); assert.deepStrictEqual(alone.audience, "owner_only"); assert.isTrue(alone.threadId.startsWith("kin:")); + // A social lead's own turn with its owner still lists Social's tools. + const [seat] = yield* sql<{ domain: string }>`SELECT domain FROM kin_leads`; + yield* sql`UPDATE kin_leads SET domain = 'social'`; + assert.isTrue(yield* socialSeatThread(ThreadId.make(alone.threadId))); + yield* sql`UPDATE kin_leads SET domain = ${seat!.domain}`; yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('teammate-member', 'org', 'owner-chat', 'person', 'teammate', 'member', ${at})`; const shared = yield* turn("shared"); diff --git a/apps/server/src/kin/social/seat.ts b/apps/server/src/kin/social/seat.ts index ce5864ba97e5..76fc2c117836 100644 --- a/apps/server/src/kin/social/seat.ts +++ b/apps/server/src/kin/social/seat.ts @@ -2,6 +2,8 @@ import type { ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as SqlClient from "effect/sql/SqlClient"; +import { MIXED_WAKE_THREAD_PREFIX, OWNER_CHAT_THREAD_PREFIX } from "../lead/sessionAudience.ts"; + /** A remit that includes social media: the agents that get Social's tools and section. */ export const isSocialDomain = (domain: string) => /^(social|marketing|content|brand)/.test(domain); @@ -12,10 +14,14 @@ export const isSocialDomain = (domain: string) => /^(social|marketing|content|br export const socialSeatThread = Effect.fn("KinSocial.seatThread")( function* (threadId: ThreadId) { const sql = yield* SqlClient.SqlClient; - // The lead's own thread only: a shared chat's turn (chat_id set) never carries them. + // The owner's own threads only (one per chat he alone reads, a mixed wake's, or the old one + // with no chat); a shared or co-owner chat's turn never carries them. + const owners = + threadId.startsWith(OWNER_CHAT_THREAD_PREFIX) || + threadId.startsWith(MIXED_WAKE_THREAD_PREFIX); const rows = yield* sql<{ domain: string }>`SELECT l.domain FROM kin_agent_threads t JOIN kin_leads l ON l.org_id = t.org_id AND l.agent_id = t.agent_id - WHERE t.thread_id = ${threadId} AND t.ended_at IS NULL AND t.chat_id IS NULL + WHERE t.thread_id = ${threadId} AND t.ended_at IS NULL AND (${owners} OR t.chat_id IS NULL) ORDER BY t.thread_id LIMIT 1`; return rows[0] !== undefined && isSocialDomain(rows[0].domain); }, From 572c9a2c7d08725b2a1358218025c0ddfb94145a Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:46:11 +0530 Subject: [PATCH 4/8] fix(kin): a task a mixed wake delegated is answered in T3's run T3 starts a run on the delegating thread when a task ends. A mixed owner wake's one-shot thread was never looked up again, so the task's wake started a second fresh run on a new thread while T3's ran on with no wake: two model runs per task. The wake now takes over T3's run on that live mixed thread; it stays a mixed wake (other_chat, no stored session, never selected by any chat). People-change: None; a task started from a mixed request no longer costs a second model run. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/WakeupRunner.test.ts | 51 +++++++++++++++++++ apps/server/src/kin/lead/WakeupRunner.ts | 20 +++++++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 8c54729b06a8..7194389ced2a 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -3900,6 +3900,57 @@ describe("WakeupRunner", () => { }).pipe(provideDeterministicTestRuntime), ); + it.effect("a task an owner's mixed wake delegated is answered in the run T3 started", () => + Effect.gen(function* () { + const held = yield* Deferred.make(); + yield* Effect.gen(function* () { + const sql = yield* seedCarry; + const queue = yield* KinEventQueue.KinEventQueue; + 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')`; + const mixed = yield* ownerSays("dispatch-mixed", "private"); + if (mixed._tag !== "chat.message") throw new Error("Expected a chat event"); + yield* queue.enqueue({ ...mixed, origin: { agentId, chatId: KinChatId.make("direct") } }); + yield* Fiber.join(yield* run()); + const asked = yield* carryProjection; + const task = yield* taskNotice(asked.thread.id, asked.runs[0]!, "dispatch"); + const { run: notice, message } = yield* task.dispatch; + yield* (yield* TaskWake.make).enqueue(message); + yield* (yield* ThreadManagement.ThreadManagementService) + .streamStoredEventsFrom({ + threadId: asked.thread.id, + afterSequence: 0, + eventType: "provider-turn.updated", + }) + .pipe( + Stream.filter( + ({ event }) => + event.type === "provider-turn.updated" && + event.payload.ordinal === notice.ordinal && + event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + ); + const answering = yield* run(); + yield* Deferred.succeed(held, undefined); + yield* Fiber.join(answering); + const last = (yield* carryRows).at(-1)!; + const [answer] = yield* sql<{ runId: string | null }>`SELECT run_id AS "runId" + FROM kin_wakeups WHERE wakeup_id = ${last.wakeupId}`; + // One run answers the finished task: the wake takes over T3's, never starts its own beside it. + assert.strictEqual(answer?.runId, notice.id); + // Still a mixed wake: no chat continues it or stores it as a session. + assert.include(last, { threadId: asked.thread.id, reason: "other_chat" }); + assert.deepStrictEqual(yield* sql`SELECT thread_id FROM kin_session_seen`, []); + }).pipe( + Effect.provide( + carryHarness({ holdRunning: (ordinal) => (ordinal === 2 ? held : undefined) }), + ), + ); + }).pipe(provideDeterministicTestRuntime), + ); + it.effect( "teammates carry only their own chat; a co-owner seat with file tools starts fresh", () => diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index bb1b6a25c906..39bc83a7b213 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -2448,7 +2448,25 @@ const make = Effect.gen(function* () { AND substr(thread_id, 1, ${BILLS_THREAD_PREFIX.length}) <> ${BILLS_THREAD_PREFIX} AND substr(thread_id, 1, ${TRIAGE_THREAD_PREFIX.length}) <> ${TRIAGE_THREAD_PREFIX})) ORDER BY started_at DESC, thread_id DESC LIMIT 1`; - let existingThreadId = mixed || chatId === null ? null : (live?.threadId ?? null); + // A task a mixed wake delegated reports on that wake's one-shot thread, where T3 has + // started a run for it: taking that run over keeps one run per finished task. + const noticeThreads = [ + ...new Set( + events.flatMap((event) => (event._tag === "task.finished" ? [event.threadId] : [])), + ), + ]; + const noticeThread = noticeThreads.length === 1 ? noticeThreads[0] : undefined; + const [mixedNotice] = + mixed && noticeThread?.startsWith(MIXED_WAKE_THREAD_PREFIX) === true + ? yield* sql<{ threadId: ThreadId }>`SELECT thread_id AS "threadId" + FROM kin_agent_threads WHERE org_id = ${orgId} AND agent_id = ${agentId} + AND thread_id = ${noticeThread} AND ended_at IS NULL AND chat_id IS ${chatId}` + : []; + let existingThreadId = mixed + ? (mixedNotice?.threadId ?? null) + : chatId === null + ? null + : (live?.threadId ?? null); if (existingThreadId !== null) { const existing = yield* threads .getThreadRecords(existingThreadId, []) From 15ea9d8331933df1fee168b52d56bcf677ee460c Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:02:10 +0530 Subject: [PATCH 5/8] fix(kin): retire old chat sessions when a reader returns Reopened memberships now run the same transactional fence as new joins. Keep execution receipts in the original audience, clarify Usage reasons, and pin the remaining owner-chat boundaries with regression and entitlement checks. People-change: Returning readers no longer allow an in-flight private conversation to finish for a wider audience; Kin also avoids a duplicate execution notice and explains fresh starts more accurately. Co-Authored-By: GPT-6.2 Sol --- .../src/features/usage/UsageKinCacheLine.tsx | 9 +- .../src/kin/chat/KinChatService.test.ts | 126 +++++++++++++- apps/server/src/kin/chat/KinChatService.ts | 21 ++- apps/server/src/kin/chat/KinGroups.ts | 49 ++---- apps/server/src/kin/chat/executionNotices.ts | 6 +- apps/server/src/kin/chat/layer.ts | 9 +- apps/server/src/kin/chat/sharing.ts | 13 +- apps/server/src/kin/lead/ChatSharing.ts | 42 +++++ apps/server/src/kin/lead/WakeupRunner.test.ts | 160 ++++++++++++++++-- .../src/kin/lead/WakeupRunner.testkit.ts | 11 +- apps/server/src/kin/people/KinPeople.ts | 76 ++++++++- apps/server/src/kin/people/leaver.test.ts | 115 +++++++++++++ apps/server/src/kin/team/KinTeam.ts | 25 +-- .../components/usage/UsageKinCacheLine.tsx | 7 +- .../src/kin/kinCacheDaily.test.ts | 8 +- .../client-runtime/src/kin/kinCacheDaily.ts | 27 +-- verification/kin/reply/README.md | 4 +- verification/kin/reply/Reply.tla | 21 ++- verification/kin/reply/view.ts | 7 + 19 files changed, 634 insertions(+), 102 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageKinCacheLine.tsx b/apps/mobile/src/features/usage/UsageKinCacheLine.tsx index 07ebea23a331..2a30d4cede36 100644 --- a/apps/mobile/src/features/usage/UsageKinCacheLine.tsx +++ b/apps/mobile/src/features/usage/UsageKinCacheLine.tsx @@ -4,6 +4,7 @@ import { kinCacheDayLine, kinCacheLabel, } from "@t3tools/client-runtime/kin/kinCacheDaily"; +import { useMessages } from "gt-react-native"; import type { EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; @@ -51,6 +52,7 @@ function KinCacheLines(props: { readonly environmentId: EnvironmentId; readonly label: string | null; }) { + const messages = useMessages(); const result = useAtomValue( kinClient.cacheDays({ environmentId: props.environmentId, input: {} }), ); @@ -62,9 +64,10 @@ function KinCacheLines(props: { {props.label} )} {days !== null ? ( - [kinCacheDayLine("today", days.day), kinCacheDayLine("yesterday", days.before)].map( - (line) => , - ) + [ + kinCacheDayLine("today", days.day, messages), + kinCacheDayLine("yesterday", days.before, messages), + ].map((line) => ) ) : failed ? ( {KIN_CACHE_DAILY_COPY.failed} diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts index 74aef482cb3a..f02cd5722afd 100644 --- a/apps/server/src/kin/chat/KinChatService.test.ts +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -32,6 +32,7 @@ import { EnvironmentId, KinAgentId, KinChatId, + KinPendingAction, KinKeyThumbprint, KinMemberId, type KinChatListEvent, @@ -75,7 +76,12 @@ import { ServerSettingsService } from "../../serverSettings.ts"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import type { McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; import { KinKeyNotices } from "../approvals/ExecutionNotices.ts"; -import { keyNoticeBody, keyNoticesLayer } from "./executionNotices.ts"; +import { + keyNoticeBody, + keyNoticesLayer, + layer as executionNoticesLayer, +} from "./executionNotices.ts"; +import { KinExecutionNotices } from "../approvals/ExecutionNotices.ts"; import * as Hub from "./KinChatHub.ts"; import * as RefreshHub from "./KinRefreshHub.ts"; import * as Repository from "./KinChatRepository.ts"; @@ -321,6 +327,124 @@ const seed = Effect.fn("test.seed")(function* ( return { repo, service, identity, person, agent, chat }; }); +it.effect( + "execution notices keep the owner's result direct and copy only a co-owner chat's own result", + () => + Effect.gen(function* () { + const { repo, service, identity, person, chat } = yield* seed(); + const sql = yield* SqlClient.SqlClient; + const notices = yield* KinExecutionNotices; + const { orgId } = person; + const meera = KinPersonId.make("meera"); + yield* sql`INSERT INTO kin_people (org_id, person_id, handle, display_name, created_at, access) + VALUES (${orgId}, ${meera}, 'meera', 'Meera', ${timestamp}, 'co_owner')`; + const other = yield* service.createDirect({ ...person, personId: meera }, { orgId, agentId }); + const group = yield* repo.createChat({ + orgId, + chatId: KinChatId.make("dispatch"), + kind: "team_group", + title: "Dispatch", + teamId: null, + directKey: null, + lastMessageAt: null, + createdAt: timestamp, + archivedAt: null, + }); + yield* repo.addMember({ + orgId, + chatId: group.chatId, + memberId: KinMemberId.make("dispatch-rhea"), + principal: { _tag: "person", personId: person.personId }, + role: "owner", + joinedAt: timestamp, + leftAt: null, + mutedUntil: null, + }); + for (const [name, source, to, expected] of [ + ["legacy", threadId, undefined, [chat.chatId]], + ["owner", ThreadId.make("kin:owner-chat:dispatch"), group.chatId, [chat.chatId]], + ["mixed", ThreadId.make("kin:mixed-wake:dispatch"), group.chatId, [chat.chatId]], + ["co-owner", ThreadId.make("kin:meera"), other.chatId, [chat.chatId, other.chatId]], + ] as const) { + if (to !== undefined) + yield* identity.registerAgentThread({ orgId, agentId, threadId: source, chatId: to }); + const action = Schema.decodeSync(KinPendingAction)({ + id: `delete-${name}`, + orgId, + idempotencyKey: "a".repeat(64), + kind: "delete_branch", + target: { + _tag: "branch", + host: "github.com", + repo: "invented/dispatch", + ref: "finished", + }, + resolved: { _tag: "branch", headSha: "a".repeat(40) }, + targetDigest: "b".repeat(64), + nonce: "invented", + revision: 1, + reason: "Merged", + requestedBy: { agentId, threadId: source }, + provenance: { + startedBy: { humanId: name === "co-owner" ? meera : person.personId }, + startedByRole: "owner", + chain: [], + ceilingBelowOwner: false, + }, + requiredApprovers: [{ role: "owner" }], + state: "succeeded", + createdAt: timestamp, + updatedAt: timestamp, + expiresAt: timestamp, + }); + yield* sql`INSERT INTO kin_pending_actions (action_id, org_id, idempotency_key, + kind, target_json, resolved_json, target_digest, nonce, revision, reason, + requested_by_agent_id, requested_by_thread_id, provenance_json, required_approvers_json, + state, created_at, updated_at, expires_at) + VALUES (${action.id}, ${orgId}, ${name}, ${action.kind}, '{}', '{}', 'fixture', 'nonce', 1, + 'Merged', ${agentId}, ${source}, '{}', '[]', 'succeeded', 0, 0, 0)`; + yield* sql`INSERT INTO kin_grants (grant_id, org_id, action_id, revision, jti, + approver_human_id, key_thumbprint, compact, iat_s, exp_s, accepted_at) + VALUES (${name}, ${orgId}, ${action.id}, 1, ${name}, ${meera}, 'key', 'fixture', 0, 1, 0)`; + const finished = notices.finished({ action, outcome: "succeeded" }); + yield* finished; + yield* finished; + const destinations = yield* sql<{ chat_id: KinChatId }>`SELECT chat_id FROM kin_messages + WHERE org_id = ${orgId} AND message_id IN (${`kin-exec:${action.id}`}, ${`kin-exec-asked:${action.id}`}) + ORDER BY message_id DESC`; + assert.sameMembers( + destinations.map(({ chat_id }) => chat_id), + [...expected], + name, + ); + } + }).pipe(Effect.provide(Layer.provideMerge(executionNoticesLayer, layer))), +); + +it.effect("reopening a former reader's direct chat ends its old thread", () => + Effect.gen(function* () { + const { repo, service, identity, person } = yield* seed(); + const sql = yield* SqlClient.SqlClient; + const { orgId } = person; + const meera = KinPersonId.make("meera"); + const viewer = { ...person, personId: meera }; + yield* sql`INSERT INTO kin_people (org_id, person_id, handle, display_name, created_at, access) + VALUES (${orgId}, ${meera}, 'meera', 'Meera', ${timestamp}, 'co_owner')`; + const chat = yield* service.createDirect(viewer, { orgId, agentId }); + const member = (yield* repo.listMembers(chat)).find((row) => row.principal._tag === "person")!; + yield* repo.leaveChat({ ...member, leftAt: timestamp }); + const former = ThreadId.make("kin:meera-former"); + yield* identity.registerAgentThread({ orgId, agentId, threadId: former, chatId: chat.chatId }); + assert.strictEqual( + (yield* service.createDirect(viewer, { orgId, agentId })).chatId, + chat.chatId, + ); + const [thread] = yield* sql<{ ended_at: string | null }>`SELECT ended_at FROM kin_agent_threads + WHERE org_id = ${orgId} AND thread_id = ${former}`; + assert.isString(thread?.ended_at); + }).pipe(Effect.provide(layer)), +); + const progressSettings = Effect.fnUntraced(function* (flipOnRead = false) { const settings = yield* Ref.make({ ...DEFAULT_SERVER_SETTINGS, diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index 31fb0ec20af0..96f3d08d2b40 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -156,7 +156,8 @@ import { hasTurnChanges } from "../lead/turnChanges.ts"; import * as Repository from "./KinChatRepository.ts"; import type { WriteAudience } from "./KinChatRepository.ts"; import { KinAttachmentStore } from "./KinAttachmentStore.ts"; -import type { AgentIdentity, PersonIdentity } from "./KinIdentity.ts"; +import { KinIdentity, type AgentIdentity, type PersonIdentity } from "./KinIdentity.ts"; +import { finishPersonJoin, onPersonJoined } from "../lead/ChatSharing.ts"; import { roomReadable } from "./memberAccess.ts"; import * as Reactions from "./reactions.ts"; import * as LeadAccess from "../lead/LeadAccess.ts"; @@ -837,6 +838,7 @@ const make = Effect.gen(function* () { // Absent where no attachments directory exists; a send with files is then refused. const attachmentStore = yield* Effect.serviceOption(KinAttachmentStore); const stop = yield* Effect.serviceOption(KinStop); + const identities = yield* Effect.serviceOption(KinIdentity); // A deferral card's [Start now] hands its work to the lead's queue in the tap's transaction. const queue = yield* Effect.serviceOption(KinEventQueue); /** For a stream event; left out of a chat that was never cleared. */ @@ -3907,6 +3909,23 @@ const make = Effect.gen(function* () { leftAt: null, mutedUntil: null, }); + if (mine.leftAt !== null) { + const join = yield* onPersonJoined({ + orgId: chat.orgId, + chatId: chat.chatId, + personId: person.personId, + }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.mapError(toPersistenceSqlError("KinChatService.directRejoin")), + ); + yield* finishPersonJoin(chat, join, { + repo, + hub, + ...(Option.isSome(identities) ? { identity: identities.value } : {}), + ...(Option.isSome(stop) ? { stop: stop.value } : {}), + ...(Option.isSome(presence) ? { presence: presence.value } : {}), + }).pipe(Effect.provideService(SqlClient.SqlClient, sql)); + } yield* hub.publish({ type: "member.updated", orgId: chat.orgId, diff --git a/apps/server/src/kin/chat/KinGroups.ts b/apps/server/src/kin/chat/KinGroups.ts index f116af2ae698..44f37d239bfb 100644 --- a/apps/server/src/kin/chat/KinGroups.ts +++ b/apps/server/src/kin/chat/KinGroups.ts @@ -38,7 +38,12 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as SqlError from "effect/sql/SqlError"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; -import { freezeMovedCard, onPersonJoined, settleCards, tellStopped } from "../lead/ChatSharing.ts"; +import { + finishPersonJoin, + freezeMovedCard, + onPersonJoined, + settleCards, +} from "../lead/ChatSharing.ts"; import { KinStop } from "../lead/KinStop.ts"; import * as Reach from "../lead/Reach.ts"; import { ownerLevel } from "../people/KinAccess.ts"; @@ -313,41 +318,13 @@ const make = Effect.gen(function* () { SqlError: (cause) => Effect.fail(toPersistenceSqlError("KinGroups.freezeCard")(cause)), }), ); - if (shared.expired.length > 0 && Option.isSome(presence)) { - const line = presence.value; - yield* sql.afterCommit( - Effect.forEach( - new Set(shared.expired.map((row) => row.agentId)), - (id) => - syncQueued(line, chat.orgId, KinAgentId.make(id)).pipe( - Effect.provideService(SqlClient.SqlClient, sql), - ), - { discard: true }, - ), - ); - } - if (shared.stopped.length > 0) - yield* sql.afterCommit( - withChat(tellStopped({ ...chat, lines: shared.stopped })).pipe( - Effect.ignore({ log: "Warn", message: "KinGroups.tellStopped" }), - ), - ); - if (shared.threads.length > 0) - yield* sql.afterCommit( - Effect.forEach( - shared.threads, - (threadId) => - identity.endAgentThread({ orgId: chat.orgId, threadId }).pipe(Effect.ignore), - { discard: true }, - ), - ); - if (shared.turns.length === 0 || Option.isNone(stop)) return; - yield* sql.afterCommit( - stop.value.abortTurns( - chat.orgId, - shared.turns.map((turn) => KinWakeupId.make(turn.wakeupId)), - ), - ); + yield* finishPersonJoin(chat, shared, { + identity, + repo, + hub, + ...(Option.isSome(stop) ? { stop: stop.value } : {}), + ...(Option.isSome(presence) ? { presence: presence.value } : {}), + }).pipe(Effect.provideService(SqlClient.SqlClient, sql)); }); /** Tells everyone still in the chat that who is in it, its name or its lead changed. */ diff --git a/apps/server/src/kin/chat/executionNotices.ts b/apps/server/src/kin/chat/executionNotices.ts index 9d84b4eeff19..20edaba197d9 100644 --- a/apps/server/src/kin/chat/executionNotices.ts +++ b/apps/server/src/kin/chat/executionNotices.ts @@ -17,6 +17,7 @@ import { type KinExecutionOutcome, type KinKeyChange, } from "../approvals/ExecutionNotices.ts"; +import { MIXED_WAKE_THREAD_PREFIX, OWNER_CHAT_THREAD_PREFIX } from "../lead/sessionAudience.ts"; import { CHIEF_OF_STAFF_DOMAIN } from "../lead/orgLeads.ts"; import { textLocale, type TextClock } from "../work/companyProfile.ts"; import { ownerZone } from "../work/recordRows.ts"; @@ -85,6 +86,9 @@ export const layer = Layer.effect( * the request came from when that is a co-owner's own, so whoever asked hears the result. */ const post = Effect.fnUntraced(function* (action: KinPendingAction, body: string) { + const source = action.requestedBy.threadId; + const ownerSource = + source.startsWith(OWNER_CHAT_THREAD_PREFIX) || source.startsWith(MIXED_WAKE_THREAD_PREFIX); const [lead] = yield* sql<{ readonly chatId: string; readonly askedIn: string | null; @@ -92,7 +96,7 @@ export const layer = Layer.effect( }>` SELECT l.owner_chat_id AS "chatId", (SELECT t.chat_id FROM kin_agent_threads t WHERE t.org_id = l.org_id - AND t.thread_id = ${action.requestedBy.threadId}) AS "askedIn", + AND t.agent_id = l.agent_id AND t.thread_id = ${source} AND NOT ${ownerSource}) AS "askedIn", (SELECT p.display_name FROM kin_grants g JOIN kin_people p ON p.org_id = g.org_id AND p.person_id = g.approver_human_id JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id diff --git a/apps/server/src/kin/chat/layer.ts b/apps/server/src/kin/chat/layer.ts index 310e55ba2860..9b8c8ab63461 100644 --- a/apps/server/src/kin/chat/layer.ts +++ b/apps/server/src/kin/chat/layer.ts @@ -17,6 +17,7 @@ import * as VisualHosts from "./KinVisualHosts.ts"; import * as Records from "../work/KinRecords.ts"; import { KinIdentity, KinIdentityConfig } from "./KinIdentity.ts"; +const identities = KinIdentity.layer.pipe(Layer.provide(KinIdentityConfig.layer)); const stop = Stop.layer.pipe(Layer.provide(Presence.layer), Layer.provideMerge(Queue.layer)); const service = Layer.mergeAll( @@ -33,12 +34,8 @@ const service = Layer.mergeAll( VisualHosts.layer, ).pipe(Layer.provideMerge(stop)), // A join stops the turns it aborts (`KinGroups.shareWith`) through the stop switch's fan-out. - Groups.layer.pipe( - Layer.provide(Presence.layer), - Layer.provide(stop), - Layer.provideMerge(KinIdentity.layer.pipe(Layer.provide(KinIdentityConfig.layer))), - ), -); + Groups.layer.pipe(Layer.provide(Presence.layer), Layer.provide(stop)), +).pipe(Layer.provideMerge(identities)); const storage = Layer.merge(Hub.layer, RefreshHub.layer).pipe( Layer.provideMerge(Repository.layer), diff --git a/apps/server/src/kin/chat/sharing.ts b/apps/server/src/kin/chat/sharing.ts index 2c03cc4986fd..8ffe227db388 100644 --- a/apps/server/src/kin/chat/sharing.ts +++ b/apps/server/src/kin/chat/sharing.ts @@ -16,15 +16,22 @@ const notOwnerSql = (org: string, chat: string, person: string) => /** * In the transaction that makes a member active: a person besides the owner reads from the next - * seq on, and their chat is shared from then, once and for good (`shared_at`). Everything before + * seq on (unless restoring the same reader's history), and the chat is shared once and for good. + * Everything before * `shared_from_seq` was written for the owner alone. Returns whether this join shared the chat. */ export const recordJoin = Effect.fn("KinChatSharing.recordJoin")(function* ( sql: SqlClient.SqlClient, - input: { readonly orgId: string; readonly chatId: string; readonly memberId: string }, + input: { + readonly orgId: string; + readonly chatId: string; + readonly memberId: string; + readonly preserveHistory?: true; + }, ) { const now = yield* Clock.currentTimeMillis; - yield* sql`UPDATE kin_chat_members AS m SET joined_seq = CASE + if (input.preserveHistory !== true) + yield* sql`UPDATE kin_chat_members AS m SET joined_seq = CASE WHEN m.principal_kind = 'person' AND ${sql.literal(notOwnerSql("m.org_id", "m.chat_id", "m.person_id"))} THEN (SELECT c.last_seq + 1 FROM kin_chats c WHERE c.org_id = m.org_id AND c.chat_id = m.chat_id) ELSE 0 END diff --git a/apps/server/src/kin/lead/ChatSharing.ts b/apps/server/src/kin/lead/ChatSharing.ts index c870fb7cca13..c7e350793824 100644 --- a/apps/server/src/kin/lead/ChatSharing.ts +++ b/apps/server/src/kin/lead/ChatSharing.ts @@ -16,6 +16,9 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; +import type { KinIdentity } from "../chat/KinIdentity.ts"; +import type { KinStop } from "./KinStop.ts"; +import { KinPresence, syncQueued } from "../reply/KinPresence.ts"; import { KinChatHub } from "../chat/KinChatHub.ts"; import { KinChatRepository } from "../chat/KinChatRepository.ts"; import { historyFloor } from "../chat/sharing.ts"; @@ -102,6 +105,45 @@ export const onPersonJoined = Effect.fn("KinChatSharing.onPersonJoined")(functio return { turns, threads, expired, moved, stopped: yield* stoppedLines(sql, input, expired) }; }); +/** Commit the live effects only after the reader and the transcript fence have committed. */ +export const finishPersonJoin = Effect.fn("KinChatSharing.finishPersonJoin")(function* ( + chat: { readonly orgId: KinOrgId; readonly chatId: string }, + join: Effect.Success>, + services: { + readonly identity?: KinIdentity["Service"]; + readonly stop?: KinStop["Service"]; + readonly presence?: KinPresence["Service"]; + readonly repo: KinChatRepository["Service"]; + readonly hub: KinChatHub["Service"]; + }, +) { + const sql = yield* SqlClient.SqlClient; + const { identity, stop, presence, repo, hub } = services; + yield* sql.afterCommit( + Effect.gen(function* () { + if (identity !== undefined) + for (const threadId of join.threads) + yield* identity.endAgentThread({ orgId: chat.orgId, threadId }).pipe(Effect.ignore); + if (stop !== undefined && join.turns.length > 0) + yield* stop.abortTurns( + chat.orgId, + join.turns.map((turn) => KinWakeupId.make(turn.wakeupId)), + ); + if (presence !== undefined) + for (const agentId of new Set(join.expired.map((row) => row.agentId))) + 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. diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 7194389ced2a..ce43283ecd0a 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -85,6 +85,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 { recordJoin } from "../chat/sharing.ts"; import { socialSeatThread } from "../social/seat.ts"; import * as TaskWake from "./TaskWake.ts"; import { sensitiveShown, turnSensitive } from "../work/sensitiveReads.ts"; @@ -119,6 +120,7 @@ import { import * as HostBackup from "../hostBackup.ts"; import * as PlatformError from "effect/PlatformError"; import { + CARRIED_TURN_NOTE, KinLeadPrompt, KinLeadPromptError, SESSION_CHANGES_CAP, @@ -2577,9 +2579,15 @@ describe("WakeupRunner", () => { "", "No standing rule applies now, including those you read earlier in this session.", ], + [ + "Use the ISO currency code.", + "Write currency codes first.", + 'They are now, in full: "Write currency codes first." This replaces every standing rule you read earlier in this session.', + "private", + ], ] as const)( "a standing change carries the whole new document, with no old wording or actor", - ([before, after, note]) => { + ([before, after, note, chat]) => { let rules: string = before; const reads: string[] = []; const beforeTurn = ({ threadId, runOrdinal }: ProviderAdapterV2TurnInput) => @@ -2587,10 +2595,13 @@ describe("WakeupRunner", () => { ? readCarryHook(threadId).pipe(Effect.tap((text) => Effect.sync(() => reads.push(text)))) : Effect.void; return Effect.gen(function* () { - yield* seedCarry; - yield* wake("tidewater-first"); + const sql = yield* seedCarry; + if (chat !== undefined) + 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* wake("tidewater-first", chat); rules = after; - yield* wake("tidewater-second"); + yield* wake("tidewater-second", chat); assert.include((yield* carryRows).at(-1), { sent: "carried", reason: null }); assert.deepStrictEqual(yield* sessions(), [1, 1]); // The stamp's name is a git author string the pusher chose, so the line names no one. @@ -3397,6 +3408,7 @@ describe("WakeupRunner", () => { it.effect.each([ "worked", "owner group", + "owner group digest changed", "other chat", "failed", "chat only", @@ -3416,7 +3428,7 @@ describe("WakeupRunner", () => { let standingPart = "Owner permission is active."; return Effect.gen(function* () { const room = scenario === "confined room"; - const group = scenario === "owner group"; + const group = scenario === "owner group" || scenario === "owner group digest changed"; const sql = room ? yield* seedCarryRoom : yield* seedCarry; if (group) yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at) @@ -3469,11 +3481,21 @@ describe("WakeupRunner", () => { }; }), }); + if (scenario === "owner group digest changed") { + // Adding an agent changes the digest without widening the human audience or ending the thread. + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) + VALUES ('room-lead', ${orgId}, 'room', 'agent', ${agentId}, 'member', '2026-11-26')`; + } yield* runCompaction; yield* runCompaction; const ledger = yield* sql`SELECT kind, thread_id, run_id, event_ids FROM kin_wakeups WHERE json_extract(carry_json, '$.action') = 'compaction'`; - if (scenario !== "worked" && scenario !== "other chat" && scenario !== "failed" && !group) { + if ( + scenario !== "worked" && + scenario !== "other chat" && + scenario !== "failed" && + scenario !== "owner group" + ) { assert.strictEqual(requests, 0); assert.deepStrictEqual(ledger, []); return; @@ -3707,6 +3729,7 @@ describe("WakeupRunner", () => { it.effect.each([ "interleave", "join", + "member join", "outside", "mixed", "steer", @@ -3747,6 +3770,8 @@ describe("WakeupRunner", () => { const direct = yield* latest; yield* wake("dispatch-2", "private"); const group = yield* latest; + const groupRequest = + scenario === "member join" ? carriedSend(yield* carryProjection) : undefined; if (scenario === "legacy") { assert.notEqual(direct.threadId, "kin:legacy"); assert.notEqual(group.threadId, "kin:legacy"); @@ -3819,9 +3844,9 @@ describe("WakeupRunner", () => { assert.include(yield* latest, { reason: "other_chat", sent: "fresh" }); } if (scenario === "restart") yield* wake("dispatch-team-before-restart", "team"); - if (scenario === "join") { + if (scenario === "join" || scenario === "member join") { const chatId = KinChatId.make("private"); - const personId = KinPersonId.make("meera"); + const personId = KinPersonId.make(scenario === "join" ? "meera" : "zoya"); yield* sql.withTransaction( Effect.gen(function* () { yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) @@ -3842,10 +3867,25 @@ describe("WakeupRunner", () => { } yield* wake("dispatch-4", "private"); const next = yield* latest; - if (scenario === "join") { + if (scenario === "join" || scenario === "member join") { assert.include(next, { sent: "fresh", reason: "members" }); assert.notEqual(next.threadId, group.threadId); - yield* sql`UPDATE kin_chat_members SET left_at = '2026-11-29' WHERE member_id = 'private-meera'`; + if (scenario === "member join") { + const [audience] = + yield* sql`SELECT audience FROM kin_wakeups WHERE wakeup_id = ${next.wakeupId}`; + assert.deepStrictEqual(audience, { audience: "shared" }); + const [old] = yield* sql<{ + ended_at: string | null; + }>`SELECT ended_at FROM kin_agent_threads WHERE thread_id = ${group.threadId}`; + assert.isString(old?.ended_at); + const request = carriedSend(yield* carryProjection); + assert.include(groupRequest!.text, "Invented owner-only dispatch rule."); + assert.notInclude(request.text, "Invented owner-only dispatch rule."); + assert.notInclude(request.text, CARRIED_TURN_NOTE); + assert.notEqual(request.run.providerThreadId, groupRequest!.run.providerThreadId); + return; + } + yield* sql`UPDATE kin_chat_members SET left_at = '2026-11-29' WHERE member_id = 'private-new-reader'`; yield* wake("dispatch-after-leave", "private"); assert.notEqual((yield* latest).threadId, group.threadId); return; @@ -3891,6 +3931,9 @@ describe("WakeupRunner", () => { }).pipe( Effect.provide( carryHarness({ + ...(scenario === "member join" + ? { includeRulebook: true, standingRules: () => "Invented owner-only dispatch rule." } + : {}), beforeTurn: ({ threadId }) => readCarryHook(threadId, current).pipe(Effect.asVoid), providerSteers: steers, holdRunning: () => (block ? hold : undefined), @@ -3900,6 +3943,103 @@ describe("WakeupRunner", () => { }).pipe(provideDeterministicTestRuntime), ); + it.effect("a task from an ended owner group reports direct without adopting the old run", () => + Effect.gen(function* () { + const held = yield* Deferred.make(); + yield* Effect.gen(function* () { + const sql = yield* seedCarry; + yield* wake("dispatch-direct"); + const direct = (yield* carryRows).at(-1)!; + 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* wake("dispatch-group", "private"); + const asked = yield* carryProjection; + const task = yield* taskNotice(asked.thread.id, asked.runs[0]!, "dispatch"); + yield* sql`UPDATE kin_agent_threads SET ended_at = '2026-11-29' WHERE thread_id = ${asked.thread.id}`; + const lane = yield* TaskWake.taskChat(asked.thread.id); + assert.strictEqual(lane?.chatId, "direct"); + const { run: notice, message } = yield* task.dispatch; + yield* (yield* TaskWake.make).enqueue(message); + yield* Fiber.join(yield* run()); + yield* Deferred.succeed(held, undefined); + const last = (yield* carryRows).at(-1)!; + assert.include(last, { sent: "fresh", reason: "other_chat" }); + assert.notEqual(last.threadId, asked.thread.id); + assert.notEqual(last.threadId, direct.threadId); + const [answer] = yield* sql`SELECT w.run_id, json_extract(e.json, '$.chatId') AS chat + FROM kin_wakeups w JOIN kin_events e USING (org_id, wakeup_id) + WHERE w.wakeup_id = ${last.wakeupId}`; + assert.strictEqual(answer?.["chat"], "direct"); + assert.isString(answer?.["run_id"]); + assert.notEqual(answer?.["run_id"], notice.id); + }).pipe( + Effect.provide( + carryHarness({ + holdRunning: (ordinal) => (ordinal === 2 ? held : undefined), + }), + ), + ); + }).pipe(provideDeterministicTestRuntime), + ); + + it.effect("an outside GitHub wake defaults to direct and marks only that session", () => { + let database: SqlClient.SqlClient | undefined; + const prepare: Memory.Memory["Service"]["prepareWakeup"] = (org, wakeupId) => + Effect.gen(function* () { + if (database !== undefined && wakeupId !== undefined) { + const [github] = yield* database`SELECT 1 FROM kin_events + WHERE org_id = ${org} AND wakeup_id = ${wakeupId} AND tag = 'github'`; + // The real prompt marks a GitHub wake without a trusted trigger. + if (github !== undefined) + yield* inheritOutside({ + orgId: org, + wakeupId, + eventIds: [], + shows: "github", + }).pipe(Effect.provideService(SqlClient.SqlClient, database)); + } + return { head: "abc", indexAsOf: DateTime.makeUnsafe(0), read: "/private/tmp" }; + }).pipe(Effect.orDie); + return Effect.gen(function* () { + const sql = yield* seedCarry; + database = sql; + 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* wake("dispatch-direct"); + yield* wake("dispatch-group", "private"); + const [direct, group] = yield* carryRows; + yield* (yield* KinEventQueue.KinEventQueue).enqueue({ + ...event("dispatch-github"), + _tag: "github", + deliveryId: "dispatch-delivery", + dedupeKey: "dispatch-delivery", + eventName: "push", + repo: "invented/dispatch", + summary: "Invented external change", + }); + yield* Fiber.join(yield* run()); + const github = (yield* carryRows).at(-1)!; + assert.include(github, { sent: "carried", threadId: direct!.threadId }); + assert.isTrue(yield* outsideRead({ orgId, wakeupId: github.wakeupId })); + yield* wake("dispatch-group-next", "private"); + assert.include((yield* carryRows).at(-1), { sent: "carried", threadId: group!.threadId }); + yield* wake("dispatch-direct-next"); + assert.include((yield* carryRows).at(-1), { + sent: "fresh", + reason: "marked", + threadId: direct!.threadId, + }); + }).pipe( + Effect.provide( + carryHarness({ + prepare, + beforeTurn: ({ threadId }) => readCarryHook(threadId).pipe(Effect.asVoid), + }), + ), + provideDeterministicTestRuntime, + ); + }); + it.effect("a task an owner's mixed wake delegated is answered in the run T3 started", () => Effect.gen(function* () { const held = yield* Deferred.make(); diff --git a/apps/server/src/kin/lead/WakeupRunner.testkit.ts b/apps/server/src/kin/lead/WakeupRunner.testkit.ts index 37ad2976d9e8..149d2a9578c5 100644 --- a/apps/server/src/kin/lead/WakeupRunner.testkit.ts +++ b/apps/server/src/kin/lead/WakeupRunner.testkit.ts @@ -913,9 +913,14 @@ function parts(options: HarnessOptions) { ); const sections = { header: "Tidewater Freight" }; return { - full: options.includeRulebook - ? `# Standing rules\n\n${options.standingRules?.() ?? "invented standing"}\n\n${full}` - : full, + full: + options.includeRulebook && + (yield* turnAudience(input).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.orDie, + )) === "owner_only" + ? `# Standing rules\n\n${options.standingRules?.() ?? "invented standing"}\n\n${full}` + : full, message: "Tidewater message", confinedDelta: () => sections.header, standing: "Tidewater standing", diff --git a/apps/server/src/kin/people/KinPeople.ts b/apps/server/src/kin/people/KinPeople.ts index 5f9d7ba6106b..b2aaf6da8fea 100644 --- a/apps/server/src/kin/people/KinPeople.ts +++ b/apps/server/src/kin/people/KinPeople.ts @@ -11,6 +11,7 @@ import { KinInviteId, KinMessageId, KIN_TEXT_LOCALE, + KIN_TEAM_ROOM_TEAM_ID, formatKinWhen, KinPerson, KinPersonId, @@ -72,7 +73,14 @@ import { abortChatTurns } from "../lead/Audience.ts"; import { closeUngranted } from "../lead/directClose.ts"; import { signedInPeople } from "./signedIn.ts"; import { KinHostCare } from "../host/KinHostCare.ts"; -import { onPersonRemoved } from "../lead/ChatSharing.ts"; +import { + finishPersonJoin, + freezeMovedCard, + onPersonJoined, + onPersonRemoved, + settleCards, +} from "../lead/ChatSharing.ts"; +import { recordJoin } from "../chat/sharing.ts"; import { KinStop } from "../lead/KinStop.ts"; import { KinPresence, syncQueued } from "../reply/KinPresence.ts"; import { KinPushSender } from "../push/KinPushSender.ts"; @@ -467,6 +475,52 @@ export const make = Effect.gen(function* () { expiresAt: DateTime.formatIso(DateTime.makeUnsafe(expiresAt)), }; }); + const gainedChat = Effect.fn("KinPeople.gainedChat")(function* ( + input: { + readonly orgId: KinOrgId; + readonly chatId: string; + readonly memberId: string; + readonly personId: KinPersonId; + }, + preserveHistory: boolean, + ) { + const provideSql = Effect.provideService(SqlClient.SqlClient, sql); + const withChat = ( + effect: Effect.Effect, + ) => + effect.pipe( + provideSql, + Effect.provideService(KinChatRepository, repo), + Effect.provideService(KinChatHub, hub), + ); + yield* recordJoin(sql, { + ...input, + ...(preserveHistory ? { preserveHistory: true as const } : {}), + }).pipe(Effect.mapError(toPersistenceSqlError("KinPeople.gainedChat"))); + const joined = yield* onPersonJoined(input).pipe( + provideSql, + Effect.mapError(toPersistenceSqlError("KinPeople.gainedChat")), + ); + yield* withChat(settleCards(input)).pipe( + Effect.catchTags({ + SqlError: (cause) => Effect.fail(toPersistenceSqlError("KinPeople.gainedChatCards")(cause)), + }), + ); + for (const task of joined.moved) + yield* withChat(freezeMovedCard({ ...input, ...task })).pipe( + Effect.catchTags({ + SqlError: (cause) => + Effect.fail(toPersistenceSqlError("KinPeople.gainedChatTask")(cause)), + }), + ); + yield* finishPersonJoin(input, joined, { + identity, + repo, + hub, + ...(Option.isSome(stop) ? { stop: stop.value } : {}), + ...(Option.isSome(presence) ? { presence: presence.value } : {}), + }).pipe(provideSql); + }); /** * The same person let back in: the level, places, leads and chats their access was removed * from come back as they were, history included, and their tasks note who let them back. @@ -498,11 +552,15 @@ export const make = Effect.gen(function* () { const removedAt = gone?.removedAt ?? null; if (removedAt === null) return; // Removal stamps each with the same instant, so this undoes that removal and nothing older. - yield* sql`UPDATE kin_chat_members SET left_at = NULL + const restored = yield* sql<{ chatId: string; memberId: string }>` + UPDATE kin_chat_members SET left_at = NULL WHERE org_id = ${orgId} AND principal_kind = 'person' AND person_id = ${personId} - AND left_at = ${DateTime.formatIso(DateTime.makeUnsafe(removedAt))}`.pipe( + AND left_at = ${DateTime.formatIso(DateTime.makeUnsafe(removedAt))} + RETURNING chat_id AS "chatId", member_id AS "memberId"`.pipe( Effect.mapError(toPersistenceSqlError("KinPeople.backChats")), ); + for (const membership of restored.toSorted((a, b) => a.chatId.localeCompare(b.chatId))) + yield* gainedChat({ orgId, personId, ...membership }, true); // Made a member while removed: back as one, exactly as `setAccess` would have made them. if (gone?.was === "co_owner" && gone.kept === "member") yield* closeUngranted({ repo, hub, presence }, orgId, personId).pipe( @@ -1382,6 +1440,18 @@ export const make = Effect.gen(function* () { yield* viewMoved(input.orgId, input.personId); if (before === "co_owner" && input.access === "member") yield* closeStranded(input.orgId, was); + if (input.access === "co_owner") { + // A demoted member can retain their Team row, but could not read the room at that level. + const rooms = yield* sql<{ chatId: string; memberId: string }>` + SELECT c.chat_id AS "chatId", m.member_id AS "memberId" + FROM kin_chats c JOIN kin_chat_members m USING (org_id, chat_id) + WHERE c.org_id = ${input.orgId} AND c.team_id = ${KIN_TEAM_ROOM_TEAM_ID} + AND c.archived_at IS NULL AND m.person_id = ${input.personId} + AND m.principal_kind = 'person' AND m.left_at IS NULL ORDER BY c.chat_id`.pipe( + Effect.mapError(toPersistenceSqlError("KinPeople.teamAccess")), + ); + for (const room of rooms) yield* gainedChat({ ...input, ...room }, false); + } // A co-owner talks to every agent in their own chat with it, never in the owner's. if (input.access === "co_owner" && Option.isSome(chats)) { const leads = yield* sql<{ agentId: KinAgentId }>`SELECT l.agent_id AS "agentId" diff --git a/apps/server/src/kin/people/leaver.test.ts b/apps/server/src/kin/people/leaver.test.ts index d438f6eb43cf..ffcdca752c13 100644 --- a/apps/server/src/kin/people/leaver.test.ts +++ b/apps/server/src/kin/people/leaver.test.ts @@ -9,6 +9,8 @@ import { KinChatId, KinEventId, KinMessageId, + KinMemberId, + KIN_TEAM_ROOM_TEAM_ID, KinPersonId, KinWidgetId, KIN_LEFT_FIELD, @@ -31,6 +33,10 @@ import * as TestClock from "effect/testing/TestClock"; import { SessionStore } from "../../auth/SessionStore.ts"; import { KinChatRepository } from "../chat/KinChatRepository.ts"; import { KinChatService } from "../chat/KinChatService.ts"; +import { KinGroups } from "../chat/KinGroups.ts"; +import { ownerSessionAudience } from "../lead/sessionAudience.ts"; +import { KinEventQueue } from "../lead/KinEventQueue.ts"; +import { KinWakeupId } from "@t3tools/contracts"; import { KinIdentity, type PersonIdentity } from "../chat/KinIdentity.ts"; import { KinRefreshHub } from "../chat/KinRefreshHub.ts"; import { KinHostCare } from "../host/KinHostCare.ts"; @@ -288,6 +294,115 @@ const activity = (ctx: Ctx, key: string) => ), ); +it.effect( + "bringing a co-owner back aborts a running private-group turn and retires its session", + () => + run((ctx) => + Effect.gen(function* () { + const { orgId, owner, sql } = ctx; + const groups = yield* KinGroups; + const identity = yield* KinIdentity; + const { chatId } = yield* groups.create([owner], { + orgId, + title: "Ambermill dispatch", + agentIds: [chief], + personIds: [meeraId], + }); + yield* ctx.people.removeAccess(ownerSession, { orgId, personId: meeraId }); + const scope = { orgId, agentId: chief }; + assert.isString((yield* ownerSessionAudience(scope, chatId))?.audience); + const threadId = ThreadId.make("kin:owner-chat:ambermill"); + yield* identity.registerAgentThread({ ...scope, threadId, chatId }); + const message = yield* ctx.chats.send(owner, { + chatId, + body: "Invented private dispatch", + clientMessageId: "private-dispatch", + }); + const queue = yield* KinEventQueue; + if (message.author._tag !== "human") throw new Error("Expected an owner's message"); + yield* queue.enqueue({ + _tag: "chat.message", + orgId, + agentId: chief, + eventId: KinEventId.make("private-dispatch"), + receivedAt: yield* DateTime.now, + dedupeKey: null, + chatId, + messageId: message.messageId, + provenance: message.author, + }); + yield* TestClock.adjust("20 seconds"); + const wakeupId = KinWakeupId.make("ambermill-running"); + yield* Effect.scoped(queue.claim({ ...scope, wakeupId, model: "test" })); + yield* sql`UPDATE kin_wakeups SET thread_id = ${threadId}, audience = 'owner_only' + WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId}`; + const state = 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 = ${wakeupId}`; + assert.deepStrictEqual(yield* state, [{ ended_at: null, aborted_at: null }]); + yield* bringBack(ctx, "Meera", meeraId); + const [after] = yield* state; + assert.isString(after?.ended_at); + assert.isNumber(after?.aborted_at); + assert.isFalse(identity.isLeadThread(threadId)); + assert.isUndefined(yield* ownerSessionAudience(scope, chatId)); + }), + ), +); + +it.effect("promotion fences the Team room if the member's row never left", () => + run((ctx) => + Effect.gen(function* () { + const { orgId, sql } = ctx; + const repo = yield* KinChatRepository; + const identity = yield* KinIdentity; + const { chatId } = yield* repo.createChat({ + orgId, + chatId: KinChatId.make("ambermill-team"), + kind: "team_group", + title: "Team", + directKey: null, + teamId: KIN_TEAM_ROOM_TEAM_ID, + lastMessageAt: null, + createdAt: at, + archivedAt: null, + }); + for (const [personId, role] of [ + [ctx.owner.personId, "owner"], + [meeraId, "member"], + ] as const) + yield* repo.addMember({ + orgId, + chatId, + memberId: KinMemberId.make(`team-${personId}`), + principal: { _tag: "person", personId }, + role, + joinedAt: at, + leftAt: null, + mutedUntil: null, + }); + yield* ctx.people.setAccess(ownerSession, { orgId, personId: meeraId, access: "member" }); + const member = { orgId, personId: meeraId }; + const [row] = yield* sql`SELECT left_at FROM kin_chat_members WHERE org_id = ${orgId} + AND chat_id = ${chatId} AND person_id = ${meeraId}`; + assert.deepStrictEqual(row, { left_at: null }); + const page = { chatId, beforeSeq: 1_000, limit: 100 }; + assert.strictEqual( + (yield* ctx.chats.history(ctx.person(meeraId), page).pipe(Effect.result))._tag, + "Failure", + ); + const threadId = ThreadId.make("kin-shared:ambermill-team"); + yield* identity.registerAgentThread({ orgId, agentId: chief, threadId, chatId }); + yield* ctx.people.setAccess(ownerSession, { ...member, access: "co_owner" }); + assert.isFalse(identity.isLeadThread(threadId)); + assert.strictEqual( + (yield* ctx.chats.history(ctx.person(meeraId), page).pipe(Effect.result))._tag, + "Success", + ); + }), + ), +); + it.effect( "a leaver's card: once per removal for the owner and each co-owner, none for someone who held nothing; a co-owner gives it all and the owner's copy closes; the receiver is told once and keeps it when they come back", () => diff --git a/apps/server/src/kin/team/KinTeam.ts b/apps/server/src/kin/team/KinTeam.ts index af20deee066b..126bb1f78836 100644 --- a/apps/server/src/kin/team/KinTeam.ts +++ b/apps/server/src/kin/team/KinTeam.ts @@ -38,7 +38,7 @@ import { KinChatService } from "../chat/KinChatService.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { SHARED_REFUSAL, aborted } from "../lead/Audience.ts"; import { KinEventQueue } from "../lead/KinEventQueue.ts"; -import { onPersonJoined, tellStopped } from "../lead/ChatSharing.ts"; +import { finishPersonJoin, onPersonJoined } from "../lead/ChatSharing.ts"; import { KinStop } from "../lead/KinStop.ts"; import { outsideStamp, stampEvent } from "../lead/OutsideContent.ts"; import { teamAgent } from "../lead/LeadAccess.ts"; @@ -323,23 +323,12 @@ const make = Effect.gen(function* () { TEAM_ROOM_MUTED, ); const joined = yield* onPersonJoined({ orgId, chatId: room.chatId, personId }).pipe(access); - yield* sql.afterCommit( - Effect.gen(function* () { - for (const threadId of joined.threads) - yield* identity.endAgentThread({ orgId, threadId }).pipe(Effect.ignore); - if (Option.isSome(stop) && joined.turns.length > 0) - yield* stop.value.abortTurns( - orgId, - joined.turns.map((turn) => KinWakeupId.make(turn.wakeupId)), - ); - if (joined.stopped.length > 0) - yield* tellStopped({ orgId, chatId: room.chatId, lines: joined.stopped }).pipe( - Effect.provideService(KinChatRepository, repo), - Effect.provideService(KinChatHub, hub), - Effect.ignore({ log: "Warn", message: "KinTeam.tellStopped" }), - ); - }), - ); + yield* finishPersonJoin(room, joined, { + identity, + repo, + hub, + ...(Option.isSome(stop) ? { stop: stop.value } : {}), + }).pipe(access); } for (const agent of all) if ( diff --git a/apps/web/src/components/usage/UsageKinCacheLine.tsx b/apps/web/src/components/usage/UsageKinCacheLine.tsx index 0b2de6160a92..d5ec68564078 100644 --- a/apps/web/src/components/usage/UsageKinCacheLine.tsx +++ b/apps/web/src/components/usage/UsageKinCacheLine.tsx @@ -4,6 +4,7 @@ import { kinCacheDayLine, kinCacheLabel, } from "@t3tools/client-runtime/kin/kinCacheDaily"; +import { useMessages } from "gt-react"; import type { EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import * as AsyncResult from "effect/reactivity/AsyncResult"; @@ -41,6 +42,7 @@ function KinCacheLines(props: { readonly environmentId: EnvironmentId; readonly label: string | null; }) { + const messages = useMessages(); const result = useAtomValue( kinClient.cacheDays({ environmentId: props.environmentId, input: {} }), ); @@ -48,7 +50,10 @@ function KinCacheLines(props: { const lines = days === null ? null - : [kinCacheDayLine("today", days.day), kinCacheDayLine("yesterday", days.before)]; + : [ + kinCacheDayLine("today", days.day, messages), + kinCacheDayLine("yesterday", days.before, messages), + ]; return (
{props.label === null ? null : ( diff --git a/packages/client-runtime/src/kin/kinCacheDaily.test.ts b/packages/client-runtime/src/kin/kinCacheDaily.test.ts index e054b573b3be..a4eca6fbb087 100644 --- a/packages/client-runtime/src/kin/kinCacheDaily.test.ts +++ b/packages/client-runtime/src/kin/kinCacheDaily.test.ts @@ -106,7 +106,13 @@ describe("kinCacheDayLine", () => { name: "the last two of those, and a confined chat's turn that held another chat's text", day: "today" as const, figure: figure({ fresh: 4, freshByReason: { rules_overflow: 2, no_file: 1, other_chat: 1 } }), - text: "Kin today: 94% of input read from cache · about $0.089 a turn · 41 turns · 4 fresh starts (2 too many rule changes to add, 1 another chat's text, 1 saved conversation missing) · keeping the cache warm about $0.12", + text: "Kin today: 94% of input read from cache · about $0.089 a turn · 41 turns · 4 fresh starts (2 too many rule changes to add, 1 cross-chat or unverified context, 1 saved conversation missing) · keeping the cache warm about $0.12", + }, + { + name: "the first turn and owner room access changes have accurate reasons", + day: "today" as const, + figure: figure({ fresh: 6, freshByReason: { ended: 3, members: 2, thread: 1 } }), + text: "Kin today: 94% of input read from cache · about $0.089 a turn · 41 turns · 6 fresh starts (3 no session to continue, 2 chat access changed, 1 chat not eligible to continue) · keeping the cache warm about $0.12", }, { name: "upkeep with a null cost", diff --git a/packages/client-runtime/src/kin/kinCacheDaily.ts b/packages/client-runtime/src/kin/kinCacheDaily.ts index a8592ca7f02d..b4100715ab1c 100644 --- a/packages/client-runtime/src/kin/kinCacheDaily.ts +++ b/packages/client-runtime/src/kin/kinCacheDaily.ts @@ -1,5 +1,7 @@ import type { KinCacheDailyResult } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; /** The Usage page's cache line for Kin: one set of words on web and phone. */ export const KIN_CACHE_DAILY_COPY = { @@ -12,13 +14,14 @@ export const KIN_CACHE_DAILY_COPY = { * Why a turn started a fresh session, by the code the host stores (`lead/sessionCarry.ts` and the * carry step in `WakeupRunner.ts`). A code missing here is counted as "other", never hidden. */ -const FRESH_REASON_LABELS: Readonly> = { +type ReasonLabel = string | ((resolve: MFunctionType) => string); +const FRESH_REASON_LABELS: Readonly> = { off: "carry turned off", provider: "other AI program", - thread: "not the owner's chat", + thread: (m) => m(msg("chat not eligible to continue")), chat: "new chat", marked: "read outside content", - ended: "last turn didn't finish", + ended: (m) => m(msg("no session to continue")), foreign_run: "another run in between", expired: "cache expired", size: "conversation too long", @@ -27,8 +30,8 @@ const FRESH_REASON_LABELS: Readonly> = { instructions: "instructions changed", tool_list: "tools changed", lead: "agent changed", - members: "people changed", - other_chat: "another chat's text", + members: (m) => m(msg("chat access changed")), + other_chat: (m) => m(msg("cross-chat or unverified context")), lists: "lists changed", budgets: "budgets changed", recipes: "recipes changed", @@ -62,13 +65,13 @@ const count = (n: number, one: string) => const about = (amount: number) => amount > 0 && amount < 0.001 ? usd(amount) : `about ${usd(amount)}`; -function freshPart(figure: KinCacheDailyResult) { +function freshPart(figure: KinCacheDailyResult, resolve: MFunctionType) { if (figure.fresh === 0) return "no fresh starts"; const counts = new Map(); let recorded = 0; for (const [code, n] of Object.entries(figure.freshByReason)) { - const label = - (Object.hasOwn(FRESH_REASON_LABELS, code) ? FRESH_REASON_LABELS[code] : null) ?? OTHER; + const reason = Object.hasOwn(FRESH_REASON_LABELS, code) ? FRESH_REASON_LABELS[code] : undefined; + const label = typeof reason === "function" ? reason(resolve) : (reason ?? OTHER); counts.set(label, (counts.get(label) ?? 0) + n); recorded += n; } @@ -93,7 +96,11 @@ export const kinCacheLabel = (day: KinCacheDay) => * One day's line: whole parts, so a narrow screen wraps between them and never cuts a number. * Null is "not available", never 0% or $0; dollars are estimates at Usage's prices. */ -export function kinCacheDayLine(day: KinCacheDay, figure: KinCacheDailyResult) { +export function kinCacheDayLine( + day: KinCacheDay, + figure: KinCacheDailyResult, + resolve: MFunctionType = mFallback, +) { const label = kinCacheLabel(day); const parts: string[] = []; if (figure.turns === 0) parts.push(day === "today" ? "no turns yet" : "no turns"); @@ -107,7 +114,7 @@ export function kinCacheDayLine(day: KinCacheDay, figure: KinCacheDailyResult) { ? "cost per turn not available" : `${about(figure.costPerTurnUsd)} a turn`, count(figure.turns, "turn"), - freshPart(figure), + freshPart(figure, resolve), ); } if (figure.upkeep.count > 0) diff --git a/verification/kin/reply/README.md b/verification/kin/reply/README.md index 5c4b1c7fa2e5..2f9c681c7728 100644 --- a/verification/kin/reply/README.md +++ b/verification/kin/reply/README.md @@ -179,4 +179,6 @@ TLC 1.7.4, one worker per run; wall times reflect concurrent checks on the same **Re-confirmed 2026-11-29** on train 18 of 29 Nov (every cache lever: the shared first block, the eval placement runner, keep-warm, one stored session per chat with notes and Kin's compaction, the daily figure, the note wording and file margin, the summary wording, and the confined-status fix, joined on kin `de2553ba2c6`; no spec change, `PerChat = TRUE` as committed). All 18 rules hold over 1,719,959 states in 612 s; 40/40 variants caught in 61 s. The covered files the line changes are `lead/WakeupRunner.ts` and `lead/sessionCarry.ts`, as J3a, J3b and J3c describe above. The join adds nothing to them. Its fixes sit in keep-warm placement and its prompt, the daily figure and the Usage labels, none of which decides who a session may hold. -**Checked 2026-11-29** for train 19 A: all 18 rules hold over 1,794,442 distinct states (674,893 ms), and 43/43 mutations are caught (69,955 ms). The three added mutations expose retained direct-chat words in a private group, owner-only words to a newcomer, and mixed-wake words to a later clean group request. `SessionOnlyToEntitled` rejects each at a request that would receive the forbidden text. +**Checked 2026-11-29** for train 19 A: all 18 rules hold over 1,794,442 distinct states (674,893 ms), and 43/43 mutations are caught (69,955 ms). `owner-join-retains-private` is the entitlement catch: Ben gains Rhea’s earlier private words. `owner-cross-chat` and `owner-reuse-mixed` instead pin the per-chat design and the exclusion of mixed text; Rhea is still the only reader in both traces. + +**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. diff --git a/verification/kin/reply/Reply.tla b/verification/kin/reply/Reply.tla index 9601940cce39..16ddd0033e45 100644 --- a/verification/kin/reply/Reply.tla +++ b/verification/kin/reply/Reply.tla @@ -636,7 +636,7 @@ NoTranscript == [status |-> "none", scope |-> NoScope, tools |-> "none", heat |-> "warm", summarized |-> FALSE] SessionInit == [checking |-> TRUE, slots |-> [chat \in Chats |-> NoTranscript], - active |-> NoTurn, joinedChat |-> "none", demoted |-> FALSE, widened |-> FALSE, sends |-> 0] + active |-> NoTurn, joinedChat |-> "none", demoted |-> FALSE, widened |-> FALSE, disclosedPrivate |-> FALSE, sends |-> 0] Scope(chat) == [chat |-> chat, @@ -785,7 +785,10 @@ Close(request, status) == CompleteSession == /\ SessionStep /\ session.active # NoTurn - /\ session' = Close(session.active, "completed") + /\ LET request == session.active + retained == IF request.carried THEN Previous(request.scope.chat).privateText ELSE {} + IN session' = [Close(request, "completed") EXCEPT !.disclosedPrivate = + session.disclosedPrivate \/ (retained # {} /\ ~(Scope(request.scope.chat).readers \subseteq {"Rhea"}))] AbortSession == /\ SessionStep @@ -802,6 +805,15 @@ JoinSessionChat == /\ (Previous(chat) # NoTranscript \/ session.active.scope.chat = chat) /\ session' = [InterruptIn(chat) EXCEPT !.joinedChat = chat] +(* This private group has a former co-owner. Returning their membership grants a view + immediately; the join side effects must happen even without a new invitation to this chat. *) +ReturnSessionReader == + /\ SessionStep + /\ session.joinedChat = "none" + /\ session.active.scope.chat = "private group" /\ session.active.carried + /\ LET onReturn == IF Broken = "return-without-abort" THEN session ELSE InterruptIn("private group") + IN session' = [onReturn EXCEPT !.joinedChat = "private group"] + DemoteSessionReader == /\ SessionStep /\ ~session.demoted @@ -820,7 +832,8 @@ SessionOnlyToEntitled == IF ~session.checking THEN TRUE ELSE LET request == session.active prior == Previous(request.scope.chat) - IN /\ \A chat \in Chats : Previous(chat).summarized => ~Previous(chat).outsideMarked + IN /\ ~session.disclosedPrivate + /\ \A chat \in Chats : Previous(chat).summarized => ~Previous(chat).outsideMarked /\ request.summaryChat # "none" => /\ request.summaryChat = request.scope.chat /\ request.scope = prior.scope @@ -850,7 +863,7 @@ Next == \/ Skip \/ RunEnds \/ Flush \/ ReplyHeldBack \/ Nudge \/ RunCompletes \/ RunFails \/ RunStopped \/ Restart \/ ClaimSession \/ ReadOutside \/ CompleteSession \/ AbortSession - \/ JoinSessionChat \/ DemoteSessionReader \/ WidenSessionVisibility \/ AgeOwnerSession \/ CompactOwnerSession + \/ JoinSessionChat \/ ReturnSessionReader \/ DemoteSessionReader \/ WidenSessionVisibility \/ AgeOwnerSession \/ CompactOwnerSession Fair == WF_replyVars(Claim) /\ WF_replyVars(RunEnds) /\ WF_replyVars(Flush) /\ WF_replyVars(ReplyHeldBack) /\ WF_replyVars(Nudge) diff --git a/verification/kin/reply/view.ts b/verification/kin/reply/view.ts index 93253b290834..f8148790b096 100644 --- a/verification/kin/reply/view.ts +++ b/verification/kin/reply/view.ts @@ -250,6 +250,11 @@ export const variants = [ breaks: "SessionOnlyToEntitled", what: "a new group reader gains the owner's previously private words", }, + { + name: "return-without-abort", + breaks: "SessionOnlyToEntitled", + what: "a returning member reads the reply to a carried private turn that the return did not stop", + }, { name: "owner-reuse-mixed", breaks: "SessionOnlyToEntitled", @@ -314,6 +319,8 @@ export const step = (action: string, from: Vars, to: Vars) => { return "The turn is aborted before it completes"; case "JoinSessionChat": return `Ben joins ${String(sessionOf(to)["joinedChat"])}`; + case "ReturnSessionReader": + return "Ben is brought back and can read the private group again"; case "DemoteSessionReader": return "Meera is made a member and loses owner-level access"; case "RestartSessions": From c1d88570b7a73d86673bfafa759a0ef23638c720 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:05:00 +0530 Subject: [PATCH 6/8] refactor(kin): share the scoped owner-thread test Use one owner-wake namespace check for Social and the receipt destination, and make the join fixtures exercise the stored history floor and the actual departure. People-change: None; keeps the owner-seat checks and their coverage aligned. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/chat/KinChatService.test.ts | 3 ++- apps/server/src/kin/chat/executionNotices.ts | 5 ++--- apps/server/src/kin/lead/WakeupRunner.test.ts | 3 ++- apps/server/src/kin/lead/sessionAudience.ts | 2 ++ apps/server/src/kin/social/seat.ts | 6 ++---- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts index f02cd5722afd..94f34d922fd1 100644 --- a/apps/server/src/kin/chat/KinChatService.test.ts +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -108,6 +108,7 @@ const decodeKinMemberId = Schema.decodeSync(KinMemberId); const decodeThreadId = Schema.decodeSync(ThreadId); const decodeTask = Schema.decodeUnknownEffect(KinTaskCardState); const decodeSend = Schema.decodeUnknownEffect(KinMessagesSendInput); +const decodePendingAction = Schema.decodeSync(KinPendingAction); const database = authorityLayer; const repositories = Layer.provideMerge(Repository.layer, database); const dependencies = Layer.provideMerge(Layer.merge(Hub.layer, RefreshHub.layer), repositories); @@ -368,7 +369,7 @@ it.effect( ] as const) { if (to !== undefined) yield* identity.registerAgentThread({ orgId, agentId, threadId: source, chatId: to }); - const action = Schema.decodeSync(KinPendingAction)({ + const action = decodePendingAction({ id: `delete-${name}`, orgId, idempotencyKey: "a".repeat(64), diff --git a/apps/server/src/kin/chat/executionNotices.ts b/apps/server/src/kin/chat/executionNotices.ts index 20edaba197d9..2f0486f3b596 100644 --- a/apps/server/src/kin/chat/executionNotices.ts +++ b/apps/server/src/kin/chat/executionNotices.ts @@ -17,7 +17,7 @@ import { type KinExecutionOutcome, type KinKeyChange, } from "../approvals/ExecutionNotices.ts"; -import { MIXED_WAKE_THREAD_PREFIX, OWNER_CHAT_THREAD_PREFIX } from "../lead/sessionAudience.ts"; +import { isScopedOwnerWakeThread } from "../lead/sessionAudience.ts"; import { CHIEF_OF_STAFF_DOMAIN } from "../lead/orgLeads.ts"; import { textLocale, type TextClock } from "../work/companyProfile.ts"; import { ownerZone } from "../work/recordRows.ts"; @@ -87,8 +87,7 @@ export const layer = Layer.effect( */ const post = Effect.fnUntraced(function* (action: KinPendingAction, body: string) { const source = action.requestedBy.threadId; - const ownerSource = - source.startsWith(OWNER_CHAT_THREAD_PREFIX) || source.startsWith(MIXED_WAKE_THREAD_PREFIX); + const ownerSource = isScopedOwnerWakeThread(source); const [lead] = yield* sql<{ readonly chatId: string; readonly askedIn: string | null; diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index ce43283ecd0a..eb1f60f5b124 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -3850,7 +3850,8 @@ describe("WakeupRunner", () => { yield* sql.withTransaction( Effect.gen(function* () { yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) - VALUES ('private-meera', ${orgId}, ${chatId}, 'person', ${personId}, 'member', '2026-11-26')`; + VALUES ('private-new-reader', ${orgId}, ${chatId}, 'person', ${personId}, 'member', '2026-11-26')`; + yield* recordJoin(sql, { orgId, chatId, memberId: "private-new-reader" }); yield* onPersonJoined({ orgId, chatId, personId }); }), ); diff --git a/apps/server/src/kin/lead/sessionAudience.ts b/apps/server/src/kin/lead/sessionAudience.ts index 301a022cb6d8..f215ff5c60fd 100644 --- a/apps/server/src/kin/lead/sessionAudience.ts +++ b/apps/server/src/kin/lead/sessionAudience.ts @@ -121,6 +121,8 @@ export const confinedTranscriptProven = Effect.fn("KinSessionAudience.transcript export const OWNER_CHAT_THREAD_PREFIX = "kin:owner-chat:"; export const MIXED_WAKE_THREAD_PREFIX = "kin:mixed-wake:"; +export const isScopedOwnerWakeThread = (id: string) => + id.startsWith(OWNER_CHAT_THREAD_PREFIX) || id.startsWith(MIXED_WAKE_THREAD_PREFIX); type Wake = { readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly wakeupId: string }; diff --git a/apps/server/src/kin/social/seat.ts b/apps/server/src/kin/social/seat.ts index 76fc2c117836..379b42a7f265 100644 --- a/apps/server/src/kin/social/seat.ts +++ b/apps/server/src/kin/social/seat.ts @@ -2,7 +2,7 @@ import type { ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as SqlClient from "effect/sql/SqlClient"; -import { MIXED_WAKE_THREAD_PREFIX, OWNER_CHAT_THREAD_PREFIX } from "../lead/sessionAudience.ts"; +import { isScopedOwnerWakeThread } from "../lead/sessionAudience.ts"; /** A remit that includes social media: the agents that get Social's tools and section. */ export const isSocialDomain = (domain: string) => /^(social|marketing|content|brand)/.test(domain); @@ -16,9 +16,7 @@ export const socialSeatThread = Effect.fn("KinSocial.seatThread")( const sql = yield* SqlClient.SqlClient; // The owner's own threads only (one per chat he alone reads, a mixed wake's, or the old one // with no chat); a shared or co-owner chat's turn never carries them. - const owners = - threadId.startsWith(OWNER_CHAT_THREAD_PREFIX) || - threadId.startsWith(MIXED_WAKE_THREAD_PREFIX); + const owners = isScopedOwnerWakeThread(threadId); const rows = yield* sql<{ domain: string }>`SELECT l.domain FROM kin_agent_threads t JOIN kin_leads l ON l.org_id = t.org_id AND l.agent_id = t.agent_id WHERE t.thread_id = ${threadId} AND t.ended_at IS NULL AND (${owners} OR t.chat_id IS NULL) From 102b56c6044722877317946528e6d32538b479d0 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:09:02 +0530 Subject: [PATCH 7/8] test(kin): exercise the first turn after a reader returns Hold a carried provider turn open during real invite acceptance, then verify the returning reader ends its slot and the next group turn starts fresh. People-change: None; covers the running-turn fence with an actual runner and invite transaction. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/lead/WakeupRunner.test.ts | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index eb1f60f5b124..92921705871b 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -9,6 +9,8 @@ import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit import { assert, describe, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import { + AuthSessionId, + AuthStandardClientScopes, CommandId, DEFAULT_KIN_BACKGROUND_MODEL_SELECTION, EventId, @@ -39,6 +41,8 @@ import { mailRuleContentHash } from "../arrivals/ruleContent.ts"; import * as OwnerCheck from "../triggers/ownerCheck.ts"; import * as ChatService from "../chat/KinChatService.ts"; import * as ChatHub from "../chat/KinChatHub.ts"; +import * as People from "../people/KinPeople.ts"; +import { SessionStore } from "../../auth/SessionStore.ts"; import * as Groups from "../chat/KinGroups.ts"; import * as Presence from "../reply/KinPresence.ts"; import * as ReplyBridge from "../reply/KinReplyBridge.ts"; @@ -3944,6 +3948,101 @@ describe("WakeupRunner", () => { }).pipe(provideDeterministicTestRuntime), ); + it.effect( + "the first group wake after a real return cannot continue the in-flight owner session", + () => + Effect.gen(function* () { + const hold = yield* Deferred.make(); + yield* Effect.gen(function* () { + const sql = yield* seedCarry; + const queue = yield* KinEventQueue.KinEventQueue; + const identity = yield* KinIdentity.KinIdentity; + const owner = { _tag: "person" as const, orgId, personId: KinPersonId.make("owner") }; + const meera = KinPersonId.make("meera"); + const ownerSession = { + sessionId: AuthSessionId.make("owner-fixture"), + subject: "browser", + method: "browser-session-cookie" as const, + scopes: AuthStandardClientScopes, + }; + const people = yield* People.make.pipe( + Effect.provideService(KinIdentity.KinIdentity, { + ...identity, + owner, + resolve: () => Effect.succeed([owner]), + }), + Effect.provide(ChatHub.layer), + Effect.provide( + Layer.mock(SessionStore)({ + issue: () => + Effect.succeed({ + sessionId: AuthSessionId.make("returning-device"), + token: "fixture-token", + expiresAt: DateTime.makeUnsafe(Date.UTC(2027, 0, 1)), + }), + revoke: () => Effect.succeed(true), + }), + ), + ); + 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-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"); + const prior = (yield* carryRows).at(-1)!; + assert.include(prior, { sent: "carried" }); + + yield* queue.enqueue(yield* ownerSays("dispatch-in-flight", "private")); + const threads = yield* ThreadManagement.ThreadManagementService; + const running = yield* threads.streamDomainEvents.pipe( + Stream.filter( + (update) => + update.type === "provider-turn.updated" && update.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const active = yield* run(); + yield* Fiber.join(running); + const inflight = (yield* carryRows).at(-1)!; + assert.include(inflight, { + sent: "carried", + status: "running", + threadId: prior.threadId, + }); + const invite = yield* people.createInvite(ownerSession, { + orgId, + displayName: "Meera", + personId: meera, + }); + yield* people.accept({ secret: invite.secret }); + 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}`; + yield* Deferred.succeed(hold, undefined); + yield* Fiber.join(active); + assert.isString(fenced?.ended_at); + assert.isNumber(fenced?.aborted_at); + yield* wake("dispatch-after-return", "private"); + const next = (yield* carryRows).at(-1)!; + assert.include(next, { sent: "fresh", reason: "members" }); + assert.notEqual(next.threadId, prior.threadId); + }).pipe( + Effect.provide( + carryHarness({ + beforeTurn: ({ threadId }) => readCarryHook(threadId).pipe(Effect.asVoid), + holdRunning: (ordinal) => (ordinal === 3 ? hold : undefined), + }), + ), + ); + }).pipe(provideDeterministicTestRuntime), + ); + it.effect("a task from an ended owner group reports direct without adopting the old run", () => Effect.gen(function* () { const held = yield* Deferred.make(); From e9d7a2d08331b04791d6e7189efaef996ee28720 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:12:11 +0530 Subject: [PATCH 8/8] test(kin): use the complete issued-session fixture The return regression now supplies all required metadata from the session-store contract without changing the invite path or its assertions. People-change: None; only the return test fixture changes. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/lead/WakeupRunner.test.ts | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 92921705871b..6f2537ca2d0c 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -3971,17 +3971,27 @@ describe("WakeupRunner", () => { owner, resolve: () => Effect.succeed([owner]), }), - Effect.provide(ChatHub.layer), Effect.provide( - Layer.mock(SessionStore)({ - issue: () => - Effect.succeed({ - sessionId: AuthSessionId.make("returning-device"), - token: "fixture-token", - expiresAt: DateTime.makeUnsafe(Date.UTC(2027, 0, 1)), - }), - revoke: () => Effect.succeed(true), - }), + Layer.merge( + ChatHub.layer, + Layer.mock(SessionStore)({ + cookieName: "fixture-session", + legacyCookieName: undefined, + issue: (input) => + Effect.succeed({ + sessionId: AuthSessionId.make("returning-device"), + token: "fixture-token", + method: "bearer-access-token", + client: { + ...input?.client, + deviceType: input?.client?.deviceType ?? "mobile", + }, + scopes: input?.scopes ?? [], + expiresAt: DateTime.makeUnsafe(Date.UTC(2027, 0, 1)), + }), + revoke: () => Effect.succeed(true), + }), + ), ), ); yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at)