diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 86aa91aa1cd1..5359731647c4 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -457,22 +457,6 @@ const readCarryHook = (threadId: ThreadId) => { Effect.orDie, ); }; -type CacheWeights = { - input: number; - read: number; - write5m: number; - write1h: number; - output: number; -}; -// The shape `cacheWeights` in `provider.ts` returns. -const pricing = vi.hoisted(() => ({ - cacheWeights: (_driver: string, _model: string): CacheWeights | undefined => undefined, -})); -vi.mock("./turn/providers/provider.ts", async (importOriginal) => ({ - ...(await importOriginal()), - cacheWeights: (driver: string, model: string) => pricing.cacheWeights(driver, model), -})); - const carryServices = (boot = "fixture-boot") => Layer.mergeAll( KinSessionContext.layer, @@ -2048,7 +2032,7 @@ describe("WakeupRunner", () => { Effect.provide( WakeupRunner.layer.pipe( Layer.provide(rejectBad), - Layer.provideMerge(orchestrationHarness()), + Layer.provideMerge(orchestrationHarness({ settings: { kinSessionCarry: false } })), Layer.provide(bridge), ), ), @@ -2596,6 +2580,305 @@ 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.each(["missing company time", "old stamp"] as const)( + "a session stamped before K244 starts fresh once (%s)", + (legacy) => + Effect.gen(function* () { + const sql = yield* seedCarry; + yield* wake("tidewater-old"); + const [old] = yield* carryRows; + if (legacy === "missing company time") + yield* sql`UPDATE kin_wakeups SET last_request_kin_at = NULL WHERE wakeup_id = ${old!.wakeupId}`; + else + yield* sql`UPDATE kin_wakeups SET carry_json = json_remove(carry_json, '$.ageClock') + 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 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; @@ -2863,73 +3146,6 @@ describe("WakeupRunner", () => { ), ); - it.effect("a carried session that costs more than a fresh start starts fresh", () => - Effect.gen(function* () { - using mockWeights = vi.spyOn(pricing, "cacheWeights").mockReturnValue(undefined); - const sql = yield* seedCarry; - yield* wake("tidewater-fresh"); - yield* wake("tidewater-carried"); - const [first, carried] = yield* carryRows; - assert.strictEqual(carried?.sent, "carried"); - const usage = (inputTokens: number, cachedInputTokens: number, cacheCreationTokens = 0) => - JSON.stringify([ - { - providerTurnId: "fixture", - turnTokenUsage: { - usageScope: "main_agent", - usageStatus: "complete", - hasSubagents: false, - inputTokens, - cachedInputTokens, - cacheCreationTokens, - outputTokens: 0, - }, - }, - ]); - const carriedUsage = usage(1_000, 1_000); - yield* sql`UPDATE kin_wakeups SET tokens_json = ${carriedUsage} WHERE wakeup_id = ${carried!.wakeupId}`; - const [stored] = yield* sql<{ stamp: string; fingerprint: string; started: number }>` - SELECT carry_json AS stamp, standing_key AS fingerprint, started_at AS started - FROM kin_wakeups WHERE wakeup_id = ${first!.wakeupId}`; - for (const [offset, tokens] of [ - [5, usage(100, 85, 15)], - [4, usage(100, 90, 10)], - [3, usage(5_000, 4_500, 500)], - [2, usage(20_000, 0)], - [1, usage(20_000, 0)], - ] as const) { - yield* sql`INSERT INTO kin_wakeups - (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids, - carry_json, standing_key, tokens_json) - VALUES (${"cost-fixture-" + offset}, ${orgId}, ${agentId}, ${first!.threadId}, - ${selection.model}, ${stored!.started - offset}, 'completed', '[]', - json_set(${stored!.stamp}, '$.sessionStart', ${"cost-fixture-" + offset}), - ${stored!.fingerprint}, ${tokens})`; - } - yield* wake("tidewater-unknown-weight"); - const unknown = (yield* carryRows).at(-1)!; - assert.strictEqual(unknown.sent, "carried"); - yield* sql`UPDATE kin_wakeups SET tokens_json = ${carriedUsage} WHERE wakeup_id = ${unknown.wakeupId}`; - mockWeights.mockImplementation((driver) => - driver === "claudeAgent" - ? { input: 1, read: 0.25, write5m: 1.25, write1h: 2, output: 3 } - : undefined, - ); - yield* wake("tidewater-reprice"); - assert.include((yield* carryRows).at(-1), { reason: "cost", sent: "fresh" }); - assert.isTrue(carriedSend(yield* carryProjection).run.freshContext); - yield* wake("tidewater-shorter-session"); - assert.include((yield* carryRows).at(-1), { reason: null, sent: "carried" }); - }).pipe( - Effect.provide( - carryHarness({ - beforeTurn: ({ threadId }) => readCarryHook(threadId).pipe(Effect.asVoid), - }), - ), - provideDeterministicTestRuntime, - ), - ); - it.effect("a timed-out turn that skips capture cannot leave a delta for a fresh turn", () => { let timeout = false; const reads: string[] = []; @@ -2978,44 +3194,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, @@ -3024,40 +3238,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", @@ -3399,9 +3612,9 @@ describe("WakeupRunner", () => { yield* sql`UPDATE kin_wakeups SET carry_json = json_set(carry_json, '$.sessionStart', ${started.sessionStart}) WHERE wakeup_id = ${second!.wakeup_id}`; 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) + (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids, kind, carry_json, last_request_at, last_request_kin_at, context_tokens) VALUES ('shadow-refresh', ${orgId}, ${agentId}, ${second!.thread_id}, ${selection.model}, ${refreshAt}, - 'completed', '[]', 'upkeep', ${first!.carry_json}, ${refreshAt}, 120)`; + 'completed', '[]', 'upkeep', ${first!.carry_json}, ${refreshAt}, ${refreshAt}, 120)`; const compare = carryFacts( { orgId, agentId, wakeupId: KinWakeupId.make("candidate") }, { @@ -3414,14 +3627,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, refreshed.facts.gapMs); + 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) @@ -3441,6 +3654,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 6a7dedbc9a29..8229aaf5f1ad 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -164,7 +164,6 @@ import { KinAgentSessions } from "../mcp/KinAgentSessions.ts"; import { captureChatCursor, readCursor, sessionChanges, type Cursor } from "./sessionChanges.ts"; import { KinSessionContext, type SessionSnapshot } from "./turn/sessionContext.ts"; import { claude } from "./turn/providers/claude.ts"; -import * as cachePricing from "./turn/providers/provider.ts"; import { KinWorkspace } from "../gendocs/workspace.ts"; import { KinBoot, carryFacts, decideCarry, ulid, type PromptFingerprint } from "./sessionCarry.ts"; import { closeQuietRunCards, postQuietRunCard } from "./quietRunCard.ts"; @@ -871,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; @@ -2379,14 +2378,6 @@ const make = Effect.gen(function* () { const ownerClaude = alone && confined === undefined && driver === claude.driver; const send = yield* Effect.gen(function* () { const toolListSha = agentSessions?.lastToolList(threadId) ?? null; - const weights = ownerClaude - ? cachePricing.cacheWeights(claude.driver, modelSelection.model) - : undefined; - // The owner seat writes its prompt cache for an hour. - const cacheWeights = - weights === undefined - ? undefined - : { read: weights.read, write: weights.write1h, output: weights.output }; const factsEffect = carryFacts(row, { threadId, ownerThread: alone && confined === undefined, @@ -2403,7 +2394,6 @@ const make = Effect.gen(function* () { prompt: promptFingerprint, enabled: hostSettings.kinSessionCarry, ...(yield* carryClocks), - ...(cacheWeights === undefined ? {} : { cacheWeights }), stopRevision: refreshHub?.stopRevision(orgId) ?? 0, compactAtTokens: hostSettings.kinSessionCompactAtTokens, }); @@ -2487,6 +2477,7 @@ const make = Effect.gen(function* () { ageClock: 2, companyGapMs: facts.facts.companyGapMs, ...facts.diagnostics, + ...(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 85d90bf3a546..2bf73c83a845 100644 --- a/apps/server/src/kin/lead/sessionCarry.test.ts +++ b/apps/server/src/kin/lead/sessionCarry.test.ts @@ -5,7 +5,13 @@ import * as SqlClient from "effect/sql/SqlClient"; import { it as effectIt } from "@effect/vitest"; import { describe, expect, it } from "vite-plus/test"; -import { type CarryFacts, carryFacts, decideCarry, fingerprintPrompt } from "./sessionCarry.ts"; +import { + CARRY_LIFETIME_MS, + type CarryFacts, + carryFacts, + decideCarry, + fingerprintPrompt, +} from "./sessionCarry.ts"; import { agentId, harness, orgId, seedCarry, selection, wake } from "./WakeupRunner.testkit.ts"; import { provideDeterministicTestRuntime } from "../../orchestration-v2/testkit/DeterministicRuntime.ts"; @@ -17,8 +23,8 @@ const clean: CarryFacts = { previousCompleted: true, marked: false, foreignRun: false, - gapMs: 55 * 60_000, - companyGapMs: 55 * 60_000, + gapMs: CARRY_LIFETIME_MS, + companyGapMs: CARRY_LIFETIME_MS, sameBoot: true, sameModel: true, sameInstructions: true, @@ -41,14 +47,13 @@ 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, companyGapMs: 1_000, sameBoot: false }], - ["expired", { companyGapMs: 55 * 60_000 + 1, gapMs: 1_000 }], + ["expired", { gapMs: CARRY_LIFETIME_MS + 1, companyGapMs: 1_000, sameBoot: false }], + ["expired", { companyGapMs: CARRY_LIFETIME_MS + 1, gapMs: 1_000 }], ["expired", { companyGapMs: -1 }], ["expired", { companyGapMs: null }], - ["cost", { carriedCost: 101, freshCost: 100, sameBoot: false }], ["boot", { sameBoot: false, sameModel: false }], ["model", { sameModel: false, sameInstructions: false }], ["instructions", { sameInstructions: false, sameToolList: false }], @@ -67,8 +72,37 @@ 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, carriedCost: 100, freshCost: 100 })).toEqual({ carry: true }); + expect(decideCarry(clean)).toEqual({ carry: true }); }); }); @@ -93,8 +127,6 @@ effectIt.effect("size wins over boot and accepts the inclusive limit", () => decideCarry({ ...atLimit, contextTokens: 100_001, - carriedCost: 110, - freshCost: 100, sameBoot: false, }), ).toEqual({ @@ -153,19 +185,20 @@ effectIt.effect("names the lane, mark source and ending behind a refusal", () => const marked = yield* compare; expect(marked.diagnostics).toEqual({ lane: "owner", - markSource: "this_wake", + markSource: undefined, endedDetail: undefined, }); - expect(marked.facts.marked).toBe(true); + expect(marked.facts.marked).toBe(false); yield* sql`UPDATE kin_events SET json = json_set(json, '$.subject', json('{"approved":true}')) WHERE org_id = ${orgId} AND wakeup_id = ${prior!.wakeupId}`; expect((yield* compare).diagnostics.markSource).toBe("approved_draft"); yield* sql`UPDATE kin_wakeups SET status = 'failed' WHERE wakeup_id = ${prior!.wakeupId}`; const failed = yield* compare; expect(failed.diagnostics.endedDetail).toBe("failed"); + expect(failed.diagnostics.markSource).toBe("approved_draft"); expect(decideCarry({ ...failed.facts, enabled: true })).toEqual({ carry: false, - reason: "ended", + reason: "marked", }); yield* sql`UPDATE kin_wakeups SET status = 'completed', carry_json = json_set(carry_json, '$.sessionStart', 'missing-session') diff --git a/apps/server/src/kin/lead/sessionCarry.ts b/apps/server/src/kin/lead/sessionCarry.ts index 69d2e125c9b9..7073cab418d6 100644 --- a/apps/server/src/kin/lead/sessionCarry.ts +++ b/apps/server/src/kin/lead/sessionCarry.ts @@ -2,7 +2,6 @@ import * as NodeCrypto from "node:crypto"; import { KinWakeupId, - TurnTokenUsage, type KinAgentId, type KinOrgId, type ModelSelection, @@ -35,8 +34,6 @@ export interface CarryFacts { readonly foreignRun: boolean; readonly gapMs: number | null; readonly companyGapMs: number | null; - readonly carriedCost?: number; - readonly freshCost?: number; readonly contextTokens?: number | null; readonly compactAtTokens?: number; readonly compactedSince?: boolean; @@ -56,7 +53,8 @@ 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 = 49 * 60_000; const CARRY_INDEX_LINES = 40; const expired = (gap: number | null) => @@ -71,10 +69,10 @@ 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" : expired(facts.gapMs) || expired(facts.companyGapMs) @@ -83,39 +81,35 @@ export function decideCarry(facts: CarryFacts) { facts.compactAtTokens !== undefined && facts.contextTokens > facts.compactAtTokens ? "size" - : facts.carriedCost !== undefined && - facts.freshCost !== undefined && - facts.carriedCost > facts.freshCost - ? "cost" - : !facts.sameBoot - ? "boot" - : !facts.sameModel - ? "model" - : !facts.sameInstructions - ? "instructions" - : !facts.sameToolList - ? "tool_list" - : !facts.sameLead - ? "lead" - : !facts.sameMembers - ? "members" - : !facts.sameLists - ? "lists" - : !facts.sameBudgets - ? "budgets" - : !facts.sameRecipes - ? "recipes" - : !facts.sameZone - ? "zone" - : facts.paused - ? "paused" - : !facts.sameStanding - ? "standing" - : facts.indexLinesChanged > CARRY_INDEX_LINES - ? "index" - : facts.missed - ? "missed" - : undefined; + : !facts.sameBoot + ? "boot" + : !facts.sameModel + ? "model" + : !facts.sameInstructions + ? "instructions" + : !facts.sameToolList + ? "tool_list" + : !facts.sameLead + ? "lead" + : !facts.sameMembers + ? "members" + : !facts.sameLists + ? "lists" + : !facts.sameBudgets + ? "budgets" + : !facts.sameRecipes + ? "recipes" + : !facts.sameZone + ? "zone" + : facts.paused + ? "paused" + : !facts.sameStanding + ? "standing" + : facts.indexLinesChanged > CARRY_INDEX_LINES + ? "index" + : facts.missed + ? "missed" + : undefined; if (reason !== undefined) return { carry: false as const, reason }; return facts.compactedSince ? { carry: true as const, refill: true as const } @@ -159,6 +153,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), @@ -245,95 +240,6 @@ const recipeFingerprint = Effect.fn("KinSessionCarry.recipeFingerprint")(functio : fingerprintJson([catalog.value, defaults, labels, baselines]); }); -type CacheWeights = { readonly read: number; readonly write: number; readonly output: number }; - -const decodeWakeUsage = Schema.decodeUnknownOption( - Schema.fromJsonString( - Schema.Array( - Schema.Struct({ - providerTurnId: Schema.String, - turnTokenUsage: Schema.optional(TurnTokenUsage), - }), - ), - ), -); - -function estimateCost(tokensJson: string | null, weights: CacheWeights) { - const usage = Option.getOrUndefined(decodeWakeUsage(tokensJson)); - if (usage === undefined) return undefined; - let input = 0; - let read = 0; - let cost = 0; - const seen = new Set(); - for (const { providerTurnId, turnTokenUsage: ledger } of usage) { - if (seen.has(providerTurnId)) continue; - seen.add(providerTurnId); - if (ledger?.localCommand === true) continue; - if (ledger?.usageStatus !== "complete") return undefined; - const cached = ledger.cachedInputTokens ?? 0; - const written = ledger.cacheCreationTokens ?? 0; - const uncached = ledger.inputTokens - cached - written; - if (uncached < 0) return undefined; - const other = ledger.otherUsage; - input += ledger.inputTokens + (other?.inputTokens ?? 0); - read += cached; - cost += - uncached + - (other?.inputTokens ?? 0) + - cached * weights.read + - written * weights.write + - (ledger.outputTokens + (other?.outputTokens ?? 0)) * weights.output; - } - return input > 0 && Number.isFinite(cost) ? { cost, warm: read >= input * 0.85 } : undefined; -} - -const laneCosts = Effect.fn("KinSessionCarry.laneCosts")(function* ( - wakeup: Wakeup, - threadId: ThreadId, - chat: string, - model: string, - sessionStart: KinWakeupId, - weights: CacheWeights, -) { - const sql = yield* SqlClient.SqlClient; - const completedHere = sql`org_id = ${wakeup.orgId} AND agent_id = ${wakeup.agentId} - AND thread_id = ${threadId} AND wakeup_id <> ${wakeup.wakeupId} - AND kind = 'turn' AND status = 'completed' - AND json_extract(standing_key, '$.chat') = ${chat} - AND json_extract(standing_key, '$.model') = ${model}`; - // A fresh start discards the prefix whose cost forced the reset. - const [carried] = yield* sql<{ tokensJson: string | null }>`SELECT tokens_json AS "tokensJson" - FROM kin_wakeups WHERE ${completedHere} AND json_extract(carry_json, '$.sent') = 'carried' - AND json_extract(carry_json, '$.sessionStart') = ${sessionStart} - ORDER BY started_at DESC, wakeup_id DESC LIMIT 1`; - const carriedCost = - carried === undefined ? undefined : estimateCost(carried.tokensJson, weights)?.cost; - if (carriedCost === undefined) return {}; - const fresh: number[] = []; - type Sample = { - readonly tokensJson: string; - readonly startedAt: number; - readonly wakeupId: string; - }; - let before: Sample | undefined; - while (fresh.length < 3) { - const page: ReadonlyArray = yield* sql` - SELECT tokens_json AS "tokensJson", started_at AS "startedAt", wakeup_id AS "wakeupId" - FROM kin_wakeups WHERE ${completedHere} AND json_extract(carry_json, '$.sent') = 'fresh' - AND tokens_json IS NOT NULL - ${before === undefined ? sql`` : sql`AND (started_at, wakeup_id) < (${before.startedAt}, ${before.wakeupId})`} - ORDER BY started_at DESC, wakeup_id DESC LIMIT 32`; - if (page.length === 0) break; - for (const row of page) { - const sample = estimateCost(row.tokensJson, weights); - if (sample?.warm) fresh.push(sample.cost); - if (fresh.length === 3) return { carriedCost, freshCost: fresh.sort((a, b) => a - b)[1]! }; - } - before = page.at(-1); - } - return { carriedCost }; -}); - export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( wakeup: Wakeup, input: { @@ -348,7 +254,6 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( readonly enabled: boolean; readonly now: number; readonly wallNow: number; - readonly cacheWeights?: CacheWeights; readonly stopRevision: number; readonly compactAtTokens?: number; }, @@ -405,6 +310,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; @@ -414,18 +320,20 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( fingerprint: string | null; promptIndex: string | null; providerThreadId: string | null; + aborted: number; ended: number; }>` 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", + 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 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 = @@ -447,8 +355,9 @@ 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; @@ -463,31 +372,34 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( 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; - let markSource: "this_wake" | "earlier_outside" | "approved_draft" | undefined; - for (const member of [...history, { wakeupId, draft: 0 }]) { - if (member.draft === 1 || (yield* outsideRead({ orgId, wakeupId: member.wakeupId }))) { - marked = true; - markSource = - member.draft === 1 - ? "approved_draft" - : member.wakeupId === wakeupId - ? "this_wake" - : "earlier_outside"; + 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 ? [] @@ -500,7 +412,8 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( LIMIT 1`; const last = history[0]; const gapMs = last?.lastRequest == null ? null : input.wallNow - last.lastRequest; - const companyGapMs = last?.lastRequestKin == null ? gapMs : input.now - last.lastRequestKin; + const companyGapMs = + prior?.ageClock !== 2 || last?.lastRequestKin == null ? null : input.now - last.lastRequestKin; const ownerThread = input.ownerThread && threadId.startsWith("kin:"); const lane = threadId.startsWith(TRIAGE_THREAD_PREFIX) ? "triage" @@ -520,34 +433,23 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( const endedDetail = previous === undefined ? "no_stamp" - : previous.status === "interrupted" - ? "stopped" - : previous.status !== "completed" - ? "failed" - : previous.ended !== 0 - ? "thread_ended" - : previous.providerThreadId === null - ? "no_provider_thread" - : prior === undefined - ? "no_stamp" - : !sessionExists - ? "session_missing" - : undefined; - const costs = - ownerThread && - chat !== null && - chat === lead?.ownerChat && - sessionStart !== undefined && - input.cacheWeights !== undefined - ? yield* laneCosts( - wakeup, - threadId, - chat, - fingerprint.model, - sessionStart, - input.cacheWeights, - ) - : {}; + : previous.aborted === 1 + ? "aborted" + : previous.status === "released" + ? "released" + : previous.status === "interrupted" + ? "stopped" + : previous.status !== "completed" + ? "failed" + : previous.ended !== 0 + ? "thread_ended" + : previous.providerThreadId === null + ? "no_provider_thread" + : prior === undefined + ? "no_stamp" + : !sessionExists + ? "session_missing" + : undefined; const facts = { enabled: input.enabled, provider: input.driver, @@ -558,17 +460,17 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( (priorFingerprint === undefined || chat === priorFingerprint.chat), previousCompleted: previous?.status === "completed" && + previous.aborted === 0 && previous.ended === 0 && previous.providerThreadId !== null && sessionExists, - marked: marked || approved !== undefined, + marked: markSource !== undefined, foreignRun: foreign !== undefined || history.length > SESSION_HISTORY_LIMIT || (wakeup.runId != null && adoptedInSession === undefined), gapMs, companyGapMs, - ...costs, contextTokens: last?.contextTokens ?? null, ...(input.compactAtTokens === undefined ? {} : { compactAtTokens: input.compactAtTokens }), compactedSince: @@ -597,9 +499,10 @@ export const carryFacts = Effect.fn("KinSessionCarry.facts")(function* ( } satisfies CarryFacts; return { facts, + approvedDraft, diagnostics: { lane, - markSource: approved === undefined ? markSource : "approved_draft", + markSource, endedDetail, }, fingerprint, diff --git a/apps/server/src/kin/lead/turn/providers/claude.test.ts b/apps/server/src/kin/lead/turn/providers/claude.test.ts index ee2eccdb376e..8b6abf6d86f0 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.test.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.test.ts @@ -31,7 +31,6 @@ import { OWNER_SEAT_NO_SUBAGENTS, OWNER_SEAT_OFF, } from "./claude.ts"; -import { cacheWeights } from "./provider.ts"; import { captureClaudeOptions } from "./claude.testkit.ts"; import { BILLS_SEAT_INSTRUCTIONS, kinInstructions, REVIEW_SEAT_INSTRUCTIONS } from "../session.ts"; import { KinSessionContext } from "../sessionContext.ts"; @@ -239,23 +238,6 @@ it.effect("every seat's options match Kin byte for byte", () => ), ); -it("weights only priced Claude models, in units of plain input", () => { - const haiku = { input: 1, read: 0.1, write5m: 1.25, write1h: 2, output: 5 }; - const high = { ...haiku, read: 0.05 }; - for (const [driver, model, expected] of [ - ["claudeAgent", "claude-haiku-5-5", haiku], - ["claudeAgent", "claude-opus-5-5", high], - ["claudeAgent", "claude-sonnet-5-5", high], - ["claudeAgent", "claude-sonnet-4-6", undefined], - ["claudeAgent", "claude-haiku-5-5-custom", undefined], - ["codex", "claude-haiku-5-5", undefined], - ["acpRegistry", "claude-haiku-5-5", undefined], - ["unknown", "claude-haiku-5-5", undefined], - ] as const) { - expect(cacheWeights(driver, model), `${driver}/${model}`).toEqual(expected); - } -}); - it.effect("an enabled owner seat without KinSessionContext logs one error and still opens", () => { const errors: string[] = []; return withPreparedContext( diff --git a/apps/server/src/kin/lead/turn/providers/provider.ts b/apps/server/src/kin/lead/turn/providers/provider.ts index 60368ff170f0..74a099b0fea9 100644 --- a/apps/server/src/kin/lead/turn/providers/provider.ts +++ b/apps/server/src/kin/lead/turn/providers/provider.ts @@ -16,26 +16,3 @@ export interface KinProvider { readonly capabilities: Partial>>>; readonly install: (base: Layer.Layer) => Layer.Layer; } - -const claudeOpusAndSonnetWeights = { - input: 1, - read: 0.05, - write5m: 1.25, - write1h: 2, - output: 5, -} as const; -const claudeHaikuWeights = { ...claudeOpusAndSonnetWeights, read: 0.1 } as const; - -/** Relative token prices in units of plain input. Unpriced models have no cost comparison. */ -export const cacheWeights = (driver: string, model: string) => { - if (driver !== "claudeAgent") return undefined; - switch (model) { - case "claude-opus-5-5": - case "claude-sonnet-5-5": - return claudeOpusAndSonnetWeights; - case "claude-haiku-5-5": - return claudeHaikuWeights; - default: - return undefined; - } -}; 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 eee7a1db11d6..1f3253f55eb9 100644 --- a/verification/kin/discussion/README.md +++ b/verification/kin/discussion/README.md @@ -109,3 +109,5 @@ On 2026-11-26, against `feat/kin-session-changes` (`fc8c965117c`, on kin `4df1cc **Re-confirmed 2026-11-29** for the session carry clocks and cost gate (base `bc0259ac6be`; no spec change; all 13 rules hold over 44,410 states, 16/16 broken variants caught). `WakeupRunner` changes how it ages and prices an owner-only session, not who can join or speak, which thread a turn uses, what the Team room can read, or how `finishWakeup`, `wakeupEnded` and `reportBack` settle a turn. A Team-room turn still starts fresh and inherits no session marks. **Re-confirmed 2026-11-29** on train 16 of 29 Nov (the cache fixes and the Finance follow-through, five steps joined on kin `bc0259ac6be`; no spec change, all 13 rules hold over 44,410 states in 34 s; 16/16 variants caught in 23 s). The one covered file the line changes, `lead/WakeupRunner.ts`, differs from kin only by the carry clocks and cost gate (the line above), which now price with the turn provider's real `cacheWeights(driver, model)` table, so the shim that waited for it is gone. Pricing is asked only on the owner-only Claude path; a Team-room turn still starts fresh and inherits no session marks. + +**Re-confirmed 2026-11-29** for the cache carry policy and default (train 16 base `d35b52e265c`; spec and configuration unchanged from the run). 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 564145388b7d..4813f9253482 100644 --- a/verification/kin/reply/README.md +++ b/verification/kin/reply/README.md @@ -118,3 +118,5 @@ The guard "Steer waits after a Stop" (rule 12) now rests on code, from kin's `15 **Re-confirmed 2026-11-29** for the session carry clocks and cost gate (base `bc0259ac6be`; no spec change; all 17 rules hold over 1,554,826 states, 28/28 broken variants caught). `WakeupRunner` uses the previous provider completion to age a session and can start a fresh provider context when carry costs more. It still takes the same claim, audience, delivery, rescue, requeue and Stop paths; the extra wake-up stamp fields do not feed those paths. **Re-confirmed 2026-11-29** on train 16 of 29 Nov (the cache fixes and the Finance follow-through, five steps joined on kin `bc0259ac6be`; no spec change, all 17 rules hold over 1,554,826 states in 649 s; 28/28 variants caught in 46 s). The one covered file the line changes, `lead/WakeupRunner.ts`, differs from kin only by the carry clocks and cost gate (the line above), which now price with the turn provider's real `cacheWeights(driver, model)` table, so the shim that waited for it is gone. A carried session that costs more only starts fresh; it takes the same claim, audience, delivery, rescue, requeue and Stop paths. + +**Re-confirmed 2026-11-29** for the cache carry policy and default (train 16 base `d35b52e265c`; spec and configuration unchanged from the run). 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.