From a334a39bafef69cb3626b16332b56ea0886a0b83 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:28:42 +0530 Subject: [PATCH 1/3] fix(kin): carry eligible private wakes by default Use the same idle limit for wall time and company time. A wake that brings outside content can use the clean private session, but the following wake starts fresh. People-change: Eligible private chats continue by default, and a mail check-in no longer starts over when its session is clean. An explicit off setting still starts fresh. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/lead/WakeupRunner.test.ts | 292 +++++++++++++----- apps/server/src/kin/lead/WakeupRunner.ts | 24 +- apps/server/src/kin/lead/sessionCarry.test.ts | 40 ++- apps/server/src/kin/lead/sessionCarry.ts | 66 ++-- packages/contracts/src/settings.kin.test.ts | 12 +- packages/contracts/src/settings.ts | 2 +- verification/kin/discussion/README.md | 2 + verification/kin/reply/README.md | 2 + 8 files changed, 336 insertions(+), 104 deletions(-) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 3194810a1e07..240911377544 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -471,6 +471,7 @@ const carryRows = Effect.gen(function* () { threadId: ThreadId; status: string; reason: string | null; + markSource: string | null; sent: string | null; missed: number; compacted: number | null; @@ -478,6 +479,7 @@ const carryRows = Effect.gen(function* () { delta: string | null; }>`SELECT wakeup_id AS "wakeupId", thread_id AS "threadId", status, delta_json AS delta, json_extract(carry_json, '$.reason') AS reason, json_extract(carry_json, '$.sent') AS sent, + json_extract(carry_json, '$.markSource') AS "markSource", json_extract(carry_json, '$.missed') AS missed, json_extract(carry_json, '$.compacted') AS compacted, json_extract(carry_json, '$.cursorCaptured') AS captured @@ -2004,7 +2006,7 @@ describe("WakeupRunner", () => { Effect.provide( WakeupRunner.layer.pipe( Layer.provide(rejectBad), - Layer.provideMerge(orchestrationHarness()), + Layer.provideMerge(orchestrationHarness({ settings: { kinSessionCarry: false } })), Layer.provide(bridge), ), ), @@ -2552,6 +2554,150 @@ describe("WakeupRunner", () => { }), ); + it.effect.each([ + ["a wake that starts with outside mail continues a clean session", "mail"], + ["an approved draft's own wake starts fresh for marked", "draft"], + ] as const)("%s", ([, source]) => { + const database = KinPersistence.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)); + return Effect.gen(function* () { + let show = false; + let firstCall: string | undefined; + let sensitiveAtFirstCall = false; + const sql = yield* SqlClient.SqlClient; + const prepare: Memory.Memory["Service"]["prepareWakeup"] = (orgId, wakeupId) => + Effect.gen(function* () { + if (show && wakeupId !== undefined) { + if (source === "mail") yield* markOutside({ orgId, wakeupId }, "check-in"); + else + yield* sql`UPDATE kin_events SET json = json_set(json, '$.subject.approved', json('true')) + WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId}`; + } + return { head: "abc", indexAsOf: DateTime.makeUnsafe(0), read: "/private/tmp" }; + }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.orDie); + const beforeTurn = ({ threadId }: ProviderAdapterV2TurnInput) => + Effect.gen(function* () { + if (!show) return; + firstCall = yield* fullSessionRefusal(threadId); + const [running] = yield* sql<{ wakeupId: KinWakeupId }>` + SELECT wakeup_id AS "wakeupId" FROM kin_wakeups WHERE thread_id = ${threadId} + AND status = 'running'`; + sensitiveAtFirstCall = yield* turnSensitive(orgId, running!.wakeupId); + }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.orDie); + yield* Effect.gen(function* () { + yield* seedCarry; + yield* wake("tidewater-first"); + const [first] = yield* carryRows; + yield* sql`INSERT INTO kin_wakeup_sensitive_reads (org_id, wakeup_id, read_at) + VALUES (${orgId}, ${first!.wakeupId}, 1)`; + show = true; + yield* wake("tidewater-mail"); + const [, next] = yield* carryRows; + if (source === "mail") { + assert.strictEqual(next?.sent, "carried"); + assert.isNull(next?.reason); + assert.deepStrictEqual(yield* sessions(), [1, 1]); + assert.strictEqual(firstCall, SESSION_REFUSAL.outside); + assert.isTrue(sensitiveAtFirstCall); + } else { + assert.include(next, { sent: "fresh", reason: "marked", markSource: "approved_draft" }); + show = false; + yield* sql`UPDATE kin_events SET wakeup_id = NULL WHERE wakeup_id = ${next!.wakeupId}`; + yield* wake("tidewater-after-draft"); + assert.include((yield* carryRows).at(-1), { + sent: "fresh", + reason: "marked", + markSource: "approved_draft", + }); + assert.deepStrictEqual(yield* sessions(), [1, 2, 3]); + } + }).pipe(Effect.provide(carryHarness({ prepare, beforeTurn, database }))); + }).pipe(Effect.provide(database), provideDeterministicTestRuntime); + }); + + it.effect.each([ + [ + "the wake after an outside read starts fresh for marked, even when it starts clean", + "completed", + "intact", + ], + ["a mail wake that is aborted still ends the session", "released", "aborted"], + ["a mail wake that fails still ends the session", "failed", "unstamped"], + ["a mail wake that is stopped still ends the session", "interrupted", "unstamped"], + ["a mail wake that is released and retried still ends the session", "released", "retry"], + ["a mail wake that is cut off by a restart still ends the session", "interrupted", "restart"], + ["a released mail wake from a fresh session still ends that session", "released", "fresh"], + ["an aborted clean wake ends the session", "released", "clean-abort"], + [ + "an earlier mail wake without a carry stamp still marks its provider session", + "completed", + "older", + ], + ] as const)("%s", ([, status, scenario]) => + Effect.gen(function* () { + const sql = yield* seedCarry; + yield* wake("tidewater-first"); + if (scenario === "fresh") yield* TestClock.adjust(CARRY_LIFETIME_MS + 1); + yield* wake("tidewater-mail"); + if (scenario === "older") { + yield* wake("tidewater-newer"); + assert.deepStrictEqual(yield* sessions(), [1, 1, 1]); + } + const [, mail] = yield* carryRows; + const aborted = scenario === "aborted" || scenario === "clean-abort"; + const dirty = scenario !== "clean-abort"; + if (dirty) yield* markOutside({ orgId, wakeupId: mail!.wakeupId }, "check-in"); + yield* sql`UPDATE kin_wakeups SET status = ${status}, + aborted_at = ${aborted ? 1 : null}, + carry_json = CASE WHEN ${scenario !== "intact" && scenario !== "fresh" && scenario !== "clean-abort"} + THEN NULL ELSE carry_json END + WHERE wakeup_id = ${mail!.wakeupId}`; + if (scenario === "restart") { + yield* sql`UPDATE kin_wakeups SET carry_json = json_set(carry_json, '$.bootId', 'older') + WHERE org_id = ${orgId}`; + yield* (yield* KinSessionContext).forget(mail!.threadId); + } + if (scenario === "retry") { + yield* sql`UPDATE kin_events SET state = 'queued', wakeup_id = NULL, attempts = 1, + not_before = NULL, replied_at = NULL + WHERE org_id = ${orgId} AND event_id = 'tidewater-mail'`; + yield* Fiber.join(yield* run()); + } else yield* wake("tidewater-clean"); + const next = (yield* carryRows).at(-1)!; + assert.include(next, { + reason: dirty ? "marked" : "ended", + sent: "fresh", + markSource: dirty ? "earlier_outside" : null, + }); + assert.deepStrictEqual( + yield* sessions(), + scenario === "fresh" ? [1, 2, 3] : scenario === "older" ? [1, 1, 1, 2] : [1, 1, 2], + ); + if (scenario !== "retry") + assert.isFalse(yield* outsideRead({ orgId, wakeupId: next.wakeupId })); + }).pipe( + Effect.provide( + carryHarness({ beforeTurn: (input) => readCarryHook(input.threadId).pipe(Effect.asVoid) }), + ), + provideDeterministicTestRuntime, + ), + ); + + it.effect("a session stamped before K244 starts fresh once", () => + Effect.gen(function* () { + const sql = yield* seedCarry; + yield* wake("tidewater-old"); + const [old] = yield* carryRows; + yield* sql`UPDATE kin_wakeups SET carry_json = json_remove(carry_json, '$.ageClock', '$.lastRequestKinAt') + WHERE wakeup_id = ${old!.wakeupId}`; + yield* wake("tidewater-fresh"); + yield* wake("tidewater-follow-up"); + const [, fresh, next] = yield* carryRows; + assert.include(fresh, { reason: "expired", sent: "fresh" }); + assert.include(next, { reason: null, sent: "carried" }); + assert.deepStrictEqual(yield* sessions(), [1, 2, 2]); + }).pipe(Effect.provide(carryHarness()), provideDeterministicTestRuntime), + ); + it.effect("a change list over 9,000 characters goes inside the message", () => Effect.gen(function* () { yield* seedCarry; @@ -2707,44 +2853,42 @@ describe("WakeupRunner", () => { ); }); - it.effect( - "a released carried turn with a failed cursor capture cannot match the older snapshot", - () => { - const started = Deferred.makeUnsafe(); - return Effect.gen(function* () { - const sql = yield* seedCarry; - yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) + it.effect("a released carried turn with a failed cursor capture ends the session", () => { + const started = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const sql = yield* seedCarry; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) VALUES ('direct-lead', ${orgId}, 'direct', 'agent', ${agentId}, 'member', '2026-11-26')`; - yield* wake("tidewater-first"); - const [first] = yield* carryRows; - assert.strictEqual(first?.captured, 1); - yield* (yield* KinEventQueue.KinEventQueue).enqueue( - yield* ownerSays("tidewater-capture", "direct"), + yield* wake("tidewater-first"); + const [first] = yield* carryRows; + assert.strictEqual(first?.captured, 1); + yield* (yield* KinEventQueue.KinEventQueue).enqueue( + yield* ownerSays("tidewater-capture", "direct"), + ); + const active = yield* run(); + yield* Deferred.await(started); + const [, carrying] = yield* carryRows; + assert.strictEqual(carrying?.reason, null); + assert.strictEqual(carrying?.sent, "carried"); + const threads = yield* ThreadManagement.ThreadManagementService; + const projection = yield* carryProjection; + yield* threads + .streamStoredEventsFrom({ + threadId: carrying!.threadId, + afterSequence: 0, + eventType: "provider-turn.updated", + }) + .pipe( + Stream.filter( + ({ event }) => + event.type === "provider-turn.updated" && + event.payload.ordinal === 2 && + event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, ); - const active = yield* run(); - yield* Deferred.await(started); - const [, carrying] = yield* carryRows; - assert.strictEqual(carrying?.reason, null); - assert.strictEqual(carrying?.sent, "carried"); - const threads = yield* ThreadManagement.ThreadManagementService; - const projection = yield* carryProjection; - yield* threads - .streamStoredEventsFrom({ - threadId: carrying!.threadId, - afterSequence: 0, - eventType: "provider-turn.updated", - }) - .pipe( - Stream.filter( - ({ event }) => - event.type === "provider-turn.updated" && - event.payload.ordinal === 2 && - event.payload.status === "running", - ), - Stream.take(1), - Stream.runDrain, - ); - yield* sql`WITH RECURSIVE held(seq) AS ( + yield* sql`WITH RECURSIVE held(seq) AS ( SELECT 100 UNION ALL SELECT seq + 1 FROM held WHERE seq < ${100 + SESSION_CHANGES_CAP * 4} ) INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, author_agent_id, @@ -2753,40 +2897,39 @@ describe("WakeupRunner", () => { SELECT 'held-' || seq, ${orgId}, 'direct', seq, 'agent', ${agentId}, ${carrying!.threadId}, 'owner', 'direct-lead', ${carrying!.wakeupId}, 'member', 'text', 'Invented', '[]', 'posted', '2026-11-26' FROM held`; - yield* sql`INSERT INTO kin_org_state (org_id, paused, paused_at, paused_by) VALUES (${orgId}, 1, 1000, 'owner')`; - yield* threads.interruptThread({ - projectId: projection.thread.projectId, - threadId: carrying!.threadId, - runId: projection.runs.at(-1)!.id, - commandId: CommandId.make("fixture-pause"), - }); - yield* Fiber.join(active); - const [, released] = yield* carryRows; - assert.strictEqual(released?.status, "released"); - assert.strictEqual(released?.captured, 0); - yield* sql`UPDATE kin_org_state SET paused = 0, paused_at = NULL, paused_by = NULL WHERE org_id = ${orgId}`; - yield* TestClock.adjust(KinStop.PAUSE_POLL_INTERVAL_MS); - yield* wake("tidewater-after-release"); - const [, , next] = yield* carryRows; - assert.strictEqual(next?.reason, "snapshot"); - assert.deepStrictEqual(yield* sessions(), [1, 1, 2]); - }).pipe( - Effect.provide( - carryHarness({ - untilInterrupted: (ordinal) => ordinal === 2, - beforeTurn: (input) => - input.runOrdinal === 2 - ? readCarryHook(input.threadId).pipe( - Effect.andThen(Deferred.succeed(started, undefined)), - Effect.asVoid, - ) - : Effect.void, - }), - ), - provideDeterministicTestRuntime, - ); - }, - ); + yield* sql`INSERT INTO kin_org_state (org_id, paused, paused_at, paused_by) VALUES (${orgId}, 1, 1000, 'owner')`; + yield* threads.interruptThread({ + projectId: projection.thread.projectId, + threadId: carrying!.threadId, + runId: projection.runs.at(-1)!.id, + commandId: CommandId.make("fixture-pause"), + }); + yield* Fiber.join(active); + const [, released] = yield* carryRows; + assert.strictEqual(released?.status, "released"); + assert.strictEqual(released?.captured, 0); + yield* sql`UPDATE kin_org_state SET paused = 0, paused_at = NULL, paused_by = NULL WHERE org_id = ${orgId}`; + yield* TestClock.adjust(KinStop.PAUSE_POLL_INTERVAL_MS); + yield* wake("tidewater-after-release"); + const [, , next] = yield* carryRows; + assert.strictEqual(next?.reason, "ended"); + assert.deepStrictEqual(yield* sessions(), [1, 1, 2]); + }).pipe( + Effect.provide( + carryHarness({ + untilInterrupted: (ordinal) => ordinal === 2, + beforeTurn: (input) => + input.runOrdinal === 2 + ? readCarryHook(input.threadId).pipe( + Effect.andThen(Deferred.succeed(started, undefined)), + Effect.asVoid, + ) + : Effect.void, + }), + ), + provideDeterministicTestRuntime, + ); + }); it.effect( "a carried beside delta lost across boots counts as missed when recovery completes", @@ -3117,7 +3260,7 @@ describe("WakeupRunner", () => { yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids, kind, carry_json, last_request_at, context_tokens) VALUES ('shadow-refresh', ${orgId}, ${agentId}, ${second!.thread_id}, ${selection.model}, ${refreshAt}, - 'completed', '[]', 'upkeep', ${first!.carry_json}, ${refreshAt}, 120)`; + 'completed', '[]', 'upkeep', json_set(${first!.carry_json}, '$.lastRequestKinAt', ${refreshAt}), ${refreshAt}, 120)`; const compare = carryFacts( { orgId, agentId, wakeupId: KinWakeupId.make("candidate") }, { @@ -3130,12 +3273,14 @@ describe("WakeupRunner", () => { toolListSha: toolHash, prompt: fingerprintPrompt(["invented standing"], "invented index"), enabled: true, - now: refreshAt + CARRY_LIFETIME_MS + 1, + now: refreshAt + CARRY_LIFETIME_MS - 1, + wallNow: refreshAt + CARRY_LIFETIME_MS + 1, stopRevision: 0, }, ); const refreshed = yield* compare; assert.strictEqual(refreshed.facts.gapMs, CARRY_LIFETIME_MS + 1); + assert.strictEqual(refreshed.facts.companyGapMs, CARRY_LIFETIME_MS - 1); assert.strictEqual(refreshed.contextTokens, 120); assert.deepStrictEqual(decideCarry(refreshed.facts), { carry: false, reason: "expired" }); yield* sql`INSERT INTO kin_wakeup_sensitive_reads (org_id, wakeup_id, read_at) @@ -3155,6 +3300,7 @@ describe("WakeupRunner", () => { Layer.merge( harnessWith( { + settings: { kinSessionCarry: false }, toolOutputs: [ { tool: "lookup", output: "invented" }, { tool: "lookup", output: "result only" }, diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 6691f4536bdf..5cadc9e738cf 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -56,6 +56,7 @@ import { KinRefreshHub, KinRefreshObserver } from "../chat/KinRefreshHub.ts"; import { KinChatService } from "../chat/KinChatService.ts"; import * as HostBackup from "../hostBackup.ts"; import { ServerConfig } from "../../config.ts"; +import { KinDevClock } from "../DevClock.ts"; import * as Floor from "../floor/KinFloor.ts"; import * as Writer from "../memory/MemoryWriter.ts"; import * as Memory from "../memory/Memory.ts"; @@ -237,6 +238,13 @@ const decodeTaskIds = Schema.decodeUnknownOption( const make = Effect.gen(function* () { const boot = yield* Effect.serviceOption(KinBoot); const bootId = Option.isSome(boot) ? boot.value : yield* ulid; + const devClock = Option.getOrUndefined(yield* Effect.serviceOption(KinDevClock)); + const realClock = + devClock?.onRealClock({ now: Clock.currentTimeMillis }).now ?? Clock.currentTimeMillis; + const carryClocks = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + return { now, wallNow: realClock === Clock.currentTimeMillis ? now : yield* realClock }; + }); const sessionContext = Option.getOrUndefined(yield* Effect.serviceOption(KinSessionContext)); const workspace = Option.getOrUndefined(yield* Effect.serviceOption(KinWorkspace)); const agentSessions = Option.getOrUndefined(yield* Effect.serviceOption(KinAgentSessions)); @@ -862,7 +870,7 @@ const make = Effect.gen(function* () { if (row.threadId === null) return; const threadId = row.threadId; const unread = sessionContext?.take(threadId) !== undefined; - // A released turn can leave the previous row eligible but its snapshot is no longer valid. + // Never leave the older snapshot active if capturing this turn fails. if (snapshot !== undefined && sessionContext !== undefined) yield* sessionContext.forget(threadId); if (row.runId === null) return; @@ -909,7 +917,10 @@ const make = Effect.gen(function* () { ); const toolListSha = agentSessions?.lastToolList(threadId) ?? null; const contextTokens = last?.tokenUsage?.usedTokens ?? null; - const lastRequestAt = last?.startedAt == null ? null : DateTime.toEpochMillis(last.startedAt); + const lastRequest = last?.completedAt ?? last?.startedAt; + const lastRequestAt = lastRequest == null ? null : DateTime.toEpochMillis(lastRequest); + const { now, wallNow } = yield* carryClocks; + const lastRequestKinAt = lastRequestAt === null ? null : lastRequestAt + (now - wallNow); const [shadow] = yield* sql<{ background: number | null; carry: number | null; @@ -923,7 +934,8 @@ const make = Effect.gen(function* () { previousContext: number | null; }>` UPDATE kin_wakeups SET context_tokens = ${contextTokens}, last_request_at = ${lastRequestAt}, - carry_json = json_set(carry_json, '$.toolListSha', ${toolListSha}) + carry_json = json_set(carry_json, '$.toolListSha', ${toolListSha}, + '$.lastRequestKinAt', ${lastRequestKinAt}) WHERE org_id = ${row.orgId} AND wakeup_id = ${row.wakeupId} RETURNING json_extract(carry_json, '$.background') AS background, json_extract(carry_json, '$.carry') AS carry, @@ -2381,7 +2393,7 @@ const make = Effect.gen(function* () { toolListSha, prompt: promptFingerprint, enabled: hostSettings.kinSessionCarry, - now: yield* Clock.currentTimeMillis, + ...(yield* carryClocks), stopRevision: refreshHub?.stopRevision(orgId) ?? 0, compactAtTokens: hostSettings.kinSessionCompactAtTokens, }); @@ -2461,7 +2473,11 @@ const make = Effect.gen(function* () { sent, sessionStart: sent === "fresh" ? facts.sessionStart : facts.carriedFrom, carriedFrom: facts.carriedFrom, + ageClock: 2, gapMs: facts.facts.gapMs, + companyGapMs: facts.facts.companyGapMs, + markSource: facts.markSource, + ...(facts.approvedDraft ? { approvedDraft: true } : {}), contextTokens: facts.contextTokens, bootId, toolListSha, diff --git a/apps/server/src/kin/lead/sessionCarry.test.ts b/apps/server/src/kin/lead/sessionCarry.test.ts index ace6f98aba84..b4e792426767 100644 --- a/apps/server/src/kin/lead/sessionCarry.test.ts +++ b/apps/server/src/kin/lead/sessionCarry.test.ts @@ -2,7 +2,7 @@ import * as Effect from "effect/Effect"; import { it as effectIt } from "@effect/vitest"; import { describe, expect, it } from "vite-plus/test"; -import { type CarryFacts, decideCarry } from "./sessionCarry.ts"; +import { CARRY_LIFETIME_MS, type CarryFacts, decideCarry } from "./sessionCarry.ts"; const clean: CarryFacts = { enabled: true, @@ -12,7 +12,8 @@ const clean: CarryFacts = { previousCompleted: true, marked: false, foreignRun: false, - gapMs: 55 * 60_000, + gapMs: CARRY_LIFETIME_MS, + companyGapMs: CARRY_LIFETIME_MS, sameBoot: true, sameModel: true, sameInstructions: true, @@ -35,10 +36,10 @@ describe("decides carry only when every condition holds", () => { ["provider", { provider: "codex", ownerThread: false }], ["thread", { ownerThread: false, sameChat: false }], ["chat", { sameChat: false, previousCompleted: false }], - ["ended", { previousCompleted: false, marked: true }], - ["marked", { marked: true, foreignRun: true }], + ["marked", { marked: true, previousCompleted: false }], + ["ended", { previousCompleted: false, foreignRun: true }], ["foreign_run", { foreignRun: true, gapMs: null }], - ["expired", { gapMs: 55 * 60_000 + 1, sameBoot: false }], + ["expired", { gapMs: CARRY_LIFETIME_MS + 1, sameBoot: false }], ["boot", { sameBoot: false, sameModel: false }], ["model", { sameModel: false, sameInstructions: false }], ["instructions", { sameInstructions: false, sameToolList: false }], @@ -57,6 +58,35 @@ describe("decides carry only when every condition holds", () => { }, ); + it("a session started under the system layout starts fresh for instructions under the block layout", () => { + const systemStamp = { instructions: "a".repeat(64) }; + const blockStamp = { instructions: "b".repeat(64) }; + const nextWake = (previous: { instructions: string }) => + decideCarry({ + ...clean, + sameInstructions: previous.instructions === blockStamp.instructions, + }); + + expect(nextWake(systemStamp)).toEqual({ carry: false, reason: "instructions" }); + expect(nextWake(blockStamp)).toEqual({ carry: true }); + }); + + const limit = CARRY_LIFETIME_MS; + it.each([ + ["wall time over", limit + 1, limit - 1, { carry: false, reason: "expired" }], + ["company time over", limit - 1, limit + 1, { carry: false, reason: "expired" }], + ["both under", limit - 1, limit - 1, { carry: true }], + ] as const)( + "a session idle past the limit by either clock starts fresh for expired (%s)", + (_, gapMs, companyGapMs, expected) => { + const facts = { ...clean, gapMs, companyGapMs }; + expect(decideCarry(facts)).toEqual(expected); + expect(decideCarry({ ...facts, compactedSince: true })).toEqual( + expected.carry ? { carry: true, refill: true } : expected, + ); + }, + ); + it("carries at both inclusive limits", () => { expect(decideCarry(clean)).toEqual({ carry: true }); }); diff --git a/apps/server/src/kin/lead/sessionCarry.ts b/apps/server/src/kin/lead/sessionCarry.ts index 9f32d696cc8a..56a854958042 100644 --- a/apps/server/src/kin/lead/sessionCarry.ts +++ b/apps/server/src/kin/lead/sessionCarry.ts @@ -30,6 +30,7 @@ export interface CarryFacts { readonly marked: boolean; readonly foreignRun: boolean; readonly gapMs: number | null; + readonly companyGapMs: number | null; readonly contextTokens?: number | null; readonly compactAtTokens?: number; readonly compactedSince?: boolean; @@ -49,9 +50,13 @@ export interface CarryFacts { readonly missed: boolean; } -export const CARRY_LIFETIME_MS = 55 * 60_000; +// Queue 80: the longest gap with at least 97.5% cache reads, minus five minutes, capped at 55. +export const CARRY_LIFETIME_MS = 30 * 60_000; const CARRY_INDEX_LINES = 40; +const expired = (gapMs: number | null) => + gapMs === null || !Number.isFinite(gapMs) || gapMs < 0 || gapMs > CARRY_LIFETIME_MS; + export function decideCarry(facts: CarryFacts) { const reason = !facts.enabled ? "off" @@ -61,13 +66,13 @@ export function decideCarry(facts: CarryFacts) { ? "thread" : !facts.sameChat ? "chat" - : !facts.previousCompleted - ? "ended" - : facts.marked - ? "marked" + : facts.marked + ? "marked" + : !facts.previousCompleted + ? "ended" : facts.foreignRun ? "foreign_run" - : facts.gapMs === null || facts.gapMs < 0 || facts.gapMs > CARRY_LIFETIME_MS + : expired(facts.gapMs) || expired(facts.companyGapMs) ? "expired" : facts.contextTokens != null && facts.compactAtTokens !== undefined && @@ -145,6 +150,7 @@ const Fingerprint = Schema.Struct({ const decodeFingerprint = Schema.decodeUnknownOption(Schema.fromJsonString(Fingerprint)); const decodeIndex = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Schema.String))); const CarryStamp = Schema.Struct({ + ageClock: Schema.optional(Schema.Number), bootId: Schema.String, sessionStart: KinWakeupId, toolListSha: Schema.NullOr(Schema.String), @@ -244,6 +250,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( readonly prompt: PromptFingerprint; readonly enabled: boolean; readonly now: number; + readonly wallNow: number; readonly stopRevision: number; readonly compactAtTokens?: number; }, @@ -300,6 +307,7 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( standing: input.prompt.standing, stop: input.stopRevision, }; + // Even a released or unstamped wake may already have sent text to the provider. const [previous] = yield* sql<{ wakeupId: KinWakeupId; status: string; @@ -314,13 +322,13 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( SELECT w.wakeup_id AS "wakeupId", w.status, w.carry_json AS stamp, w.standing_key AS fingerprint, w.prompt_index AS "promptIndex", w.started_at AS "startedAt", w.context_tokens AS "contextTokens", r.provider_thread_id AS "providerThreadId", - CASE WHEN t.ended_at IS NOT NULL OR t.thread_id IS NULL OR t.chat_id IS NOT NULL - THEN 1 ELSE 0 END AS ended + CASE WHEN w.aborted_at IS NOT NULL OR t.ended_at IS NOT NULL + OR t.thread_id IS NULL OR t.chat_id IS NOT 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) LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = w.run_id AND r.thread_id = w.thread_id WHERE w.org_id = ${orgId} AND w.agent_id = ${agentId} AND w.thread_id = ${threadId} - AND w.wakeup_id <> ${wakeupId} AND w.kind = 'turn' AND w.status <> 'released' + AND w.wakeup_id <> ${wakeupId} AND w.kind = 'turn' ORDER BY w.started_at DESC, w.wakeup_id DESC LIMIT 1`; const prior = Option.getOrUndefined(decodeStamp(previous?.stamp)); const cursor = @@ -342,38 +350,53 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( SELECT 1 FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} AND run_id = ${wakeup.runId} AND provider_thread_id = ${previous.providerThreadId} LIMIT 1`; + // Provider run history can still identify a member whose carry stamp was never recorded. const history = - previous === undefined || prior === undefined + previous === undefined || (prior === undefined && previous.providerThreadId === null) ? [] : yield* sql<{ wakeupId: KinWakeupId; lastRequest: number | null; + lastRequestKin: number | null; contextTokens: number | null; draft: number; compactedAfterPrevious: number; }>` SELECT w.wakeup_id AS "wakeupId", w.last_request_at AS "lastRequest", + CASE WHEN json_extract(w.carry_json, '$.ageClock') = 2 + AND json_type(w.carry_json, '$.lastRequestKinAt') IN ('integer', 'real') + THEN json_extract(w.carry_json, '$.lastRequestKinAt') END AS "lastRequestKin", w.context_tokens AS "contextTokens", CASE WHEN w.kind = 'upkeep' AND (w.started_at, w.wakeup_id) > (${previous.startedAt}, ${previous.wakeupId}) AND json_extract(w.carry_json, '$.compacted') = 1 THEN 1 ELSE 0 END AS "compactedAfterPrevious", - EXISTS (SELECT 1 FROM kin_events e WHERE e.org_id = w.org_id AND e.agent_id = w.agent_id - AND e.wakeup_id = w.wakeup_id AND json_type(e.json, '$.subject.approved') IS NOT NULL) AS draft + CASE WHEN json_extract(w.carry_json, '$.approvedDraft') = 1 + OR EXISTS (SELECT 1 FROM kin_events e WHERE e.org_id = w.org_id AND e.agent_id = w.agent_id + AND e.wakeup_id = w.wakeup_id AND json_type(e.json, '$.subject.approved') IS NOT NULL) + THEN 1 ELSE 0 END AS draft FROM kin_wakeups w + LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = w.run_id AND r.thread_id = w.thread_id WHERE w.org_id = ${orgId} AND w.agent_id = ${agentId} AND w.thread_id = ${threadId} AND w.wakeup_id <> ${wakeupId} - AND json_extract(w.carry_json, '$.sessionStart') = ${prior.sessionStart} + AND (json_extract(w.carry_json, '$.sessionStart') = ${sessionStart ?? null} + OR r.provider_thread_id = ${previous.providerThreadId}) ORDER BY w.last_request_at DESC NULLS LAST, w.started_at DESC, w.wakeup_id DESC LIMIT ${SESSION_HISTORY_LIMIT + 1}`; - let marked = false; - for (const member of [...history, { wakeupId, draft: 0 }]) { - if (member.draft === 1 || (yield* outsideRead({ orgId, wakeupId: member.wakeupId }))) { - marked = true; + let markSource: "earlier_outside" | "approved_draft" | undefined; + for (const member of history) { + if (member.draft === 1) { + markSource = "approved_draft"; + break; + } + if (yield* outsideRead({ orgId, wakeupId: member.wakeupId })) { + markSource = "earlier_outside"; break; } } const [approved] = yield* sql`SELECT 1 FROM kin_events WHERE org_id = ${orgId} AND agent_id = ${agentId} AND wakeup_id = ${wakeupId} AND json_type(json, '$.subject.approved') IS NOT NULL LIMIT 1`; + const approvedDraft = approved !== undefined; + if (approvedDraft) markSource = "approved_draft"; const [foreign] = previous?.providerThreadId == null ? [] @@ -385,7 +408,9 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( AND w.thread_id = r.thread_id AND w.run_id = r.run_id AND w.wakeup_id <> ${wakeupId}) LIMIT 1`; const last = history[0]; - const gapMs = last?.lastRequest == null ? null : input.now - last.lastRequest; + const gapMs = last?.lastRequest == null ? null : input.wallNow - last.lastRequest; + const companyGapMs = + prior?.ageClock !== 2 || last?.lastRequestKin == null ? null : input.now - last.lastRequestKin; const facts = { enabled: input.enabled, provider: input.driver, @@ -400,12 +425,13 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( previous.providerThreadId !== null && sessionStart !== undefined && history.some((member) => member.wakeupId === sessionStart), - marked: marked || approved !== undefined, + marked: markSource !== undefined, foreignRun: foreign !== undefined || history.length > SESSION_HISTORY_LIMIT || (wakeup.runId != null && adoptedInSession === undefined), gapMs, + companyGapMs, contextTokens: last?.contextTokens ?? null, ...(input.compactAtTokens === undefined ? {} : { compactAtTokens: input.compactAtTokens }), compactedSince: @@ -434,6 +460,8 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( } satisfies CarryFacts; return { facts, + approvedDraft, + markSource, fingerprint, sessionStart: adoptedInSession === undefined ? wakeupId : (sessionStart ?? wakeupId), carriedFrom: sessionStart ?? null, diff --git a/packages/contracts/src/settings.kin.test.ts b/packages/contracts/src/settings.kin.test.ts index 32a1410d5db0..c42e0533df17 100644 --- a/packages/contracts/src/settings.kin.test.ts +++ b/packages/contracts/src/settings.kin.test.ts @@ -7,9 +7,17 @@ const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings); const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch); const encodeServerSettings = Schema.encodeSync(ServerSettings); -it("defaults session carry and upkeep off and accepts bounded compaction patches", () => { +it("kinSessionCarry is on when settings leave it out", () => { + expect(decodeServerSettings({}).kinSessionCarry).toBe(true); +}); + +it("an explicit false stays off", () => { + const saved = encodeServerSettings(decodeServerSettings({ kinSessionCarry: false })); + expect(decodeServerSettings(saved).kinSessionCarry).toBe(false); +}); + +it("defaults upkeep off and accepts bounded compaction patches", () => { expect(decodeServerSettings({})).toMatchObject({ - kinSessionCarry: false, kinSessionUpkeep: false, kinSessionCompactAtTokens: 500_000, }); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index aecb7b3ee947..ae807e9ed88e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1417,7 +1417,7 @@ export const ServerSettings = Schema.Struct({ kinTriggerSendOnly: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), /** Kin: a turn's progress updates leave the chat once its reply is posted; nothing is deleted. */ kinClearUpdatesAfterReply: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), - kinSessionCarry: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + kinSessionCarry: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), kinSessionUpkeep: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), kinSessionCompactAtTokens: KinSessionCompactAtTokens.pipe( Schema.withDecodingDefault(Effect.succeed(500_000)), diff --git a/verification/kin/discussion/README.md b/verification/kin/discussion/README.md index 78cef4202485..34337e1127b1 100644 --- a/verification/kin/discussion/README.md +++ b/verification/kin/discussion/README.md @@ -105,3 +105,5 @@ On 2026-11-26, against `feat/kin-session-changes` (`fc8c965117c`, on kin `4df1cc **Re-confirmed 2026-11-28** on `feat/kin-money-in-check` after its independent review, joined on kin `1fadc6799d1` (no spec change, all 13 rules hold over 44,410 states in 34 s; 16/16 variants caught in 27 s). The covered file it changes, `KinChatService.ts`, only adds the bank-check card to the types a generic widget upsert refuses, after kin's card-audience and reaction fixes; no discussion, ask, hand-off, room or check-in changes. **Re-confirmed 2026-11-28** on train 16 (the last Finance train, five steps joined on kin `db4a66e447d`; no spec change, all 13 rules hold over 44,410 states in 31 s; 16/16 variants caught in 25 s). The one covered file the line changes, `chat/KinChatService.ts`, differs from kin only by the money-in check (step 3): the bank-check card joins the types a generic widget upsert refuses. No discussion, ask, hand-off, room or check-in changes. + +**Re-confirmed 2026-11-29** for the cache carry policy and default (train 16 base `aa1104cd77b`; no spec change). All 13 rules hold over 44,410 states, and 16/16 broken variants are caught. The only covered file changed, `WakeupRunner.ts`, changes the provider context and cache age of an already-chosen owner-private wake, not who starts a discussion, the hand-off or its reply. diff --git a/verification/kin/reply/README.md b/verification/kin/reply/README.md index 7d43a7f13ad7..4ecc17f3558b 100644 --- a/verification/kin/reply/README.md +++ b/verification/kin/reply/README.md @@ -114,3 +114,5 @@ The guard "Steer waits after a Stop" (rule 12) now rests on code, from kin's `15 **Checked 2026-11-28** against Job T, `feat/kin-bills-fix-by-talking`. The change supplies the working-line labels for `bills_list`, `bill_set` and `bill_recut` in `reply/classify.ts`. The model tracks whether the line is visible through `LineClears`. **Re-confirmed 2026-11-28** on train 16 (the last Finance train, five steps joined on kin `db4a66e447d`; no spec change, all 17 rules hold over 1,554,826 states in 422 s; 28/28 variants caught in 40 s). The one covered file the line changes, `reply/classify.ts`, differs from kin only by bills fixed by talking (step 5, as its line above says): working-line labels for `bills_list`, `bill_set` and `bill_recut`. Every message still ends in a reply, a plain failure line or the person's own Stop. + +**Re-confirmed 2026-11-29** for the cache carry policy and default (train 16 base `aa1104cd77b`; no spec change). All 17 rules hold over 1,554,826 states, and 28/28 broken variants are caught. The only covered file changed, `WakeupRunner.ts`, changes when an owner-private wake can reuse a provider context. Audience checks, claim, reply, retry and Stop are unchanged; a released wake no longer lets carry look past it, even if its capture left no stamp. This model run does not verify what the provider can read in a T3-started continuation. From 6e7fd5839561a79576e83c52ad8b5d861e1f7dfb Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:24:31 +0530 Subject: [PATCH 2/3] fix(kin): a carried session lasts 49 minutes, from the measured cache lifetime A carried conversation was still fully read from the provider's cache after 54.8 idle minutes in real time. The limit is that gap minus five minutes. People-change: the owner's private chat with a lead keeps its session for up to 49 idle minutes instead of 30, so more turns are cheap ones. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/kin/lead/sessionCarry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/kin/lead/sessionCarry.ts b/apps/server/src/kin/lead/sessionCarry.ts index 9e6949bef43a..7073cab418d6 100644 --- a/apps/server/src/kin/lead/sessionCarry.ts +++ b/apps/server/src/kin/lead/sessionCarry.ts @@ -54,7 +54,7 @@ export interface CarryFacts { } // Queue 80: the longest gap with at least 97.5% cache reads, minus five minutes, capped at 55. -export const CARRY_LIFETIME_MS = 30 * 60_000; +export const CARRY_LIFETIME_MS = 49 * 60_000; const CARRY_INDEX_LINES = 40; const expired = (gap: number | null) => From 64212aac050a04ae597e63ea51e317908cfe5165 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:31:42 +0530 Subject: [PATCH 3/3] test(kin): three attack tests on a carried mail wake The independent review of the carry policy wrote three adversarial tests against the reviewed head. They pass on the joined line: - a mail wake released and retried twice still ends its session; - a session past the history bound starts fresh when its mail wake lies beyond it; - a finished task that lands in a session a mail wake continued runs outside-read and ends it. People-change: none Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/WakeupRunner.test.ts | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 4e91ccda9ddd..5359731647c4 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -2729,6 +2729,156 @@ describe("WakeupRunner", () => { }).pipe(Effect.provide(carryHarness()), provideDeterministicTestRuntime), ); + it.effect("a mail wake released and retried twice still ends its session", () => { + let database: SqlClient.SqlClient | undefined; + // As the prompt does (`LeadPrompt.build`): a claimed event's outside stamp marks its wake. + const prepare: Memory.Memory["Service"]["prepareWakeup"] = (org, wakeupId) => + Effect.gen(function* () { + if (database !== undefined && wakeupId !== undefined) { + const claimed = yield* database<{ eventId: string }>`SELECT event_id AS "eventId" + FROM kin_events WHERE org_id = ${org} AND wakeup_id = ${wakeupId}`; + yield* inheritOutside({ + orgId: org, + wakeupId, + eventIds: claimed.map((row) => row.eventId), + }).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* wake("tidewater-first"); + yield* wake("tidewater-mail"); + const [, mail] = yield* carryRows; + assert.strictEqual(mail?.sent, "carried"); + yield* markOutside({ orgId, wakeupId: mail!.wakeupId }, "check-in"); + const retry = Effect.gen(function* () { + const last = (yield* carryRows).at(-1)!; + yield* sql`UPDATE kin_wakeups SET status = 'released' WHERE wakeup_id = ${last.wakeupId}`; + yield* sql`UPDATE kin_events SET state = 'queued', wakeup_id = NULL, attempts = 1, + not_before = NULL, replied_at = NULL + WHERE org_id = ${orgId} AND event_id = 'tidewater-mail'`; + yield* Fiber.join(yield* run()); + return (yield* carryRows).at(-1)!; + }); + for (const attempt of [yield* retry, yield* retry]) { + assert.include(attempt, { sent: "fresh", reason: "marked", markSource: "earlier_outside" }); + assert.isTrue(yield* outsideRead({ orgId, wakeupId: attempt.wakeupId })); + } + yield* wake("tidewater-clean"); + yield* wake("tidewater-follow-up"); + const [clean, followUp] = (yield* carryRows).slice(-2); + assert.include(clean, { sent: "fresh", reason: "marked", markSource: "earlier_outside" }); + assert.include(followUp, { sent: "carried", reason: null }); + assert.deepStrictEqual(yield* sessions(), [1, 1, 2, 3, 4, 4]); + }).pipe(Effect.provide(carryHarness({ prepare })), provideDeterministicTestRuntime); + }); + + it.effect("a session past the history bound starts fresh when its mail wake lies beyond it", () => + Effect.gen(function* () { + const sql = yield* seedCarry; + yield* wake("tidewater-first"); + yield* wake("tidewater-mail"); + const [first, mail] = yield* carryRows; + yield* markOutside({ orgId, wakeupId: mail!.wakeupId }, "check-in"); + // The mail wake becomes the session's oldest member and the clean first wake its latest. + yield* sql`UPDATE kin_wakeups SET started_at = started_at - 1000000, last_request_at = 1 + WHERE wakeup_id = ${mail!.wakeupId}`; + yield* sql`WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000) + INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, + event_ids, kind, carry_json, last_request_at, last_request_kin_at) + SELECT 'bound-' || i, w.org_id, w.agent_id, w.thread_id, w.model, w.started_at - 1000 - i, + 'completed', '[]', 'upkeep', w.carry_json, 1 + i, 1 + i + FROM kin_wakeups w, n WHERE w.wakeup_id = ${first!.wakeupId}`; + yield* wake("tidewater-next"); + const next = (yield* carryRows).at(-1)!; + assert.include(next, { sent: "fresh", reason: "foreign_run" }); + assert.deepStrictEqual(yield* sessions(), [1, 1, 2]); + }).pipe(Effect.provide(carryHarness()), provideDeterministicTestRuntime), + ); + + it.effect( + "a finished task that lands in a session a mail wake continued runs outside-read and ends it", + () => + Effect.gen(function* () { + const held = yield* Deferred.make(); + let show = false; + let database: SqlClient.SqlClient | undefined; + const prepare: Memory.Memory["Service"]["prepareWakeup"] = (org, wakeupId) => + Effect.gen(function* () { + if (show && wakeupId !== undefined && database !== undefined) + yield* markOutside({ orgId: org, wakeupId }, "check-in").pipe( + Effect.provideService(SqlClient.SqlClient, database), + ); + return { head: "abc", indexAsOf: DateTime.makeUnsafe(0), read: "/private/tmp" }; + }).pipe(Effect.orDie); + yield* Effect.gen(function* () { + const sql = yield* seedCarry; + database = sql; + yield* wake("tidewater-first"); + const [asked] = yield* carryRows; + yield* sql`INSERT INTO kin_wakeup_sensitive_reads (org_id, wakeup_id, read_at) + VALUES (${orgId}, ${asked!.wakeupId}, 1)`; + const first = yield* carryProjection; + const task = yield* taskNotice(first.thread.id, first.runs[0]!, "tidewater"); + show = true; + yield* wake("tidewater-mail"); + show = false; + const [clean, mail] = yield* carryRows; + assert.include(mail, { sent: "carried", reason: null }); + assert.isTrue(yield* outsideRead({ orgId, wakeupId: mail!.wakeupId })); + const { run: notice, message } = yield* task.dispatch; + assert.strictEqual(notice.providerThreadId, first.runs[0]!.providerThreadId); + yield* (yield* TaskWake.make).enqueue(message); + const threads = yield* ThreadManagement.ThreadManagementService; + yield* threads + .streamStoredEventsFrom({ + threadId: first.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 active = yield* run(); + const [claim] = yield* sql<{ wakeupId: KinWakeupId }>`SELECT wakeup_id AS "wakeupId" + FROM kin_wakeups WHERE status = 'running' AND run_id = ${notice.id}`; + assert.isDefined(claim); + assert.isTrue(yield* outsideRead({ orgId, wakeupId: claim!.wakeupId })); + assert.isTrue(yield* turnSensitive(orgId, claim!.wakeupId)); + assert.strictEqual(yield* fullSessionRefusal(first.thread.id), SESSION_REFUSAL.outside); + yield* Deferred.succeed(held, undefined); + yield* Fiber.join(active); + const continued = (yield* carryRows).at(-1)!; + assert.strictEqual(continued.wakeupId, claim!.wakeupId); + const stamps = yield* sql<{ wakeupId: string; sessionStart: string }>` + SELECT wakeup_id AS "wakeupId", json_extract(carry_json, '$.sessionStart') AS "sessionStart" + FROM kin_wakeups WHERE wakeup_id IN (${clean!.wakeupId}, ${continued.wakeupId})`; + assert.strictEqual(new Set(stamps.map((row) => row.sessionStart)).size, 1); + yield* wake("tidewater-after"); + const after = (yield* carryRows).at(-1)!; + assert.include(after, { sent: "fresh", reason: "marked", markSource: "earlier_outside" }); + assert.isFalse(yield* outsideRead({ orgId, wakeupId: after.wakeupId })); + assert.deepStrictEqual(yield* sessions(), [1, 1, 1, 2]); + }).pipe( + Effect.provide( + carryHarness({ + prepare, + holdRunning: (ordinal) => (ordinal === 3 ? held : undefined), + }), + ), + ); + }).pipe(provideDeterministicTestRuntime), + ); + it.effect("a change list over 9,000 characters goes inside the message", () => Effect.gen(function* () { yield* seedCarry;