From 42574599bd64168faf4bca41750b1ed9c00f0eb8 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:29:28 -0500 Subject: [PATCH 1/3] fix(server): archiving a parent no longer kills a child's pending check-back A child thread that answered its parent and set a check-back (one that lives only in its Claude session) counted as settled, so archiving the parent archived the child too and stopped its session. The check-back died with it, and unarchiving brought back the thread but not the check-back. The rule the idle reaper uses to keep such a runtime now lives in @threadlines/shared/checkBacks (runtimeCheckBackOwed, holdsRuntimeCheckBack). The archive cascade (childArchivePlan) separates a child that holds one instead of archiving it, and the auto-archive sweeper leaves its parent alone, as it does a parent with a working child. Durable check-backs and ones long past their time don't count. childHasLiveWork is unchanged: its other callers (wrap, thread_wrap, stop targets, moves, alerts, late replies) mean "working now", and a check-back doesn't keep a thread out of Wrapped. --- .../Layers/ThreadAutoArchiveSweeper.test.ts | 20 +++++++++- .../Layers/ThreadAutoArchiveSweeper.ts | 7 +++- .../src/orchestration/childThreadDecisions.ts | 21 +++++++--- .../decider.childThreads.test.ts | 39 +++++++++++++++++++ apps/server/src/orchestration/decider.ts | 2 +- .../provider/Layers/ProviderSessionReaper.ts | 18 +++------ docs/design/child-threads.md | 6 +-- packages/shared/src/checkBacks.ts | 31 +++++++++++++++ 8 files changed, 119 insertions(+), 25 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index 112e4a854..ede0cc471 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -301,9 +301,10 @@ describe("ThreadAutoArchiveSweeper", () => { }); }); - it("stops the sessions of what it archives, and leaves a parent whose child is still at work", async () => { + it("stops the sessions of what it archives, and leaves a parent whose child is still at work or owes a check-back", async () => { const idleParent = thread("idle-parent"); const busyParent = thread("busy-parent"); + const waitingParent = thread("waiting-parent"); const busyChild = thread("busy-child", { parentThreadId: busyParent.id, attachedToParent: true, @@ -323,6 +324,22 @@ describe("ThreadAutoArchiveSweeper", () => { }), busyParent, { ...busyChild, session: runningSession(busyChild.id) }, + waitingParent, + // Idle, but set to come back in its session, which the archive would stop. + thread("check-back-child", { + parentThreadId: waitingParent.id, + attachedToParent: true, + checkBacks: [ + { + id: "cb-1", + participantId: null, + scheduledFor: new Date(NOW_MS + 20 * 60 * 1_000).toISOString(), + exact: true, + recurring: false, + durable: false, + }, + ], + }), ], takesAlong: { [idleParent.id]: ["idle-child"] }, }); @@ -332,6 +349,7 @@ describe("ThreadAutoArchiveSweeper", () => { expect.arrayContaining([idleParent.id]), ); expect(dispatched.map((command) => command.threadId)).not.toContain(busyParent.id); + expect(dispatched.map((command) => command.threadId)).not.toContain(waitingParent.id); expect(stopped).toEqual(expect.arrayContaining([idleParent.id, "idle-child"])); expect(stopped).not.toContain("separated-child"); }); diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index 4a914e3f0..34f6cd97e 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { CommandId } from "@threadlines/contracts"; +import { holdsRuntimeCheckBack } from "@threadlines/shared/checkBacks"; import { isAutoArchiveProtectedThread, selectAutoArchiveCandidates, @@ -80,8 +81,10 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti (thread) => thread.parentThreadId !== null && thread.attachedToParent && - // At work or waiting on the user (a pin is not work). - isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) && + // At work or waiting on the user (a pin is not work), or owing a + // check-back that archiving would cancel with its runtime. + (isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) || + holdsRuntimeCheckBack(thread, nowMs)) && thread.archivedAt === null, ) .map((thread) => thread.parentThreadId), diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 458bde5d8..64d0e7b11 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -12,6 +12,7 @@ * `baseFor`. The rules for who may ask live in `@threadlines/shared/childThreads`, * shared with the room MCP server. */ +import { holdsRuntimeCheckBack } from "@threadlines/shared/checkBacks"; import { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { hasLiveSideTurn } from "@threadlines/shared/sideTurns"; import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode"; @@ -1724,7 +1725,10 @@ function separationEvents( * nobody waits on (a dev server) and a command still going in its terminal. * Ask for it where the thread is about to be stopped and its terminals * closed (archiving a parent's family). A thread's move waits on the same - * pieces (threadMoveDecisions.ts, workWaits). + * pieces (threadMoveDecisions.ts, workWaits). A check-back is not work + * here: it doesn't keep a thread from wrapping up or being reported idle. + * Archiving, which stops the runtime it fires in, checks for one itself + * (childArchivePlan). */ export function childHasLiveWork( thread: OrchestrationThread, @@ -2070,13 +2074,14 @@ export function childDeletionEvents( } /** - * What archiving a parent does to its family: settled children archive with - * it (stamped, so unarchiving the parent brings them back), live ones are - * separated first and keep running on their own. + * What archiving a parent at `nowMs` does to its family: settled children + * archive with it (stamped, so unarchiving the parent brings them back), live + * ones are separated first and keep running on their own. */ export function childArchivePlan( readModel: OrchestrationReadModel, parent: OrchestrationThread, + nowMs: number, ): { readonly archive: ReadonlyArray; readonly separate: ReadonlyArray; @@ -2087,9 +2092,13 @@ export function childArchivePlan( // A child its parent still has a request open for is at work for it, even // one with nothing running yet because it is still being set up. Archiving // stops a child's runtime and closes its terminals, so a dev server or a - // command still going in its terminal keeps it out too. + // command still going in its terminal keeps it out too, and so does a + // check-back its agent set that would die with the runtime: unarchiving + // brings the thread back, not the promise to come back. const live = (child: OrchestrationThread) => - childHasLiveWork(child, { running: true }) || requestsFor(parent, child.id).length > 0; + childHasLiveWork(child, { running: true }) || + requestsFor(parent, child.id).length > 0 || + holdsRuntimeCheckBack(child, nowMs); return { archive: children.filter((child) => !live(child)), separate: children.filter(live), diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 35da10795..10898e109 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -10,6 +10,7 @@ import { EMPTY_CHILD_REQUEST_STATE, EventId, MessageId, + type OrchestrationCheckBack, type OrchestrationCommand, type OrchestrationCommandRun, type OrchestrationEvent, @@ -551,6 +552,44 @@ describe("decider child threads", () => { expect(threadIn(archived.model, ranEarlier.id).archivedAt).not.toBeNull(); }); + it("archiving a parent separates a child whose check-back would die with its runtime", async () => { + // The decider stamps the archive from the real clock. + const fromNow = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString(); + const checkBack = ( + id: string, + scheduledFor: string, + durable: boolean, + ): OrchestrationCheckBack => ({ + id, + participantId: null, + scheduledFor, + exact: true, + recurring: false, + durable, + }); + const child = (id: string, checkBacks: ReadonlyArray) => + thread(ThreadId.make(id), { parentThreadId: PARENT, attachedToParent: true, checkBacks }); + // Idle after answering, set to come back in 20 minutes. + const willCheckBack = child("will-check-back", [checkBack("cb-soon", fromNow(20), false)]); + // Saved to disk: it outlives the session the archive stops. + const savedCheckBack = child("saved-check-back", [checkBack("cb-saved", fromNow(20), true)]); + // Long past its time and never fired: nothing is owed any more. + const staleCheckBack = child("stale-check-back", [checkBack("cb-old", fromNow(-120), false)]); + const archived = await run( + readModel([thread(PARENT), willCheckBack, savedCheckBack, staleCheckBack]), + { type: "thread.archive", commandId: CommandId.make("archive"), threadId: PARENT }, + ); + const eventsFor = (id: ThreadId) => + archived.events + .filter((event) => "threadId" in event.payload && event.payload.threadId === id) + .map((event) => event.type); + expect(eventsFor(willCheckBack.id)).toEqual(["thread.parent-attachment-set"]); + expect(eventsFor(savedCheckBack.id)).toEqual(["thread.archived"]); + expect(eventsFor(staleCheckBack.id)).toEqual(["thread.archived"]); + expect(threadIn(archived.model, willCheckBack.id).attachedToParent).toBe(false); + expect(threadIn(archived.model, willCheckBack.id).archivedAt).toBeNull(); + }); + it("lets only the server start a thread as another's child, and never under a child", async () => { const childOfChild: OrchestrationCommand = { type: "thread.create", diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index d8e5264a9..f7a2bc4e5 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1961,7 +1961,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // Child threads: nothing it asked for comes back any more; its settled // children are archived with it and its live ones separated; a child's // parent stops waiting on it. - const plan = childArchivePlan(readModel, thread); + const plan = childArchivePlan(readModel, thread, Date.parse(occurredAt)); const familyEvents: ReadonlyArray = [ ...decideChildDeliveriesStop(readModel, thread, baseFor, occurredAt, "archived"), ...plan.separate.map((child): PlannedOrchestrationEvent => ({ diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index 9da9d2392..175f64a41 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -12,6 +12,7 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import { runtimeCheckBackOwed } from "@threadlines/shared/checkBacks"; import { parseParticipantSessionKey, sessionKeyThreadId, @@ -37,11 +38,6 @@ import { ProviderService } from "../Services/ProviderService.ts"; const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; const DEFAULT_BACKGROUND_TASK_GRACE_MS = 4 * 60 * 60 * 1000; -/** How long past a check-back's time its runtime is kept for it. Claude - * states a wake-up's exact time but may run a cron job up to 30 minutes - * late (its scheduler spreads jobs out). */ -const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; -const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; /** Claude's repeating jobs expire after 7 days; an idle runtime is not kept * for one longer than that. */ const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; @@ -62,13 +58,11 @@ const holdsForCheckBack = ( nowMs: number, idleDurationMs: number, ) => - checkBacks.some((checkBack) => { - if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; - const due = - Date.parse(checkBack.scheduledFor) + - (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); - return Number.isFinite(due) && nowMs < due; - }); + checkBacks.some((checkBack) => + checkBack.recurring + ? idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS + : runtimeCheckBackOwed(checkBack, nowMs), + ); type ThreadShellWithSession = { readonly session?: OrchestrationSession | null; diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 2a9dd7737..26ae321f8 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -59,7 +59,7 @@ These rules override anything in the sections below that disagrees with them. 5. **The user and a child's answer.** A user steer into the answering turn, or into its continuation, becomes part of that turn by design, and the answer includes it. A _new_ user turn in the child while the request is `awaiting_background` settles the request with the candidate before that turn runs. 6. **Room history and catch-up** name `fromThread` messages by origin ("Request from thread X", "Report from thread X") through one shared author renderer, instead of labelling them "User" (roomHistory.ts:91, roomCatchUp.ts:216). Cancellation marking (roomAgentRequests.ts:309) covers reports too. 7. **`handed-back`** is stamped only when the settle actually emits a report. Suppressed, cancelled and stopped outcomes never set it. -8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. Live children are separated; the rest are archived. +8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back still owed that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts, the rule the idle reaper keeps a runtime by): unarchiving would bring the thread back but not the check-back. A durable one, or one long past its time, doesn't. Live children are separated; the rest are archived. 9. **`archivedWithParentAt`** is set only on children this cascade newly archives. Any independent archive or unarchive of the child clears it. 10. **Revert** is refused in a parent while it has open child requests or queued reports. It's also refused in a child while a parent request is bound to it ("Finish or stop its threads first"), extending the room guard at decider.ts:2385. @@ -365,10 +365,10 @@ Each of these settles open requests and also unqueues the matching queued report - **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command carries `withChildren: true`, in which case they're deleted. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. - **Archive the parent.** The cascade is decided on the server: - - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal) are archived and stamped `archivedWithParentAt`; + - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal, no check-back owed that would die with their session) are archived and stamped `archivedWithParentAt`; - live attached children are separated first. - Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children, and otherwise uses the same cascade. Unarchive restores the parent plus the children stamped with its archive. + Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child owing such a check-back included), and otherwise uses the same cascade. A check-back doesn't keep the child itself out of Wrapped (the snooze rule); this only keeps the archive from stopping the session it fires in. Unarchive restores the parent plus the children stamped with its archive. - **Room participant leaves.** Its child requests settle `cancelled`, its queued reports are unqueued, and its pending notes are dropped. This is an extension of `cancelAgentRequestsForLeaving`. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 6c54b3c74..40e6d1e3d 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -43,3 +43,34 @@ export function sameCheckBacks( }) ); } + +/** How long past a check-back's time it is still owed. Claude states a + * wake-up's exact time but may run a cron job up to 30 minutes late (its + * scheduler spreads jobs out). */ +const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; +const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; + +/** + * Whether a check-back that dies with its runtime is still owed at `nowMs`: + * not saved to outlive it, and repeating or not yet past its time. Stopping + * a runtime that holds one cancels a promise its agent made. The idle reaper + * keeps such a runtime; archiving a parent separates such a child instead of + * archiving it. + */ +export function runtimeCheckBackOwed(checkBack: OrchestrationCheckBack, nowMs: number): boolean { + if (checkBack.durable) return false; + if (checkBack.recurring) return true; + const due = + Date.parse(checkBack.scheduledFor) + + (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); + return Number.isFinite(due) && nowMs < due; +} + +/** Whether any of a thread's agents still owes a check-back a session stop + * would cancel (runtimeCheckBackOwed). */ +export function holdsRuntimeCheckBack( + thread: { readonly checkBacks?: ReadonlyArray | undefined }, + nowMs: number, +): boolean { + return (thread.checkBacks ?? []).some((checkBack) => runtimeCheckBackOwed(checkBack, nowMs)); +} From 91a09ab85f9649b1648547946aeef058130c3118 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:38:03 -0500 Subject: [PATCH 2/3] fix(server): no archive path ends a check-back, and the cascade reads no clock Review follow-ups to the archive cascade fix: - Auto-archive and "Archive inactive threads now" could still archive the child (or any thread) holding the check-back directly. The rule now lives in isAutoArchiveProtectedThread, which both paths use. - The cascade read the decider's clock to judge a check-back's grace window, so one command could decide differently around a boundary. holdsRuntimeCheckBack is now time-free: any check-back not saved to outlive the runtime counts. The idle reaper is back to its own rule. - So a stale entry can't block auto-archive for good, thread.archive clears the runtime-only check-backs of every thread it archives, with a "Check-back ended" note. The runtime's report of them comes after the archive and was never recorded for an archived thread. - A linked child stopped for an archived parent's open request still loses its check-backs; documented as a known limit. --- .../Layers/ThreadAutoArchiveSweeper.test.ts | 3 + .../Layers/ThreadAutoArchiveSweeper.ts | 8 +-- .../src/orchestration/childThreadDecisions.ts | 9 ++- .../decider.childThreads.test.ts | 46 +++++++------- apps/server/src/orchestration/decider.ts | 61 ++++++++++++++++++- .../provider/Layers/ProviderSessionReaper.ts | 18 ++++-- docs/design/child-threads.md | 6 +- packages/shared/src/checkBacks.ts | 37 +++-------- packages/shared/src/threadAutoArchive.test.ts | 14 +++++ packages/shared/src/threadAutoArchive.ts | 9 +++ 10 files changed, 144 insertions(+), 67 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index ede0cc471..e8e3db597 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -352,6 +352,9 @@ describe("ThreadAutoArchiveSweeper", () => { expect(dispatched.map((command) => command.threadId)).not.toContain(waitingParent.id); expect(stopped).toEqual(expect.arrayContaining([idleParent.id, "idle-child"])); expect(stopped).not.toContain("separated-child"); + // Inactive long enough itself, but archiving it would end its check-back. + expect(dispatched.map((command) => command.threadId)).not.toContain("check-back-child"); + expect(stopped).not.toContain("check-back-child"); }); it("does not archive protected or recently active threads", async () => { diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index 34f6cd97e..2d117f541 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -1,7 +1,6 @@ import { randomUUID } from "node:crypto"; import { CommandId } from "@threadlines/contracts"; -import { holdsRuntimeCheckBack } from "@threadlines/shared/checkBacks"; import { isAutoArchiveProtectedThread, selectAutoArchiveCandidates, @@ -81,10 +80,9 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti (thread) => thread.parentThreadId !== null && thread.attachedToParent && - // At work or waiting on the user (a pin is not work), or owing a - // check-back that archiving would cancel with its runtime. - (isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) || - holdsRuntimeCheckBack(thread, nowMs)) && + // At work, waiting on the user or set to check back (a pin is + // not work). + isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) && thread.archivedAt === null, ) .map((thread) => thread.parentThreadId), diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 64d0e7b11..171d8c67e 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -2074,14 +2074,13 @@ export function childDeletionEvents( } /** - * What archiving a parent at `nowMs` does to its family: settled children - * archive with it (stamped, so unarchiving the parent brings them back), live - * ones are separated first and keep running on their own. + * What archiving a parent does to its family: settled children archive with + * it (stamped, so unarchiving the parent brings them back), live ones are + * separated first and keep running on their own. */ export function childArchivePlan( readModel: OrchestrationReadModel, parent: OrchestrationThread, - nowMs: number, ): { readonly archive: ReadonlyArray; readonly separate: ReadonlyArray; @@ -2098,7 +2097,7 @@ export function childArchivePlan( const live = (child: OrchestrationThread) => childHasLiveWork(child, { running: true }) || requestsFor(parent, child.id).length > 0 || - holdsRuntimeCheckBack(child, nowMs); + holdsRuntimeCheckBack(child); return { archive: children.filter((child) => !live(child)), separate: children.filter(live), diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 10898e109..cb8ac4b66 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -552,42 +552,46 @@ describe("decider child threads", () => { expect(threadIn(archived.model, ranEarlier.id).archivedAt).not.toBeNull(); }); - it("archiving a parent separates a child whose check-back would die with its runtime", async () => { - // The decider stamps the archive from the real clock. - const fromNow = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString(); - const checkBack = ( - id: string, - scheduledFor: string, - durable: boolean, - ): OrchestrationCheckBack => ({ + it("archiving a parent separates a child whose check-back would die with its runtime, and clears its own", async () => { + const checkBack = (id: string, durable: boolean): OrchestrationCheckBack => ({ id, participantId: null, - scheduledFor, + scheduledFor: at(20 * 60), exact: true, recurring: false, durable, }); const child = (id: string, checkBacks: ReadonlyArray) => thread(ThreadId.make(id), { parentThreadId: PARENT, attachedToParent: true, checkBacks }); - // Idle after answering, set to come back in 20 minutes. - const willCheckBack = child("will-check-back", [checkBack("cb-soon", fromNow(20), false)]); + // Idle after answering, set to come back in its session. + const willCheckBack = child("will-check-back", [checkBack("cb-soon", false)]); // Saved to disk: it outlives the session the archive stops. - const savedCheckBack = child("saved-check-back", [checkBack("cb-saved", fromNow(20), true)]); - // Long past its time and never fired: nothing is owed any more. - const staleCheckBack = child("stale-check-back", [checkBack("cb-old", fromNow(-120), false)]); - const archived = await run( - readModel([thread(PARENT), willCheckBack, savedCheckBack, staleCheckBack]), - { type: "thread.archive", commandId: CommandId.make("archive"), threadId: PARENT }, - ); + const savedCheckBack = child("saved-check-back", [checkBack("cb-saved", true)]); + // The parent's own check-backs: archiving it ends the one in its session. + const parent = thread(PARENT, { + checkBacks: [checkBack("cb-parent", false), checkBack("cb-parent-saved", true)], + }); + const archived = await run(readModel([parent, willCheckBack, savedCheckBack]), { + type: "thread.archive", + commandId: CommandId.make("archive"), + threadId: PARENT, + }); const eventsFor = (id: ThreadId) => archived.events .filter((event) => "threadId" in event.payload && event.payload.threadId === id) .map((event) => event.type); expect(eventsFor(willCheckBack.id)).toEqual(["thread.parent-attachment-set"]); expect(eventsFor(savedCheckBack.id)).toEqual(["thread.archived"]); - expect(eventsFor(staleCheckBack.id)).toEqual(["thread.archived"]); - expect(threadIn(archived.model, willCheckBack.id).attachedToParent).toBe(false); - expect(threadIn(archived.model, willCheckBack.id).archivedAt).toBeNull(); + expect(threadIn(archived.model, willCheckBack.id).checkBacks).toEqual([ + checkBack("cb-soon", false), + ]); + const archivedParent = threadIn(archived.model, PARENT); + expect(archivedParent.checkBacks?.map((entry) => entry.id)).toEqual(["cb-parent-saved"]); + expect( + archivedParent.activities + .filter((activity) => activity.kind === "check-back.ended") + .map((activity) => activity.summary), + ).toEqual(["Check-back ended: this thread was archived"]); }); it("lets only the server start a thread as another's child, and never under a child", async () => { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index f7a2bc4e5..f7fe4d1e1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -330,6 +330,59 @@ function childEventBase( }); } +/** + * What archiving `thread` does to its check-backs: each agent's ones that die + * with its runtime are cleared, with a note in the chat, and the saved ones + * stay. The runtime's own report of it comes after the archive and isn't + * recorded, so without this an unarchived thread would show them still set + * and auto-archive would skip it for good (holdsRuntimeCheckBack). + */ +function archiveEndsCheckBacks( + thread: OrchestrationThread, + baseFor: ChildEventBase, + at: string, + commandId: OrchestrationCommand["commandId"], +): ReadonlyArray { + const checkBacks = thread.checkBacks ?? []; + const ended = checkBacks.filter((checkBack) => !checkBack.durable); + const agents = [...new Set(ended.map((checkBack) => checkBack.participantId))]; + return [ + ...agents.map((participantId): PlannedOrchestrationEvent => ({ + ...baseFor(thread.id), + type: "thread.check-backs-set", + payload: { + threadId: thread.id, + participantId, + checkBacks: checkBacks.filter( + (checkBack) => checkBack.participantId === participantId && checkBack.durable, + ), + updatedAt: at, + }, + })), + ...ended.map((checkBack): PlannedOrchestrationEvent => ({ + ...baseFor(thread.id), + type: "thread.activity-appended", + payload: { + threadId: thread.id, + activity: { + id: EventId.make(`archive-check-back-ended:${commandId}:${checkBack.id}`), + tone: "info", + kind: "check-back.ended", + summary: "Check-back ended: this thread was archived", + payload: { + scheduledFor: checkBack.scheduledFor, + recurring: checkBack.recurring, + ...(checkBack.description ? { description: checkBack.description } : {}), + }, + turnId: null, + participantId: checkBack.participantId, + createdAt: at, + }, + }, + })), + ]; +} + /** * The user wrote: the per-message child thread counts start over, and a * lead chat's pass no longer blocks starting threads. A turn Threadlines @@ -1961,7 +2014,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // Child threads: nothing it asked for comes back any more; its settled // children are archived with it and its live ones separated; a child's // parent stops waiting on it. - const plan = childArchivePlan(readModel, thread, Date.parse(occurredAt)); + const plan = childArchivePlan(readModel, thread); const familyEvents: ReadonlyArray = [ ...decideChildDeliveriesStop(readModel, thread, baseFor, occurredAt, "archived"), ...plan.separate.map((child): PlannedOrchestrationEvent => ({ @@ -2003,6 +2056,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" baseFor, ), ), + // Archiving stops its runtimes, and with them each check-back not + // saved to outlive them. Their report of it arrives once the thread + // is archived and isn't recorded, so the archive clears them itself. + ...[thread, ...plan.archive].flatMap((archived) => + archiveEndsCheckBacks(archived, baseFor, occurredAt, command.commandId), + ), // An archived thread doesn't continue by itself, now or after it comes back. ...[thread, ...plan.archive].flatMap((archived): PlannedOrchestrationEvent[] => { const waiting = archived.session?.continueAtReset ?? null; diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index 175f64a41..9da9d2392 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -12,7 +12,6 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import { runtimeCheckBackOwed } from "@threadlines/shared/checkBacks"; import { parseParticipantSessionKey, sessionKeyThreadId, @@ -38,6 +37,11 @@ import { ProviderService } from "../Services/ProviderService.ts"; const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; const DEFAULT_BACKGROUND_TASK_GRACE_MS = 4 * 60 * 60 * 1000; +/** How long past a check-back's time its runtime is kept for it. Claude + * states a wake-up's exact time but may run a cron job up to 30 minutes + * late (its scheduler spreads jobs out). */ +const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; +const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; /** Claude's repeating jobs expire after 7 days; an idle runtime is not kept * for one longer than that. */ const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; @@ -58,11 +62,13 @@ const holdsForCheckBack = ( nowMs: number, idleDurationMs: number, ) => - checkBacks.some((checkBack) => - checkBack.recurring - ? idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS - : runtimeCheckBackOwed(checkBack, nowMs), - ); + checkBacks.some((checkBack) => { + if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; + const due = + Date.parse(checkBack.scheduledFor) + + (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); + return Number.isFinite(due) && nowMs < due; + }); type ThreadShellWithSession = { readonly session?: OrchestrationSession | null; diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 26ae321f8..86a4555ea 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -59,7 +59,7 @@ These rules override anything in the sections below that disagrees with them. 5. **The user and a child's answer.** A user steer into the answering turn, or into its continuation, becomes part of that turn by design, and the answer includes it. A _new_ user turn in the child while the request is `awaiting_background` settles the request with the candidate before that turn runs. 6. **Room history and catch-up** name `fromThread` messages by origin ("Request from thread X", "Report from thread X") through one shared author renderer, instead of labelling them "User" (roomHistory.ts:91, roomCatchUp.ts:216). Cancellation marking (roomAgentRequests.ts:309) covers reports too. 7. **`handed-back`** is stamped only when the settle actually emits a report. Suppressed, cancelled and stopped outcomes never set it. -8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back still owed that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts, the rule the idle reaper keeps a runtime by): unarchiving would bring the thread back but not the check-back. A durable one, or one long past its time, doesn't. Live children are separated; the rest are archived. +8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts: any one not saved to outlive it, with no clock read, so the decider stays deterministic): unarchiving would bring the thread back but not the check-back. Live children are separated; the rest are archived. Each thread the archive takes has its runtime-only check-backs cleared in the same command, with a "Check-back ended" note: the runtime's own report of them arrives after the archive and isn't recorded for an archived thread, so without that an unarchived thread would show them still set. 9. **`archivedWithParentAt`** is set only on children this cascade newly archives. Any independent archive or unarchive of the child clears it. 10. **Revert** is refused in a parent while it has open child requests or queued reports. It's also refused in a child while a parent request is bound to it ("Finish or stop its threads first"), extending the room guard at decider.ts:2385. @@ -368,7 +368,9 @@ Each of these settles open requests and also unqueues the matching queued report - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal, no check-back owed that would die with their session) are archived and stamped `archivedWithParentAt`; - live attached children are separated first. - Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child owing such a check-back included), and otherwise uses the same cascade. A check-back doesn't keep the child itself out of Wrapped (the snooze rule); this only keeps the archive from stopping the session it fires in. Unarchive restores the parent plus the children stamped with its archive. + Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child holding such a check-back included), and otherwise uses the same cascade. Auto-archive and Settings' "Archive inactive threads now" also skip any thread, child or not, holding one (`isAutoArchiveProtectedThread`). A check-back doesn't keep a thread out of Wrapped (the snooze rule); this only keeps an archive from stopping the session it fires in. + + Known limit: a child on a linked computer that the parent still has a request open for is stopped there (`peer.thread.stop`, docs/design/fleet.md "Stop and wrap"), and that stop ends its runtime-only check-backs, as Stop and wrap on the parent do. Interrupting only its turn would leave background work running there that nothing here shows. Unarchive restores the parent plus the children stamped with its archive. - **Room participant leaves.** Its child requests settle `cancelled`, its queued reports are unqueued, and its pending notes are dropped. This is an extension of `cancelAgentRequestsForLeaving`. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 40e6d1e3d..70bd8f655 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -44,33 +44,16 @@ export function sameCheckBacks( ); } -/** How long past a check-back's time it is still owed. Claude states a - * wake-up's exact time but may run a cron job up to 30 minutes late (its - * scheduler spreads jobs out). */ -const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; -const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; - /** - * Whether a check-back that dies with its runtime is still owed at `nowMs`: - * not saved to outlive it, and repeating or not yet past its time. Stopping - * a runtime that holds one cancels a promise its agent made. The idle reaper - * keeps such a runtime; archiving a parent separates such a child instead of - * archiving it. + * Whether any of a thread's agents holds a check-back that dies with its + * runtime (not saved to outlive it). Stopping that runtime cancels a promise + * its agent made, so archiving leaves such a thread running: a parent's + * archive separates the child instead, and auto-archive and "Archive + * inactive threads now" skip it. No clock is read: a runtime that stops + * reports its list emptied, and archiving clears what it ends. */ -export function runtimeCheckBackOwed(checkBack: OrchestrationCheckBack, nowMs: number): boolean { - if (checkBack.durable) return false; - if (checkBack.recurring) return true; - const due = - Date.parse(checkBack.scheduledFor) + - (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); - return Number.isFinite(due) && nowMs < due; -} - -/** Whether any of a thread's agents still owes a check-back a session stop - * would cancel (runtimeCheckBackOwed). */ -export function holdsRuntimeCheckBack( - thread: { readonly checkBacks?: ReadonlyArray | undefined }, - nowMs: number, -): boolean { - return (thread.checkBacks ?? []).some((checkBack) => runtimeCheckBackOwed(checkBack, nowMs)); +export function holdsRuntimeCheckBack(thread: { + readonly checkBacks?: ReadonlyArray> | undefined; +}): boolean { + return (thread.checkBacks ?? []).some((checkBack) => !checkBack.durable); } diff --git a/packages/shared/src/threadAutoArchive.test.ts b/packages/shared/src/threadAutoArchive.test.ts index 153787a36..7de903b7a 100644 --- a/packages/shared/src/threadAutoArchive.test.ts +++ b/packages/shared/src/threadAutoArchive.test.ts @@ -121,4 +121,18 @@ describe("thread auto-archive rules", () => { expect(candidates.map(({ id }) => id)).toEqual(["included"]); }); + + it("keeps a thread whose agent will check back in a session archiving would stop", () => { + const candidates = selectAutoArchiveCandidates({ + threads: [ + thread("checks-back", { checkBacks: [{ durable: false }] }), + // Saved to disk, it outlives the session. + thread("saved-check-back", { checkBacks: [{ durable: true }] }), + ], + inactiveDays: 30, + nowMs: NOW_MS, + }); + + expect(candidates.map(({ id }) => id)).toEqual(["saved-check-back"]); + }); }); diff --git a/packages/shared/src/threadAutoArchive.ts b/packages/shared/src/threadAutoArchive.ts index 18cfb318a..5f6b3545d 100644 --- a/packages/shared/src/threadAutoArchive.ts +++ b/packages/shared/src/threadAutoArchive.ts @@ -1,3 +1,5 @@ +import { holdsRuntimeCheckBack } from "./checkBacks.ts"; + export const AUTO_ARCHIVE_SUGGESTED_INACTIVE_DAYS = 30 as const; export interface AutoArchiveThreadFields { @@ -17,6 +19,8 @@ export interface AutoArchiveThreadFields { readonly awaitedChildThreadCount?: number | undefined; /** Child threads: threads its agent asked to start wait for the user. */ readonly pendingChildApproval?: boolean | undefined; + /** Times its agents set to come back (holdsRuntimeCheckBack). */ + readonly checkBacks?: ReadonlyArray<{ readonly durable: boolean }> | undefined; readonly session: { readonly status: string; readonly orchestrationStatus?: string | undefined; @@ -53,6 +57,11 @@ export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): b return true; } + // Its agent will come back in a runtime archiving would stop. + if (holdsRuntimeCheckBack(thread)) { + return true; + } + const session = thread.session; if (!session) { return false; From 7aff59043f1166fded90f0f739694d21377adaaa Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:07 -0500 Subject: [PATCH 3/3] fix(server): archive paths use the reaper's check-back rule, not a clearing Second review round on the archive cascade fix: - Drop the check-back clearing inside thread.archive. It could report a check-back ended while a room agent's runtime still held it (the named archive stops only the projected session), and two agents with the same schedule id shared one note id. - The cascade keeps its time-free rule (holdsRuntimeCheckBack): a stale entry only leaves a child as its own thread. - Auto-archive and "Archive inactive threads now" use the idle reaper's time-windowed rule (runtimeCheckBackOwed, now in shared/checkBacks), so an entry whose runtime ended unreported, or one from before this fix, stops protecting a thread on its own. The reaper's behavior is unchanged. - The sweeper rereads each candidate before archiving it, and the Settings button re-checks each thread against the live store, so one that set a check-back since the list was made is left alone. --- .../Layers/ThreadAutoArchiveSweeper.test.ts | 49 ++++++++++++++- .../Layers/ThreadAutoArchiveSweeper.ts | 20 ++++++- .../decider.childThreads.test.ts | 19 +----- apps/server/src/orchestration/decider.ts | 59 ------------------- .../provider/Layers/ProviderSessionReaper.ts | 18 +----- .../components/settings/SettingsPanels.tsx | 18 ++++++ docs/design/child-threads.md | 4 +- packages/shared/src/checkBacks.ts | 43 ++++++++++++-- packages/shared/src/threadAutoArchive.test.ts | 20 ++++++- packages/shared/src/threadAutoArchive.ts | 26 +++++--- 10 files changed, 164 insertions(+), 112 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index e8e3db597..ee662b2c4 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -110,6 +110,8 @@ function runningSession(threadId: ThreadId): OrchestrationSession { function makeSnapshotQuery( threads: readonly OrchestrationThreadShell[], leadThreadId?: ThreadId, + /** A thread as read right before its archive, when it changed since the snapshot. */ + latest: Readonly> = {}, ): ProjectionSnapshotQueryShape { const shellSnapshot = { snapshotSequence: 1, @@ -154,7 +156,10 @@ function makeSnapshotQuery( listClaimedSettingsChanges: () => Effect.succeed([]), listSecretRequests: () => Effect.succeed([]), listThreadShells: () => Effect.succeed([]), - getThreadShellById: () => Effect.succeed(Option.none()), + getThreadShellById: (threadId) => + Effect.succeed( + Option.fromNullishOr(latest[threadId] ?? threads.find((entry) => entry.id === threadId)), + ), getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), @@ -180,6 +185,7 @@ describe("ThreadAutoArchiveSweeper", () => { readonly settingsShape?: ServerSettingsShape; /** The children each parent's archive takes along, as the decider would decide. */ readonly takesAlong?: Readonly>; + readonly latest?: Readonly>; }) { const dispatched: Array> = []; const stopped: string[] = []; @@ -265,7 +271,7 @@ describe("ThreadAutoArchiveSweeper", () => { Layer.provideMerge( Layer.succeed( ProjectionSnapshotQuery, - makeSnapshotQuery(input.threads, input.leadThreadId), + makeSnapshotQuery(input.threads, input.leadThreadId, input.latest), ), ), Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)), @@ -357,6 +363,45 @@ describe("ThreadAutoArchiveSweeper", () => { expect(stopped).not.toContain("check-back-child"); }); + it("stops counting a check-back once its time is long past, and checks again right before archiving", async () => { + const checkBack = (scheduledForMs: number) => ({ + id: "cb-1", + participantId: null, + scheduledFor: new Date(scheduledForMs).toISOString(), + exact: true, + recurring: false, + durable: false, + }); + const staleParent = thread("stale-parent"); + const changedSince = thread("changed-since"); + const { dispatched, sweeper } = await createHarness({ + inactiveDays: 30, + threads: [ + staleParent, + // Its runtime ended without the report landing: the entry is two days old. + thread("stale-check-back-child", { + parentThreadId: staleParent.id, + attachedToParent: true, + checkBacks: [checkBack(NOW_MS - 2 * 24 * 60 * 60 * 1_000)], + }), + changedSince, + ], + // Set a check-back after the sweep's snapshot was taken. + latest: { + [changedSince.id]: { + ...changedSince, + updatedAt: new Date(NOW_MS).toISOString(), + checkBacks: [checkBack(NOW_MS + 20 * 60 * 1_000)], + }, + }, + }); + + await runtime!.runPromise(sweeper.sweepNow()); + const archivedIds = dispatched.map((command) => command.threadId); + expect(archivedIds).toContain(staleParent.id); + expect(archivedIds).not.toContain(changedSince.id); + }); + it("does not archive protected or recently active threads", async () => { const running = thread("running"); const { dispatched, sweeper } = await createHarness({ diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index 2d117f541..b813ed37e 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -9,6 +9,7 @@ import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -82,7 +83,7 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti thread.attachedToParent && // At work, waiting on the user or set to check back (a pin is // not work). - isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }) && + isAutoArchiveProtectedThread({ ...thread, pinnedAt: null }, nowMs) && thread.archivedAt === null, ) .map((thread) => thread.parentThreadId), @@ -103,6 +104,23 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti let archivedCount = 0; for (const thread of candidates) { + // Read again right before: since the snapshot it may have started + // working or set a check-back. A child that did is the decider's to + // keep out of the archive (childArchivePlan). + const latest = yield* projectionSnapshotQuery.getThreadShellById(thread.id).pipe( + Effect.map(Option.getOrNull), + Effect.catch(() => Effect.succeed(null)), + ); + if ( + latest === null || + selectAutoArchiveCandidates({ + threads: [leadThreadIds.has(latest.id) ? { ...latest, lead: true } : latest], + inactiveDays, + nowMs, + }).length === 0 + ) { + continue; + } // `thread.archive` carries no timestamp: the decider stamps // `archivedAt` from its own clock when it accepts the command. const command = { diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index cb8ac4b66..b72703894 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -552,7 +552,7 @@ describe("decider child threads", () => { expect(threadIn(archived.model, ranEarlier.id).archivedAt).not.toBeNull(); }); - it("archiving a parent separates a child whose check-back would die with its runtime, and clears its own", async () => { + it("archiving a parent separates a child whose check-back would die with its runtime", async () => { const checkBack = (id: string, durable: boolean): OrchestrationCheckBack => ({ id, participantId: null, @@ -567,11 +567,7 @@ describe("decider child threads", () => { const willCheckBack = child("will-check-back", [checkBack("cb-soon", false)]); // Saved to disk: it outlives the session the archive stops. const savedCheckBack = child("saved-check-back", [checkBack("cb-saved", true)]); - // The parent's own check-backs: archiving it ends the one in its session. - const parent = thread(PARENT, { - checkBacks: [checkBack("cb-parent", false), checkBack("cb-parent-saved", true)], - }); - const archived = await run(readModel([parent, willCheckBack, savedCheckBack]), { + const archived = await run(readModel([thread(PARENT), willCheckBack, savedCheckBack]), { type: "thread.archive", commandId: CommandId.make("archive"), threadId: PARENT, @@ -582,16 +578,7 @@ describe("decider child threads", () => { .map((event) => event.type); expect(eventsFor(willCheckBack.id)).toEqual(["thread.parent-attachment-set"]); expect(eventsFor(savedCheckBack.id)).toEqual(["thread.archived"]); - expect(threadIn(archived.model, willCheckBack.id).checkBacks).toEqual([ - checkBack("cb-soon", false), - ]); - const archivedParent = threadIn(archived.model, PARENT); - expect(archivedParent.checkBacks?.map((entry) => entry.id)).toEqual(["cb-parent-saved"]); - expect( - archivedParent.activities - .filter((activity) => activity.kind === "check-back.ended") - .map((activity) => activity.summary), - ).toEqual(["Check-back ended: this thread was archived"]); + expect(threadIn(archived.model, willCheckBack.id).archivedAt).toBeNull(); }); it("lets only the server start a thread as another's child, and never under a child", async () => { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index f7fe4d1e1..d8e5264a9 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -330,59 +330,6 @@ function childEventBase( }); } -/** - * What archiving `thread` does to its check-backs: each agent's ones that die - * with its runtime are cleared, with a note in the chat, and the saved ones - * stay. The runtime's own report of it comes after the archive and isn't - * recorded, so without this an unarchived thread would show them still set - * and auto-archive would skip it for good (holdsRuntimeCheckBack). - */ -function archiveEndsCheckBacks( - thread: OrchestrationThread, - baseFor: ChildEventBase, - at: string, - commandId: OrchestrationCommand["commandId"], -): ReadonlyArray { - const checkBacks = thread.checkBacks ?? []; - const ended = checkBacks.filter((checkBack) => !checkBack.durable); - const agents = [...new Set(ended.map((checkBack) => checkBack.participantId))]; - return [ - ...agents.map((participantId): PlannedOrchestrationEvent => ({ - ...baseFor(thread.id), - type: "thread.check-backs-set", - payload: { - threadId: thread.id, - participantId, - checkBacks: checkBacks.filter( - (checkBack) => checkBack.participantId === participantId && checkBack.durable, - ), - updatedAt: at, - }, - })), - ...ended.map((checkBack): PlannedOrchestrationEvent => ({ - ...baseFor(thread.id), - type: "thread.activity-appended", - payload: { - threadId: thread.id, - activity: { - id: EventId.make(`archive-check-back-ended:${commandId}:${checkBack.id}`), - tone: "info", - kind: "check-back.ended", - summary: "Check-back ended: this thread was archived", - payload: { - scheduledFor: checkBack.scheduledFor, - recurring: checkBack.recurring, - ...(checkBack.description ? { description: checkBack.description } : {}), - }, - turnId: null, - participantId: checkBack.participantId, - createdAt: at, - }, - }, - })), - ]; -} - /** * The user wrote: the per-message child thread counts start over, and a * lead chat's pass no longer blocks starting threads. A turn Threadlines @@ -2056,12 +2003,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" baseFor, ), ), - // Archiving stops its runtimes, and with them each check-back not - // saved to outlive them. Their report of it arrives once the thread - // is archived and isn't recorded, so the archive clears them itself. - ...[thread, ...plan.archive].flatMap((archived) => - archiveEndsCheckBacks(archived, baseFor, occurredAt, command.commandId), - ), // An archived thread doesn't continue by itself, now or after it comes back. ...[thread, ...plan.archive].flatMap((archived): PlannedOrchestrationEvent[] => { const waiting = archived.session?.continueAtReset ?? null; diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index 9da9d2392..ed7bbb5d6 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -12,6 +12,7 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import { runtimeCheckBackOwed } from "@threadlines/shared/checkBacks"; import { parseParticipantSessionKey, sessionKeyThreadId, @@ -37,14 +38,6 @@ import { ProviderService } from "../Services/ProviderService.ts"; const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; const DEFAULT_BACKGROUND_TASK_GRACE_MS = 4 * 60 * 60 * 1000; -/** How long past a check-back's time its runtime is kept for it. Claude - * states a wake-up's exact time but may run a cron job up to 30 minutes - * late (its scheduler spreads jobs out). */ -const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; -const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; -/** Claude's repeating jobs expire after 7 days; an idle runtime is not kept - * for one longer than that. */ -const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; /** The check-backs an agent's runtime keeps alive: ones that die with it. */ const runtimeCheckBacks = ( @@ -61,14 +54,7 @@ const holdsForCheckBack = ( checkBacks: ReadonlyArray, nowMs: number, idleDurationMs: number, -) => - checkBacks.some((checkBack) => { - if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; - const due = - Date.parse(checkBack.scheduledFor) + - (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); - return Number.isFinite(due) && nowMs < due; - }); +) => checkBacks.some((checkBack) => runtimeCheckBackOwed(checkBack, nowMs, idleDurationMs)); type ThreadShellWithSession = { readonly session?: OrchestrationSession | null; diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 8b456ca21..d5c163213 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -76,6 +76,7 @@ import { useShallow } from "zustand/react/shallow"; import { selectBootstrapCompleteForActiveEnvironment, selectProjectsAcrossEnvironments, + selectSidebarThreadSummaryByRef, selectSidebarThreadsAcrossEnvironments, useStore, } from "../../store"; @@ -2404,6 +2405,23 @@ export function ArchivedThreadsPanel({ hostedStatic }: { readonly hostedStatic: try { for (const thread of inactiveThreadCandidates) { + // Checked again as each goes: while the confirmation was open it may + // have started working or set a check-back. + const state = useStore.getState(); + const latest = selectSidebarThreadSummaryByRef( + state, + scopeThreadRef(thread.environmentId, thread.id), + ); + if ( + latest === undefined || + selectAutoArchiveCandidates({ + threads: [latest], + projects: selectProjectsAcrossEnvironments(state), + inactiveDays: autoArchivePreviewDays, + }).length === 0 + ) { + continue; + } const api = readEnvironmentApi(thread.environmentId); if (!api) { failedCount += 1; diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 86a4555ea..4511789a9 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -59,7 +59,7 @@ These rules override anything in the sections below that disagrees with them. 5. **The user and a child's answer.** A user steer into the answering turn, or into its continuation, becomes part of that turn by design, and the answer includes it. A _new_ user turn in the child while the request is `awaiting_background` settles the request with the candidate before that turn runs. 6. **Room history and catch-up** name `fromThread` messages by origin ("Request from thread X", "Report from thread X") through one shared author renderer, instead of labelling them "User" (roomHistory.ts:91, roomCatchUp.ts:216). Cancellation marking (roomAgentRequests.ts:309) covers reports too. 7. **`handed-back`** is stamped only when the settle actually emits a report. Suppressed, cancelled and stopped outcomes never set it. -8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts: any one not saved to outlive it, with no clock read, so the decider stays deterministic): unarchiving would bring the thread back but not the check-back. Live children are separated; the rest are archived. Each thread the archive takes has its runtime-only check-backs cleared in the same command, with a "Check-back ended" note: the runtime's own report of them arrives after the archive and isn't recorded for an archived thread, so without that an unarchived thread would show them still set. +8. **Archive cascade membership** uses the shared live-work predicate (`isAutoArchiveProtectedThread` inputs in packages/shared/src/threadAutoArchive.ts, plus queued or pending starts, open child requests, and a command still going in the child's terminal: `childHasLiveWork` with `running`). Every background task counts, awaited or not: archiving stops the child's runtime and closes its terminals, which would kill a dev server or a running command. A check-back that dies with the runtime counts too (`holdsRuntimeCheckBack` in packages/shared/src/checkBacks.ts: any one not saved to outlive it, however old, so the decider reads no clock): unarchiving would bring the thread back but not the check-back. A stale entry only leaves a child as its own thread. Live children are separated; the rest are archived. 9. **`archivedWithParentAt`** is set only on children this cascade newly archives. Any independent archive or unarchive of the child clears it. 10. **Revert** is refused in a parent while it has open child requests or queued reports. It's also refused in a child while a parent request is bound to it ("Finish or stop its threads first"), extending the room guard at decider.ts:2385. @@ -368,7 +368,7 @@ Each of these settles open requests and also unqueues the matching queued report - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal, no check-back owed that would die with their session) are archived and stamped `archivedWithParentAt`; - live attached children are separated first. - Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child holding such a check-back included), and otherwise uses the same cascade. Auto-archive and Settings' "Archive inactive threads now" also skip any thread, child or not, holding one (`isAutoArchiveProtectedThread`). A check-back doesn't keep a thread out of Wrapped (the snooze rule); this only keeps an archive from stopping the session it fires in. + Cleanup (session stop and terminal close, today ws.ts:849-896 for the named thread only) runs for every thread the command archives. `ThreadAutoArchiveSweeper` skips parents with open child requests or live attached children (a child holding such a check-back included), and otherwise uses the same cascade. Auto-archive and Settings' "Archive inactive threads now" also skip any thread, child or not, whose check-back is still owed (`isAutoArchiveProtectedThread`, by the idle reaper's rule `runtimeCheckBackOwed`: a one-off until a little past its time, a repeating one until Claude would have dropped it). They read the clock, so an entry whose runtime ended unreported stops protecting the thread on its own. Each re-checks a thread right before archiving it; a check-back set between that check and the archive can still be cut off, and a child that sets one after the sweeper's snapshot is separated by the cascade rather than archived. A check-back doesn't keep a thread out of Wrapped (the snooze rule); this only keeps an archive from stopping the session it fires in. Known limit: a child on a linked computer that the parent still has a request open for is stopped there (`peer.thread.stop`, docs/design/fleet.md "Stop and wrap"), and that stop ends its runtime-only check-backs, as Stop and wrap on the parent do. Interrupting only its turn would leave background work running there that nothing here shows. Unarchive restores the parent plus the children stamped with its archive. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 70bd8f655..d744f4257 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -46,14 +46,47 @@ export function sameCheckBacks( /** * Whether any of a thread's agents holds a check-back that dies with its - * runtime (not saved to outlive it). Stopping that runtime cancels a promise - * its agent made, so archiving leaves such a thread running: a parent's - * archive separates the child instead, and auto-archive and "Archive - * inactive threads now" skip it. No clock is read: a runtime that stops - * reports its list emptied, and archiving clears what it ends. + * runtime (not saved to outlive it), however old. A parent's archive + * separates such a child instead of archiving it. The decider reads no + * clock, and a stale entry only leaves a child as its own thread. */ export function holdsRuntimeCheckBack(thread: { readonly checkBacks?: ReadonlyArray> | undefined; }): boolean { return (thread.checkBacks ?? []).some((checkBack) => !checkBack.durable); } + +/** How long past a check-back's time it is still owed. Claude states a + * wake-up's exact time but may run a cron job up to 30 minutes late (its + * scheduler spreads jobs out). */ +const CHECK_BACK_EXACT_GRACE_MS = 5 * 60 * 1000; +const CHECK_BACK_SCHEDULE_GRACE_MS = 35 * 60 * 1000; +/** Claude's repeating jobs expire after 7 days; one idle longer is gone. */ +const RECURRING_CHECK_BACK_IDLE_LIMIT_MS = 7 * 24 * 60 * 60 * 1000; + +/** The check-back fields runtimeCheckBackOwed reads. */ +export type OwedCheckBackFields = Pick< + OrchestrationCheckBack, + "durable" | "recurring" | "exact" | "scheduledFor" +>; + +/** + * Whether a check-back that dies with its runtime is still owed at `nowMs`, + * its agent idle for `idleDurationMs`: a repeating one until Claude would + * have expired it, a one-off until a little past its time. Stopping the + * runtime then cancels a promise its agent made. The idle reaper keeps such a + * runtime, and auto-archive skips such a thread; a stale entry, one whose + * runtime ended without its report landing, stops counting on its own. + */ +export function runtimeCheckBackOwed( + checkBack: OwedCheckBackFields, + nowMs: number, + idleDurationMs: number, +): boolean { + if (checkBack.durable) return false; + if (checkBack.recurring) return idleDurationMs < RECURRING_CHECK_BACK_IDLE_LIMIT_MS; + const due = + Date.parse(checkBack.scheduledFor) + + (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); + return Number.isFinite(due) && nowMs < due; +} diff --git a/packages/shared/src/threadAutoArchive.test.ts b/packages/shared/src/threadAutoArchive.test.ts index 7de903b7a..7bce15e18 100644 --- a/packages/shared/src/threadAutoArchive.test.ts +++ b/packages/shared/src/threadAutoArchive.test.ts @@ -123,16 +123,30 @@ describe("thread auto-archive rules", () => { }); it("keeps a thread whose agent will check back in a session archiving would stop", () => { + const checkBack = (overrides: { durable?: boolean; recurring?: boolean; dueMs?: number }) => ({ + durable: overrides.durable ?? false, + recurring: overrides.recurring ?? false, + exact: true, + scheduledFor: new Date(overrides.dueMs ?? NOW_MS + 60 * 60 * 1_000).toISOString(), + }); const candidates = selectAutoArchiveCandidates({ threads: [ - thread("checks-back", { checkBacks: [{ durable: false }] }), + thread("checks-back", { checkBacks: [checkBack({})] }), // Saved to disk, it outlives the session. - thread("saved-check-back", { checkBacks: [{ durable: true }] }), + thread("saved", { checkBacks: [checkBack({ durable: true })] }), + // Its runtime ended unreported: long past its time. + thread("stale", { checkBacks: [checkBack({ dueMs: NOW_MS - 24 * 60 * 60 * 1_000 })] }), + // Claude drops a repeating one after 7 days; this thread was idle 45. + thread("stale-repeating", { checkBacks: [checkBack({ recurring: true })] }), ], inactiveDays: 30, nowMs: NOW_MS, }); - expect(candidates.map(({ id }) => id)).toEqual(["saved-check-back"]); + expect(candidates.map(({ id }) => id).toSorted()).toEqual([ + "saved", + "stale", + "stale-repeating", + ]); }); }); diff --git a/packages/shared/src/threadAutoArchive.ts b/packages/shared/src/threadAutoArchive.ts index 5f6b3545d..a4cbb5a50 100644 --- a/packages/shared/src/threadAutoArchive.ts +++ b/packages/shared/src/threadAutoArchive.ts @@ -1,4 +1,4 @@ -import { holdsRuntimeCheckBack } from "./checkBacks.ts"; +import { runtimeCheckBackOwed, type OwedCheckBackFields } from "./checkBacks.ts"; export const AUTO_ARCHIVE_SUGGESTED_INACTIVE_DAYS = 30 as const; @@ -19,8 +19,8 @@ export interface AutoArchiveThreadFields { readonly awaitedChildThreadCount?: number | undefined; /** Child threads: threads its agent asked to start wait for the user. */ readonly pendingChildApproval?: boolean | undefined; - /** Times its agents set to come back (holdsRuntimeCheckBack). */ - readonly checkBacks?: ReadonlyArray<{ readonly durable: boolean }> | undefined; + /** Times its agents set to come back (runtimeCheckBackOwed). */ + readonly checkBacks?: ReadonlyArray | undefined; readonly session: { readonly status: string; readonly orchestrationStatus?: string | undefined; @@ -35,7 +35,10 @@ export function getAutoArchiveThreadInactiveSince(thread: AutoArchiveThreadField return thread.updatedAt ?? thread.latestUserMessageAt ?? thread.createdAt; } -export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): boolean { +export function isAutoArchiveProtectedThread( + thread: AutoArchiveThreadFields, + nowMs: number = Date.now(), +): boolean { if (thread.archivedAt !== null || thread.pinnedAt !== null || thread.lead === true) { return true; } @@ -57,8 +60,14 @@ export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): b return true; } - // Its agent will come back in a runtime archiving would stop. - if (holdsRuntimeCheckBack(thread)) { + // Its agent will come back in a runtime archiving would stop. A stale + // entry (its runtime ended unreported) runs out with its time. + const idleDurationMs = nowMs - Date.parse(getAutoArchiveThreadInactiveSince(thread)); + if ( + (thread.checkBacks ?? []).some((checkBack) => + runtimeCheckBackOwed(checkBack, nowMs, idleDurationMs), + ) + ) { return true; } @@ -87,10 +96,11 @@ export function selectAutoArchiveCandidates(i return []; } - const cutoffMs = (input.nowMs ?? Date.now()) - input.inactiveDays * 24 * 60 * 60 * 1_000; + const nowMs = input.nowMs ?? Date.now(); + const cutoffMs = nowMs - input.inactiveDays * 24 * 60 * 60 * 1_000; return input.threads .flatMap((thread): Array => { - if (input.isExcluded?.(thread) === true || isAutoArchiveProtectedThread(thread)) { + if (input.isExcluded?.(thread) === true || isAutoArchiveProtectedThread(thread, nowMs)) { return []; }