From 354682bce7208624870a15cf984e754e70cceac1 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:47:19 +0000 Subject: [PATCH 1/2] feat(server): redirect wakes aimed at a retired thread to its replacement A retired standing-bot thread now carries a tombstone (replacedByThreadId, retiredAt). Every wake aimed at it (thread_send, schedule, pr_watch, event) resolves the chain to the live replacement (max 8 hops, fail closed on cycle or dead end), so the retired thread never starts a provider turn. Each redirect appends a record to retired-thread-redirects.jsonl (override with RETIRED_REDIRECT_LEDGER). t3_thread_update gains action set_redirect; self-redirects and cycles are rejected at write time. Model: claude-sonnet-5-5 Task: CLO-1001 Agent: claude-code Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/mcp/OrchestratorMcpService.ts | 1 + .../src/mcp/ThreadMetadataMcpService.ts | 44 ++- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../ModelAlertReactor.test.ts | 59 +++ .../src/orchestration-v2/ModelAlertReactor.ts | 104 ++++-- .../src/orchestration-v2/Orchestrator.ts | 40 ++- .../src/orchestration-v2/ProjectionStore.ts | 12 + .../PullRequestWatchReactor.ts | 111 +++++- .../RetiredThreadRedirect.test.ts | 340 ++++++++++++++++++ .../orchestration-v2/RetiredThreadRedirect.ts | 137 +++++++ .../ThreadManagementService.test.ts | 128 ++++++- .../ThreadManagementService.ts | 27 +- .../orchestration-v2/ThreadMessageIntake.ts | 45 ++- .../src/orchestration-v2/runtimeLayer.test.ts | 259 +++++++++++++ .../orchestrator-mcp-server.md | 14 + packages/contracts/src/index.ts | 1 + packages/contracts/src/orchestrationV2.ts | 14 + packages/contracts/src/threadMetadataMcp.ts | 14 +- packages/contracts/src/threadRedirect.test.ts | 173 +++++++++ packages/contracts/src/threadRedirect.ts | 128 +++++++ 20 files changed, 1590 insertions(+), 63 deletions(-) create mode 100644 apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts create mode 100644 apps/server/src/orchestration-v2/RetiredThreadRedirect.ts create mode 100644 packages/contracts/src/threadRedirect.test.ts create mode 100644 packages/contracts/src/threadRedirect.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index d2e27a3ba8784..d9764faba2c5b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -276,6 +276,7 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure { return failure("run_not_found", error.message); case "ThreadManagementThreadArchivedError": case "ThreadManagementWorktreeRestoreError": + case "ThreadRedirectError": return failure("thread_not_sendable", error.message); case "ThreadManagementNoSteerableRunError": return failure( diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 3429348ba3f31..9f8f07b8be845 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -9,6 +9,7 @@ import { type ThreadMetadataMcpUpdateInput, type ThreadMetadataMcpUpdateResult, ThreadId, + redirectLinkError, routeThreadInbox, withLegacyPeerInboxReason, } from "@t3tools/contracts"; @@ -70,7 +71,9 @@ function metadataCommand(input: { readonly actorThreadId: ThreadId | undefined; }): Extract< OrchestrationV2Command, - { readonly type: "thread.metadata.update" | "thread.standing.set" | "thread.delegation-nudge.set" } + { + readonly type: "thread.metadata.update" | "thread.standing.set" | "thread.delegation-nudge.set"; + } > { switch (input.update.action) { case "set_standing": @@ -94,6 +97,13 @@ function metadataCommand(input: { ? { kind: "mcp_client" } : { kind: "agent", threadId: input.actorThreadId }, }; + case "set_redirect": + return { + type: "thread.metadata.update", + commandId: input.commandId, + threadId: input.threadId, + replacedByThreadId: input.update.replacedByThreadId ?? null, + }; case "route": return { type: "thread.metadata.update", @@ -138,7 +148,16 @@ function resultFromThread(input: { readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" | "standing" | "delegationNudge" + | "id" + | "title" + | "titleRegeneration" + | "linkedPullRequest" + | "updatedAt" + | "inbox" + | "standing" + | "delegationNudge" + | "replacedByThreadId" + | "retiredAt" >; }): ThreadMetadataMcpUpdateResult { return { @@ -147,6 +166,13 @@ function resultFromThread(input: { ...(input.thread.delegationNudge === undefined ? {} : { delegationNudge: input.thread.delegationNudge }), + ...(input.thread.replacedByThreadId === undefined + ? {} + : { + replacedByThreadId: input.thread.replacedByThreadId, + retiredAt: + input.thread.retiredAt == null ? null : DateTime.formatIso(input.thread.retiredAt), + }), threadId: input.thread.id, action: input.action, commandId: input.commandId, @@ -214,15 +240,21 @@ const make = Effect.gen(function* () { input.inboxRouting, ); if (inboxError !== null) return yield* failure("invalid_request", inboxError); - if ( - input.action === "set_delegation_nudge" && - scope.thread?.threadId === threadId - ) { + if (input.action === "set_delegation_nudge" && scope.thread?.threadId === threadId) { return yield* failure( "invalid_request", "A thread cannot change its own delegation nudge. Ask from another thread or the client.", ); } + if (input.action === "set_redirect" && input.replacedByThreadId != null) { + // Same check the orchestrator repeats at commit; failing here gives the caller a clear reason. + const linkError = yield* redirectLinkError( + (id) => threadManagement.getThreadShell(id), + threadId, + input.replacedByThreadId, + ).pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error)))); + if (linkError !== null) return yield* failure("invalid_request", linkError); + } const requestKey = input.clientRequestId === undefined ? yield* random.uuidV4() : input.clientRequestId; const updateCommandId = commandId({ diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 330ca0c720585..281ea6c8edb32 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -270,7 +270,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Default: this thread. Founder must decide/review/approve: `request_decision` with `decision`; stays in their inbox until reply, `resolve_decision` or settle. `route`: `inboxRouting`, `reason` for founder/shared. `rename`: `title`; `set_standing`: `standing`; `set_delegation_nudge`: `delegationNudge` {enabled, thresholds?}, not on itself. Not workspace/branch.", + "Default: this thread. Founder must decide/review/approve: `request_decision` with `decision`; stays in their inbox until reply, `resolve_decision` or settle. `route`: `inboxRouting`, `reason` for founder/shared. `rename`: `title`; `set_standing`: `standing`; `set_delegation_nudge`: `delegationNudge` {enabled, thresholds?}, not on itself. `set_redirect`: `replacedByThreadId` retires a thread (tombstone): every send, schedule, PR watch and event wake aimed at it goes to the replacement and starts no turn there; null clears. Not workspace/branch.", // Keeps the input's action/field check, which rebuilding the struct would drop. parameters: ThreadMetadataMcpUpdateInput.mapFields( Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }), diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts index 18eeccd3b61fb..107c9a59aa6d2 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts @@ -1,3 +1,7 @@ +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + import { assert, it } from "@effect/vitest"; import { EnvironmentId, type OrchestrationV2Run, ThreadId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -28,6 +32,7 @@ import { watcherAlertMessage, } from "./ModelAlertReactor.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; +import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; import { alertIsStale, expectsAutoResume, replacedBySibling } from "./UsageLimitIncidents.ts"; import type { ThreadEventAlert, ThreadEventKind, ThreadFinding } from "./ThreadEventAlerts.ts"; @@ -405,6 +410,60 @@ it.effect("forwards a thread event to a watcher on another environment with one }), ); +it.effect("sends an alert for a retired watcher to its replacement and records the redirect", () => + Effect.gen(function* () { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-alert-")); + const ledger = NodePath.join(dir, "redirects.jsonl"); + const previous = process.env[REDIRECT_LEDGER_ENV]; + process.env[REDIRECT_LEDGER_ENV] = ledger; + try { + const dispatched: Array<{ threadId: string }> = []; + const tombstones: Record = { old: "new", new: null, loop: "loop" }; + const deps = { + dispatch: (command: { threadId: string }) => + Effect.sync(() => void dispatched.push(command)), + call: () => Effect.die("local watcher"), + sha256Hex: (identity: string) => Effect.succeed(`digest(${identity.length})`), + getThreadShell: (threadId: string) => + Effect.succeed( + threadId in tombstones + ? { + replacedByThreadId: tombstones[threadId] + ? ThreadId.make(tombstones[threadId]) + : null, + } + : null, + ), + } as never; + const alert = eventAlert(finding("promise-without-wake", "message:1")); + const here = EnvironmentId.make("laptop"); + const watcher = (id: string) => ({ environmentId: here, threadId: ThreadId.make(id) }); + + yield* deliverAlertToWatcher(deps, alert, watcher("old"), here); + assert.deepEqual( + dispatched.map((command) => command.threadId), + ["new"], + ); + const records = NodeFS.readFileSync(ledger, "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as Record); + assert.equal(records.length, 1); + assert.equal(records[0]!.sourceKind, "event"); + assert.equal(records[0]!.retiredThreadId, "old"); + assert.equal(records[0]!.redirectedToThreadId, "new"); + + // A watcher that cannot be resolved drops the alert: nothing is dispatched anywhere. + yield* deliverAlertToWatcher(deps, alert, watcher("loop"), here); + assert.equal(dispatched.length, 1); + } finally { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + } + }), +); + const limitInput = ( index: number, overrides: Partial[1]> = {}, diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index c6b092a909475..fa631e91b56b1 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -13,6 +13,7 @@ import { OrchestrationV2WorkerAlertReason, OrchestratorMcpThreadSendResult, ThreadId, + type ThreadRedirectNode, } from "@t3tools/contracts"; import { runModelSignals, workerAlert } from "@t3tools/provider-core/server/subagentProjection"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; @@ -47,6 +48,7 @@ import * as ServerSettings from "../serverSettings.ts"; import * as Orchestrator from "./Orchestrator.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { resolveWakeTarget } from "./RetiredThreadRedirect.ts"; import { cursorOf, planThreadSubscription, @@ -854,6 +856,10 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( readonly dispatch: Orchestrator.OrchestratorV2["Service"]["dispatch"]; readonly call: PeerMcpClient.PeerMcpClient["Service"]["call"]; readonly sha256Hex: (identity: string) => Effect.Effect; + /** Reads a thread's redirect tombstone; an alert for a retired watcher goes to its replacement. */ + readonly getThreadShell?: ( + threadId: ThreadId, + ) => Effect.Effect; }, alert: WatcherAlert, watcher: ModelAlertWatcher, @@ -869,10 +875,26 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( expiresAtMs ?? DateTime.toEpochMillis(yield* DateTime.now) + ALERT_DIGEST_TTL_MS, ); if (watcher.environmentId === here) { + // A retired watcher never takes a turn: the alert follows its redirect, or is dropped with a + // warning when the chain cannot be resolved. + const target = + deps.getThreadShell === undefined + ? watcher.threadId + : yield* resolveWakeTarget(deps.getThreadShell, watcher.threadId, { + sourceKind: "event", + }).pipe( + Effect.map((wake) => wake.threadId), + Effect.catchCause((cause) => + Effect.logWarning("alert for retired watcher dropped", { cause }).pipe( + Effect.as(null), + ), + ), + ); + if (target === null) return; yield* deps.dispatch({ type: "message.dispatch", commandId: CommandId.make(`server:${key}`), - threadId: watcher.threadId, + threadId: target, messageId: MessageId.make(`message:${key}`), text: message, attachments: [], @@ -986,7 +1008,12 @@ export const make = Effect.gen(function* () { expiresAtMs: number, ) => deliverAlertToWatcher( - { dispatch: engine.dispatch, call: peers.call, sha256Hex }, + { + dispatch: engine.dispatch, + call: peers.call, + sha256Hex, + getThreadShell: (threadId) => engine.getThreadShell(threadId), + }, alert, watcher, here, @@ -1339,35 +1366,50 @@ export const make = Effect.gen(function* () { if (decision.action === "wake") { eventWakeSeq += 1; const seq = eventWakeSeq; - yield* engine - .dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`server:event-sub:${subscription.id}:${seq}`), - threadId: subscription.subscriberThreadId, - messageId: MessageId.make(`message:event-sub:${subscription.id}:${seq}`), - text: [ - `Update on thread ${title} (${watchedThreadId}), which you subscribed to:`, - ...decision.summaries, - ].join("\n"), - notification: { - source: { kind: "monitor" }, - outcome: "updated", - summary: decision.summaries[0] ?? "thread event", - }, - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - creationSource: "server", - }) - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("event subscription wake failed", { - id: subscription.id, - threadId: subscription.subscriberThreadId, - cause, - }), - ), - ); + const wakeTarget = yield* resolveWakeTarget( + (threadId) => engine.getThreadShell(threadId), + subscription.subscriberThreadId, + { sourceKind: "event", subscriptionId: subscription.id }, + ).pipe( + Effect.map((wake) => wake.threadId), + Effect.catchCause((cause) => + Effect.logWarning("event subscription wake dropped", { + id: subscription.id, + threadId: subscription.subscriberThreadId, + cause, + }).pipe(Effect.as(null)), + ), + ); + if (wakeTarget !== null) + yield* engine + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:event-sub:${subscription.id}:${seq}`), + threadId: wakeTarget, + messageId: MessageId.make(`message:event-sub:${subscription.id}:${seq}`), + text: [ + `Update on thread ${title} (${watchedThreadId}), which you subscribed to:`, + ...decision.summaries, + ].join("\n"), + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: decision.summaries[0] ?? "thread event", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription wake failed", { + id: subscription.id, + threadId: subscription.subscriberThreadId, + cause, + }), + ), + ); } if (decision.expire) { yield* store.remove(subscription.subscriberThreadId, subscription.id).pipe( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 30ab333c6ba15..38791bac6ea42 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13,6 +13,7 @@ import { nextFounderSeenMessage, nextFounderVisits, rewindFounderVisit, + redirectLinkError, routeThreadInbox, type ThreadInbox, } from "@t3tools/contracts"; @@ -5096,6 +5097,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is no longer empty.`, }); } + // A tombstone must never loop or lead nowhere, or every wake aimed at the thread would fail. + if (command.type === "thread.metadata.update" && command.replacedByThreadId != null) { + const linkError = yield* redirectLinkError( + (id) => projectionStore.getThreadShell(id), + command.threadId, + command.replacedByThreadId, + ).pipe(mapDispatchError(command)); + if (linkError !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: linkError, + }); + } + } if (command.type === "thread.archive" && thread.archivedAt !== null) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, @@ -5669,10 +5685,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; } case "thread.delegation-nudge.set": { - const thresholds = - command.thresholds ?? - thread.delegationNudge?.thresholds ?? - [...DEFAULT_DELEGATION_NUDGE_THRESHOLDS]; + const thresholds = command.thresholds ?? + thread.delegationNudge?.thresholds ?? [...DEFAULT_DELEGATION_NUDGE_THRESHOLDS]; return { ...thread, delegationNudge: { @@ -5744,6 +5758,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { inbox: askedInbox(thread.inbox, command, now) }), ...(command.title === undefined ? {} : { title: command.title }), + ...(command.replacedByThreadId === undefined + ? {} + : command.replacedByThreadId === null + ? { replacedByThreadId: null, retiredAt: null } + : { + replacedByThreadId: command.replacedByThreadId, + // Re-pointing a retired thread keeps its original retirement time. + retiredAt: thread.retiredAt ?? now, + }), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && limitRecovery?.snooze === true && @@ -7707,6 +7730,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } } + // Backstop for the redirect: every entrypoint resolves a retired thread to its replacement before + // it dispatches, so a message that still arrives here must fail closed, never start a turn. + if (command.humanNote !== true && projection.thread.replacedByThreadId != null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is retired; its replacement is ${projection.thread.replacedByThreadId}.`, + }); + } if (command.steerFollowUpOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); if ( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2e68921fd20ce..2778e4d586f90 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1975,6 +1975,12 @@ export function threadShellFromProjection( ...(projection.thread.delegationNudge ? { delegationNudge: projection.thread.delegationNudge } : {}), + ...(projection.thread.replacedByThreadId + ? { + replacedByThreadId: projection.thread.replacedByThreadId, + retiredAt: projection.thread.retiredAt ?? null, + } + : {}), lastVisitedAt: projection.thread.lastVisitedAt, ...(projection.thread.visitsByFounder === undefined ? {} @@ -2295,6 +2301,12 @@ function shellFromState(input: { ...(input.state.thread.delegationNudge ? { delegationNudge: input.state.thread.delegationNudge } : {}), + ...(input.state.thread.replacedByThreadId + ? { + replacedByThreadId: input.state.thread.replacedByThreadId, + retiredAt: input.state.thread.retiredAt ?? null, + } + : {}), lastVisitedAt: input.state.thread.lastVisitedAt, opens: input.state.thread.opens ?? null, titleRegeneration: input.state.thread.titleRegeneration ?? null, diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index d83f2d10df57f..6257d584f7c3c 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -54,6 +54,7 @@ import { withCursor, } from "./eventSubscription.ts"; import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; +import { resolveWakeTarget } from "./RetiredThreadRedirect.ts"; import type { EventSubscription } from "@t3tools/contracts"; /** Checks take minutes; faster sweeps waste the account's shared host quota. */ @@ -116,6 +117,8 @@ interface Wake { readonly notification: OrchestrationV2Notification; readonly includesRemarks?: boolean; readonly staleProgressAt?: string; + /** Set when an event subscription row, not the plain watch, produced this wake. */ + readonly subscriptionId?: string; } /** A wake a pass holds back so each thread gets one for everything the pass found. */ @@ -336,7 +339,8 @@ export const make = Effect.gen(function* () { endedWatch?: ThreadPullRequestWatch, ) { const uuid = yield* random.uuidV4(); - return yield* engine.dispatch({ + const route = wake === undefined ? undefined : yield* routeWake(target, wake); + const synced = yield* engine.dispatch({ type: "thread.pull-request-watch.sync", commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`), threadId: target.thread.id, @@ -351,18 +355,78 @@ export const make = Effect.gen(function* () { ...(wake.staleProgressAt === undefined ? {} : { staleProgressAt: wake.staleProgressAt }), - wake: { - text: wake.text, - notification: wake.notification, - ...(wake.includesRemarks === undefined - ? {} - : { includesRemarks: wake.includesRemarks }), - messageId: MessageId.make(`message:pr-watch:${uuid}`), - }, + // A retired thread's wake is delivered below, so the sync only advances its cursor. + ...(route === "here" + ? { + wake: { + text: wake.text, + notification: wake.notification, + ...(wake.includesRemarks === undefined + ? {} + : { includesRemarks: wake.includesRemarks }), + messageId: MessageId.make(`message:pr-watch:${uuid}`), + }, + } + : {}), }), }); + if (wake !== undefined && route !== "here" && route !== "dropped") { + // Sent after the sync commits, so a watch that ended while it was read sends nothing. The + // wake has no pull request stamp: the replacement thread does not watch this pull request. + yield* engine + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:pr-watch-redirect:${route.threadId}:${uuid}`), + threadId: route.threadId, + messageId: MessageId.make(`message:pr-watch:${uuid}`), + text: wake.text, + notification: wake.notification, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("redirected pull request wake was not delivered", { + retiredThreadId: target.thread.id, + redirectedToThreadId: route.threadId, + cause, + }), + ), + ); + } + return synced; }); + /** + * Where a wake for this watch goes: `here`, or the live replacement of a retired thread. A + * retired thread's chain that loops or dead-ends drops the wake (`dropped`) with a warning; it + * never starts a turn on the retired thread. + */ + const routeWake = (target: WatchTarget, wake: Wake) => + resolveWakeTarget( + (threadId) => engine.getThreadShell(threadId), + target.thread.id, + wake.subscriptionId === undefined + ? { sourceKind: "pr_watch", prUrl: target.link.url } + : { sourceKind: "event", subscriptionId: wake.subscriptionId, prUrl: target.link.url }, + ).pipe( + Effect.map((resolved) => (resolved.redirected ? resolved : ("here" as const))), + Effect.catchTag("ThreadRedirectError", (error) => + Effect.logWarning("pull request wake dropped: retired thread has no live replacement", { + threadId: target.thread.id, + reason: error.reason, + }).pipe(Effect.as("dropped" as const)), + ), + ); + + const isRetired = (threadId: ThreadId) => + engine.getThreadShell(threadId).pipe( + Effect.map((shell) => shell?.replacedByThreadId != null), + Effect.orElseSucceed(() => false), + ); + const giveUp = (target: WatchTarget) => record(target, null, { text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because it failed to read it from the host ${READ_FAILURE_LIMIT} times in a row. Check it yourself, and call watch_pull_request only if it is still open.`, @@ -546,23 +610,36 @@ export const make = Effect.gen(function* () { rest.length === 0 ? sendOne(first!) : // A watch that ended or moved during the pass fails the whole command; each then - // goes on its own, as the orchestrator decides for it alone. - sendTogether([first!, ...rest]).pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - () => Effect.forEach([first!, ...rest], sendOne, { discard: true }), + // goes on its own, as the orchestrator decides for it alone. A retired thread's + // wakes always go one by one, each to the replacement. + isRetired(first!.target.thread.id).pipe( + Effect.flatMap((retired) => + retired + ? Effect.forEach([first!, ...rest], sendOne, { discard: true }) + : sendTogether([first!, ...rest]).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.forEach([first!, ...rest], sendOne, { discard: true }), + ), + ), ), ), { discard: true }, ); }); - const closed = (groupKey: string, target: WatchTarget, pending: readonly string[] = []) => + const closed = ( + groupKey: string, + target: WatchTarget, + pending: readonly string[] = [], + subscriptionId?: string, + ) => hold({ groupKey, target, next: null, wake: { + ...(subscriptionId === undefined ? {} : { subscriptionId }), text: [ `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`, ...pending, @@ -631,7 +708,7 @@ export const make = Effect.gen(function* () { const finishClosed = Effect.fnUntraced(function* (groupKey: string, target: WatchTarget) { const loaded = yield* loadSubscription(target); const pending = loaded.mode === "row" ? loaded.row.pendingSummaries : []; - yield* closed(groupKey, target, pending); + yield* closed(groupKey, target, pending, loaded.mode === "row" ? loaded.row.id : undefined); if (loaded.mode === "row" && loaded.row.delivery.autoExpireOnClose) { yield* dropSubscription(loaded.row); } @@ -669,6 +746,7 @@ export const make = Effect.gen(function* () { summaries: decision.summaries, }), includesRemarks: false, + ...(loaded.mode === "row" ? { subscriptionId: loaded.row.id } : {}), } : undefined, ); @@ -955,6 +1033,7 @@ export const make = Effect.gen(function* () { summaries: decision.summaries, }), includesRemarks: decision.includesRemarks, + ...(loaded.mode === "row" ? { subscriptionId: loaded.row.id } : {}), }; const endForComments = report.exhausted && decision.includesRemarks; yield* hold( diff --git a/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts b/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts new file mode 100644 index 0000000000000..469d7b3bd167b --- /dev/null +++ b/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts @@ -0,0 +1,340 @@ +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import { + REDIRECT_LEDGER_ENV, + recordRedirectHit, + resolveWakeTarget, +} from "./RetiredThreadRedirect.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + // A retired thread must never reach a provider; opening a session here fails the test loudly. + openSession: () => Effect.die("A retired thread must not open a provider session"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "retired-thread-redirect" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +const supervised = { runtimeMode: "approval-required", interactionMode: "default" } as const; + +const createThread = (threadId: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:retired-redirect"), + title: threadId, + modelSelection: { instanceId, model: "gpt-5" }, + ...supervised, + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + }); + +let commandCounter = 0; +const retire = (threadId: ThreadId, replacedByThreadId: ThreadId | null) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + commandCounter += 1; + return yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`retire:${threadId}:${commandCounter}`), + threadId, + replacedByThreadId, + }); + }); + +const sendMessage = (threadId: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + commandCounter += 1; + return yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${threadId}:${commandCounter}`), + threadId, + messageId: MessageId.make(`message:${threadId}:${commandCounter}`), + text: "wake up", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + }); + +/** Runs the body with the redirect ledger pointed at a fresh temporary file, then removes it. */ +const withLedger = (body: (path: string) => Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-ledger-")); + const previous = process.env[REDIRECT_LEDGER_ENV]; + process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); + return { dir, previous }; + }), + ({ dir }) => body(NodePath.join(dir, "redirects.jsonl")), + ({ dir, previous }) => + Effect.sync(() => { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ); + +const readLedger = (path: string) => + NodeFS.existsSync(path) + ? NodeFS.readFileSync(path, "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as Record) + : []; + +it.layer(layerTest)("retired thread tombstone", (it) => { + it.effect("sets and clears the tombstone, keeping the original retirement time", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const old = ThreadId.make("thread:tomb-old"); + const first = ThreadId.make("thread:tomb-first"); + const second = ThreadId.make("thread:tomb-second"); + yield* createThread(old); + yield* createThread(first); + yield* createThread(second); + + yield* retire(old, first); + const retired = yield* projections.getThreadShell(old); + assert.equal(retired?.replacedByThreadId, first); + assert.isNotNull(retired?.retiredAt ?? null); + + yield* retire(old, second); + const repointed = yield* projections.getThreadShell(old); + assert.equal(repointed?.replacedByThreadId, second); + assert.deepEqual(repointed?.retiredAt, retired?.retiredAt); + + yield* retire(old, null); + const cleared = yield* projections.getThreadShell(old); + assert.isNull(cleared?.replacedByThreadId ?? null); + assert.isNull(cleared?.retiredAt ?? null); + }), + ); + + it.effect("rejects a self-redirect, a cycle, and a missing replacement", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const a = ThreadId.make("thread:link-a"); + const b = ThreadId.make("thread:link-b"); + const c = ThreadId.make("thread:link-c"); + yield* createThread(a); + yield* createThread(b); + yield* createThread(c); + const orchestrator = yield* Orchestrator.OrchestratorV2; + + const self = yield* Effect.flip(retire(a, a)); + assert.equal(self._tag, "OrchestratorDispatchError"); + + yield* retire(a, b); + yield* retire(b, c); + const cycle = yield* Effect.flip(retire(c, a)); + assert.equal(cycle._tag, "OrchestratorDispatchError"); + const direct = yield* Effect.flip(retire(b, a)); + assert.equal(direct._tag, "OrchestratorDispatchError"); + + const missing = yield* Effect.flip(retire(c, ThreadId.make("thread:link-missing"))); + assert.equal(missing._tag, "OrchestratorDispatchError"); + + // None of the refused links were recorded. + assert.isNull((yield* projections.getThreadShell(c))?.replacedByThreadId ?? null); + assert.equal((yield* projections.getThreadShell(b))?.replacedByThreadId, c); + }), + ); + + it.effect("rejects a link that would make the chain longer than the hop limit", () => + Effect.gen(function* () { + const ids = Array.from({ length: 11 }, (_, index) => ThreadId.make(`thread:deep-${index}`)); + for (const id of ids) yield* createThread(id); + // Link 0 -> 1 -> ... -> 8: eight hops, the longest allowed. + for (let index = 0; index < 8; index += 1) yield* retire(ids[index]!, ids[index + 1]!); + // Putting another thread in front would make nine. + const tooLong = yield* Effect.flip(retire(ids[10]!, ids[0]!)); + assert.equal(tooLong._tag, "OrchestratorDispatchError"); + }), + ); + + it.effect("resolves multi-hop chains and records one ledger line with ids only", () => + withLedger((path) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const a = ThreadId.make("thread:chain-a"); + const b = ThreadId.make("thread:chain-b"); + const c = ThreadId.make("thread:chain-c"); + const caller = ThreadId.make("thread:chain-caller"); + yield* createThread(a); + yield* createThread(b); + yield* createThread(c); + yield* retire(a, b); + yield* retire(b, c); + + const wake = yield* resolveWakeTarget((id) => orchestrator.getThreadShell(id), a, { + sourceKind: "thread_send", + callerThreadId: caller, + }); + assert.equal(wake.threadId, c); + assert.equal(wake.hopCount, 2); + assert.isTrue(wake.redirected); + + const lines = readLedger(path); + assert.equal(lines.length, 1); + assert.deepEqual(Object.keys(lines[0]!).toSorted(), [ + "callerThreadId", + "hopCount", + "redirectedToThreadId", + "retiredThreadId", + "sourceKind", + "timestamp", + ]); + assert.equal(lines[0]!.retiredThreadId, a); + assert.equal(lines[0]!.redirectedToThreadId, c); + assert.equal(lines[0]!.sourceKind, "thread_send"); + assert.equal(lines[0]!.callerThreadId, caller); + assert.equal(lines[0]!.hopCount, 2); + assert.isFalse(Number.isNaN(Date.parse(lines[0]!.timestamp as string))); + + // A live thread resolves to itself and writes nothing. + const live = yield* resolveWakeTarget((id) => orchestrator.getThreadShell(id), c, { + sourceKind: "event", + }); + assert.isFalse(live.redirected); + assert.equal(readLedger(path).length, 1); + }), + ), + ); + + it.effect("fails closed on a dead end and writes no ledger line", () => + withLedger((path) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const old = ThreadId.make("thread:dead-old"); + const next = ThreadId.make("thread:dead-next"); + yield* createThread(old); + yield* createThread(next); + yield* retire(old, next); + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("delete:thread:dead-next"), + threadId: next, + }); + const error = yield* Effect.flip( + resolveWakeTarget((id) => orchestrator.getThreadShell(id), old, { sourceKind: "event" }), + ); + assert.equal(error._tag, "ThreadRedirectError"); + assert.equal(readLedger(path).length, 0); + }), + ), + ); + + it.effect("refuses a message to a retired thread and starts no run there", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const old = ThreadId.make("thread:backstop-old"); + const next = ThreadId.make("thread:backstop-next"); + yield* createThread(old); + yield* createThread(next); + yield* retire(old, next); + + const refused = yield* Effect.flip(sendMessage(old)); + assert.equal(refused._tag, "OrchestratorDispatchError"); + const projection = yield* orchestrator.getThreadRecords(old, ["runs", "messages"]); + assert.equal(projection.runs.length, 0); + assert.equal(projection.messages.length, 0); + + // Clearing the tombstone makes the thread an ordinary target again. + yield* retire(old, null); + assert.isNull((yield* projections.getThreadShell(old))?.replacedByThreadId ?? null); + }), + ); +}); + +it.effect("recordRedirectHit never fails the wake when the ledger cannot be written", () => + Effect.gen(function* () { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-ledger-")); + const previous = process.env[REDIRECT_LEDGER_ENV]; + // A file where a directory is needed: the append must fail. + const blocker = NodePath.join(dir, "blocker"); + NodeFS.writeFileSync(blocker, ""); + process.env[REDIRECT_LEDGER_ENV] = NodePath.join(blocker, "nested", "redirects.jsonl"); + try { + yield* recordRedirectHit({ + retiredThreadId: ThreadId.make("thread:ledger-old"), + redirectedToThreadId: ThreadId.make("thread:ledger-new"), + sourceKind: "pr_watch", + hopCount: 1, + }); + } finally { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + } + }), +); + +it.effect("recordRedirectHit appends one line per hit and clips long fields", () => + withLedger((path) => + Effect.gen(function* () { + yield* recordRedirectHit({ + retiredThreadId: ThreadId.make("thread:l-old"), + redirectedToThreadId: ThreadId.make("thread:l-new"), + sourceKind: "event", + subscriptionId: "s".repeat(2000), + prUrl: "https://github.com/o/r/pull/1", + hopCount: 1, + }); + yield* recordRedirectHit({ + retiredThreadId: ThreadId.make("thread:l-old"), + redirectedToThreadId: ThreadId.make("thread:l-new"), + sourceKind: "schedule", + taskId: "task:1", + hopCount: 1, + }); + const lines = readLedger(path); + assert.equal(lines.length, 2); + assert.equal((lines[0]!.subscriptionId as string).length, 512); + assert.equal(lines[0]!.prUrl, "https://github.com/o/r/pull/1"); + assert.equal(lines[1]!.taskId, "task:1"); + assert.equal(NodeFS.statSync(path).mode & 0o777, 0o600); + }), + ), +); diff --git a/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts b/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts new file mode 100644 index 0000000000000..a8dee8a28e1d2 --- /dev/null +++ b/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts @@ -0,0 +1,137 @@ +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { + type RedirectSourceKind, + type ResolvedThreadTarget, + type ThreadId, + type ThreadRedirectError, + type ThreadRedirectNode, + resolveActiveThreadTargetWith, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Semaphore from "effect/Semaphore"; + +import * as ServerConfig from "../config.ts"; + +/** + * Redirect for wakes aimed at a retired thread. Each wake entrypoint (`thread_send`, `schedule`, + * `pr_watch`, `event`) resolves its target here before it dispatches, so a retired thread never + * starts a provider turn. Every redirect appends one record to the redirect ledger. + */ + +/** Where a wake came from. Ids only: the ledger never carries message text. */ +export interface RedirectWakeSource { + readonly sourceKind: RedirectSourceKind; + readonly callerThreadId?: ThreadId | undefined; + readonly taskId?: string | undefined; + readonly subscriptionId?: string | undefined; + readonly prUrl?: string | undefined; +} + +export interface RedirectLedgerRecord extends RedirectWakeSource { + readonly timestamp: string; + readonly retiredThreadId: ThreadId; + readonly redirectedToThreadId: ThreadId; + readonly hopCount: number; +} + +const LEDGER_FILE = "retired-thread-redirects.jsonl"; +/** Override for the ledger location; `scripts/standing_threads.py redirect-report` reads the same variable. */ +export const REDIRECT_LEDGER_ENV = "RETIRED_REDIRECT_LEDGER"; +/** One append is a single small line, so concurrent writers never interleave it. */ +const MAX_FIELD_LENGTH = 512; +/** The ledger keeps one rotated generation, so it stays bounded at about twice this. */ +const MAX_LEDGER_BYTES = 8 * 1024 * 1024; +const APPEND_TIMEOUT = "2 seconds"; + +const appendLock = Semaphore.makeUnsafe(1); + +const clip = (value: string) => + value.length > MAX_FIELD_LENGTH ? value.slice(0, MAX_FIELD_LENGTH) : value; + +/** The ledger path: the override when set, else the server's state directory. */ +const ledgerPath = Effect.gen(function* () { + const override = process.env[REDIRECT_LEDGER_ENV]?.trim(); + if (override) return override; + const config = yield* Effect.serviceOption(ServerConfig.ServerConfig); + return Option.isSome(config) ? NodePath.join(config.value.stateDir, LEDGER_FILE) : undefined; +}); + +const appendLine = (path: string, line: string) => + Effect.tryPromise(async () => { + await NodeFSP.mkdir(NodePath.dirname(path), { recursive: true }); + const size = await NodeFSP.stat(path).then( + (stat) => stat.size, + () => 0, + ); + if (size >= MAX_LEDGER_BYTES) await NodeFSP.rename(path, `${path}.1`); + await NodeFSP.appendFile(path, line, { encoding: "utf8", mode: 0o600 }); + }); + +/** + * Appends one redirect-hit record. Never fails and never waits long: a ledger that cannot be + * written is logged, and the wake is delivered regardless. + */ +export const recordRedirectHit = Effect.fn("RetiredThreadRedirect.recordRedirectHit")(function* ( + record: Omit, +) { + const path = yield* ledgerPath; + if (path === undefined) { + return yield* Effect.logWarning("retired-thread redirect not recorded: no ledger path"); + } + const timestamp = new Date(yield* Clock.currentTimeMillis).toISOString(); + const entry: RedirectLedgerRecord = { + timestamp, + retiredThreadId: clip(record.retiredThreadId) as ThreadId, + redirectedToThreadId: clip(record.redirectedToThreadId) as ThreadId, + sourceKind: record.sourceKind, + ...(record.callerThreadId === undefined + ? {} + : { callerThreadId: clip(record.callerThreadId) as ThreadId }), + ...(record.taskId === undefined ? {} : { taskId: clip(record.taskId) }), + ...(record.subscriptionId === undefined ? {} : { subscriptionId: clip(record.subscriptionId) }), + ...(record.prUrl === undefined ? {} : { prUrl: clip(record.prUrl) }), + hopCount: record.hopCount, + }; + yield* appendLock + .withPermits(1)(appendLine(path, `${JSON.stringify(entry)}\n`)) + .pipe( + Effect.timeout(APPEND_TIMEOUT), + Effect.catchCause((cause) => + Effect.logWarning("retired-thread redirect ledger append failed", cause), + ), + ); +}); + +export interface ResolvedWakeTarget extends ResolvedThreadTarget { + /** True when the wake was aimed at a retired thread and moved. */ + readonly redirected: boolean; +} + +/** + * The live thread a wake aimed at `threadId` must go to. A thread that is not retired resolves to + * itself with no ledger record. A retired one resolves to the end of its chain and appends a + * ledger record. Fails closed with a `ThreadRedirectError` on a cycle, a chain longer than the hop + * limit, or a replacement that is gone; the caller must then drop the wake, never deliver it. + */ +export const resolveWakeTarget = Effect.fn("RetiredThreadRedirect.resolveWakeTarget")(function* < + E, + R, +>( + lookup: (threadId: ThreadId) => Effect.Effect, + threadId: ThreadId, + source: RedirectWakeSource, +): Effect.fn.Return { + const resolved = yield* resolveActiveThreadTargetWith(lookup, threadId); + if (resolved.hopCount === 0) return { ...resolved, redirected: false }; + yield* recordRedirectHit({ + retiredThreadId: threadId, + redirectedToThreadId: resolved.threadId, + hopCount: resolved.hopCount, + ...source, + }); + return { ...resolved, redirected: true }; +}); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 8be40b9fb8f29..af6ee628dec97 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -1,4 +1,8 @@ -import { expect, it } from "@effect/vitest"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; import { CommandId, EnvironmentId, @@ -11,6 +15,7 @@ import { ProviderSessionId, type OrchestrationV2StoredEvent, type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, ProjectId, ProviderInstanceId, RunId, @@ -38,6 +43,7 @@ import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; import type { ServerProvider } from "@t3tools/contracts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; @@ -306,6 +312,7 @@ it.effect.each([ Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), Layer.provide( Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadShell: () => Effect.succeed(null), getThreadRecords: () => Effect.succeed({ thread: { @@ -1174,3 +1181,122 @@ it.effect( }).pipe(Effect.provide(layerTest)); }), ); + +describe("sendToThread to a retired thread", () => { + const projectId = ProjectId.make("project:thread-management:retired"); + const retired = ThreadId.make("thread:thread-management:retired"); + const middle = ThreadId.make("thread:thread-management:retired-middle"); + const live = ThreadId.make("thread:thread-management:retired-live"); + const shells = new Map([ + [retired, { projectId, replacedByThreadId: middle }], + [middle, { projectId, replacedByThreadId: live }], + [live, { projectId, replacedByThreadId: null }], + ]); + + const run = (input: { readonly scheduledTaskId?: string; readonly senderThreadId?: ThreadId }) => + Effect.gen(function* () { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-send-")); + const ledger = NodePath.join(dir, "redirects.jsonl"); + const previous = process.env[REDIRECT_LEDGER_ENV]; + process.env[REDIRECT_LEDGER_ENV] = ledger; + const dispatched: Array<{ type: string; threadId: string }> = []; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(ProviderRegistryMock.layer()), + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadShell: (threadId) => + Effect.succeed( + (shells.get(threadId) as unknown as OrchestrationV2ThreadShell | undefined) ?? null, + ), + getThreadRecords: (threadId) => + Effect.succeed({ + thread: { + id: threadId, + projectId, + deletedAt: null, + archivedAt: null, + worktreePath: null, + branch: null, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" }, + }, + runs: [], + providerTurns: [], + messages: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push({ type: command.type, threadId: (command as never)["threadId"] }); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + try { + const threads = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + yield* Effect.flip( + threads.sendToThread({ + projectId, + threadId: retired, + commandId: CommandId.make("command:thread-management:retired"), + messageId: MessageId.make("message:thread-management:retired"), + text: "Secret message body that never reaches the ledger.", + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "mcp", + ...input, + }), + ); + return { + dispatched, + records: NodeFS.existsSync(ledger) + ? NodeFS.readFileSync(ledger, "utf8") + .split("\n") + .filter((line) => line.length > 0) + : [], + }; + } finally { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + } + }); + + it.effect("delivers a thread_send to the live replacement and records the redirect", () => + Effect.gen(function* () { + const caller = ThreadId.make("thread:thread-management:caller"); + const { dispatched, records } = yield* run({ senderThreadId: caller }); + // The retired thread takes no command at all; the live end of the chain takes the message. + expect(dispatched.map((command) => command.threadId)).toEqual([live]); + expect(dispatched[0]?.type).toBe("message.dispatch"); + expect(records).toHaveLength(1); + expect(JSON.parse(records[0]!)).toMatchObject({ + retiredThreadId: retired, + redirectedToThreadId: live, + sourceKind: "thread_send", + callerThreadId: caller, + hopCount: 2, + }); + expect(records[0]).not.toContain("Secret message body"); + }), + ); + + it.effect("delivers a scheduled wake to the live replacement and records the task", () => + Effect.gen(function* () { + const { dispatched, records } = yield* run({ scheduledTaskId: "task:nightly" }); + expect(dispatched.map((command) => command.threadId)).toEqual([live]); + expect(JSON.parse(records[0]!)).toMatchObject({ + retiredThreadId: retired, + redirectedToThreadId: live, + sourceKind: "schedule", + taskId: "task:nightly", + }); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 4e43c231c683e..80bd0472303cb 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,5 +1,5 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; -import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts"; +import { BACKGROUND_WAIT_STALE_MINUTES, ThreadRedirectError } from "@t3tools/contracts"; import { staleTimeoutMs } from "./waitStaleness.ts"; import type { OrchestrationV2SearchThreadInput, @@ -71,6 +71,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts"; import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; +import { resolveWakeTarget } from "./RetiredThreadRedirect.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; import { projectTurnItemForDetail } from "./WireProjection.ts"; @@ -426,6 +427,7 @@ export const ThreadManagementError = Schema.Union([ ThreadManagementDurableRunProjectionError, ThreadManagementProviderInstanceDisabledError, ThreadManagementWorktreeRestoreError, + ThreadRedirectError, ]); export type ThreadManagementError = typeof ThreadManagementError.Type; @@ -1026,6 +1028,29 @@ const make = Effect.gen(function* () { const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn( "ThreadManagementService.sendToThread", )(function* (input) { + // A retired thread never takes a turn: the send goes to its replacement, which is read and + // steered or queued on its own runs. The ledger records one hit for the redirect. + const wake = yield* resolveWakeTarget( + (threadId) => orchestrator.getThreadShell(threadId), + input.threadId, + input.scheduledTaskId === undefined + ? { sourceKind: "thread_send", callerThreadId: input.senderThreadId } + : { sourceKind: "schedule", taskId: input.scheduledTaskId }, + ); + if (wake.redirected) { + const replacement = yield* orchestrator.getThreadShell(wake.threadId); + if (replacement === null) { + return yield* new ThreadManagementThreadNotFoundError({ + projectId: input.projectId, + threadId: wake.threadId, + }); + } + return yield* sendToThread({ + ...input, + projectId: replacement.projectId, + threadId: wake.threadId, + }); + } const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]); if (target.thread.archivedAt !== null) { return yield* new ThreadManagementThreadArchivedError({ diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index 5f9cef414dec1..41db10d72114b 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -14,6 +14,7 @@ import * as ThreadManagement from "./ThreadManagementService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSelectionFromCommand, refuseUnservedModel } from "../provider/servedModel.ts"; import { OrchestratorCommandRejectedError } from "./Orchestrator.ts"; +import { resolveWakeTarget } from "./RetiredThreadRedirect.ts"; // These failures precede commitCommand; generic dispatch errors can follow commits and remain ambiguous. function dispatchWasNotAccepted( @@ -32,6 +33,7 @@ function dispatchWasNotAccepted( case "OrchestratorRuntimeModeAboveCeilingError": case "ThreadManagementProviderInstanceDisabledError": case "ThreadManagementWorktreeRestoreError": + case "ThreadRedirectError": return true; default: return false; @@ -88,11 +90,52 @@ const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments return { ...command, attachments: message?.attachments ?? [] }; }); +/** + * A message aimed at a retired thread goes to its live replacement instead; the retired thread + * takes no turn. Notes, guest messages and continuations of a run on the retired thread stay put, + * and the orchestrator then refuses them rather than start a turn there. Steering or restarting + * names a run on the retired thread, so on the replacement the message queues. + */ +const redirectRetiredMessage = Effect.fn("ThreadMessageIntake.redirectRetiredMessage")(function* ( + command: Extract, +) { + if ( + command.humanNote === true || + command.guestMessageId !== undefined || + command.manualContinuationOfRunId !== undefined || + command.restartContinuationOfRunId !== undefined || + command.usageLimitContinuationOfRunId !== undefined || + command.steerFollowUpOfRunId !== undefined || + command.providerFailover !== undefined + ) { + return command; + } + const threads = yield* ThreadManagement.ThreadManagementService; + const wake = yield* resolveWakeTarget( + (threadId) => threads.getThreadShell(threadId), + command.threadId, + command.scheduledTaskId === undefined + ? { sourceKind: "thread_send", callerThreadId: command.senderThreadId } + : { sourceKind: "schedule", taskId: command.scheduledTaskId }, + ); + if (!wake.redirected) return command; + return { + ...command, + threadId: wake.threadId, + dispatchMode: + command.dispatchMode.type === "steer_active" || command.dispatchMode.type === "restart_active" + ? ({ type: "queue_after_active" } as const) + : command.dispatchMode, + }; +}); + export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* ( incoming: OrchestrationV2Command, ) { const command = - incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming; + incoming.type === "message.dispatch" + ? yield* withGuestAttachments(yield* redirectRetiredMessage(incoming)) + : incoming; const threads = yield* ThreadManagement.ThreadManagementService; const selection = modelSelectionFromCommand(command); if ( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 56c3d458fbfa4..3074db95fba0d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,3 +1,9 @@ +import * as NodeFS from "node:fs"; +import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; +import { prepareSubscribe } from "./eventSubscription.ts"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; import { makeThreadInbox } from "@t3tools/contracts"; import * as HttpClient from "effect/http/HttpClient"; @@ -5891,6 +5897,258 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("redirects a pull request watch wake from a retired thread to its replacement", () => + Effect.acquireUseRelease( + Effect.sync(() => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-pr-watch-")); + const previous = process.env[REDIRECT_LEDGER_ENV]; + process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); + return { dir, previous }; + }), + ({ dir }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const retiredId = ThreadId.make("runtime-pull-request-watch-retired"); + const liveId = ThreadId.make("runtime-pull-request-watch-replacement"); + const projectId = ProjectId.make("pr-watch-retired-project"); + yield* seedProject({ + projectId, + title: "Watch retired", + workspaceRoot: "/workspace/watch-retired", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + for (const id of [retiredId, liveId]) { + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-retired-create-${id}`), + threadId: id, + projectId, + title: id, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + } + const prUrl = "https://github.com/pingdotgg/t3code/pull/31"; + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-retired-start"), + threadId: retiredId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 31, + watching: true, + link: { url: prUrl, source: "agent" }, + }); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("pr-watch-retired-tombstone"), + threadId: retiredId, + replacedByThreadId: liveId, + }); + + let status: "pending" | "success" = "pending"; + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Effect.sync(() => ({ + ...watchedPullRequestDetail({ + projectId, + number: 31, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "retired31aaa", + checks: [{ name: "test", status, description: null, url: null, required: true }], + })), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const summaries = (threadId: ThreadId) => + Effect.map(orchestrator.getThreadRecords(threadId, ["messages"]), ({ messages }) => + messages.flatMap((message) => message.notification?.summary ?? []), + ); + + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + yield* worker.drain(); + status = "success"; + yield* TestClock.adjust("10 minutes"); + yield* reactor.sweep; + yield* worker.drain(); + + assert.deepEqual(yield* summaries(liveId), ["#31: checks passed"]); + // The retired thread took no message and no run. + const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); + assert.lengthOf(retired.messages, 0); + assert.lengthOf(retired.runs, 0); + + const ledger = NodePath.join(dir, "redirects.jsonl"); + const records = NodeFS.readFileSync(ledger, "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as Record); + assert.isAtLeast(records.length, 1); + for (const record of records) { + assert.equal(record.sourceKind, "pr_watch"); + assert.equal(record.retiredThreadId, retiredId); + assert.equal(record.redirectedToThreadId, liveId); + assert.equal(record.prUrl, prUrl); + } + }), + ({ dir, previous }) => + Effect.sync(() => { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ), + ); + + it.effect("redirects a pull request event subscription wake from a retired thread", () => + Effect.acquireUseRelease( + Effect.sync(() => { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-pr-event-")); + const previous = process.env[REDIRECT_LEDGER_ENV]; + process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); + return { dir, previous }; + }), + ({ dir }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const retiredId = ThreadId.make("runtime-pr-event-retired"); + const liveId = ThreadId.make("runtime-pr-event-replacement"); + const projectId = ProjectId.make("pr-event-retired-project"); + yield* seedProject({ + projectId, + title: "Event retired", + workspaceRoot: "/workspace/event-retired", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + for (const id of [retiredId, liveId]) { + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-event-create-${id}`), + threadId: id, + projectId, + title: id, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + } + const prUrl = "https://github.com/pingdotgg/t3code/pull/32"; + const prepared = prepareSubscribe({ + id: "evt_retired_1", + subscriberThreadId: retiredId, + selector: { entity: "pull_request", by: "url", url: prUrl }, + events: [{ name: "merged" }], + createdAt: "2026-10-02T11:00:00.000Z", + }); + assert.isTrue(prepared.ok); + if (!prepared.ok) return; + // The subscription table lives in its own in-memory database, shared by the put and the reactor. + const store = yield* EventSubscriptionStore.EventSubscriptionStore.pipe( + Effect.provide( + EventSubscriptionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), + ); + yield* store.put(prepared.subscription); + // The subscription rides on the thread's pull request watch. + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-event-watch"), + threadId: retiredId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 32, + watching: true, + link: { url: prUrl, source: "agent" }, + }); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("pr-event-tombstone"), + threadId: retiredId, + replacedByThreadId: liveId, + }); + + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(EventSubscriptionStore.EventSubscriptionStore, store), + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Effect.succeed({ + ...watchedPullRequestDetail({ + projectId, + number: 32, + at: "2026-10-02T12:00:00.000Z", + }), + state: "merged" as const, + mergedAt: "2026-10-02T12:00:00.000Z", + }), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + yield* worker.drain(); + + const delivered = yield* orchestrator.getThreadRecords(liveId, ["messages"]); + assert.isAtLeast(delivered.messages.length, 1); + const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); + assert.lengthOf(retired.messages, 0); + assert.lengthOf(retired.runs, 0); + + const records = NodeFS.readFileSync(NodePath.join(dir, "redirects.jsonl"), "utf8") + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as Record); + assert.isAtLeast(records.length, 1); + for (const record of records) { + assert.equal(record.sourceKind, "event"); + assert.equal(record.subscriptionId, "evt_retired_1"); + assert.equal(record.retiredThreadId, retiredId); + assert.equal(record.redirectedToThreadId, liveId); + assert.equal(record.prUrl, prUrl); + } + }), + ({ dir, previous }) => + Effect.sync(() => { + if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; + else process.env[REDIRECT_LEDGER_ENV] = previous; + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ), + ); + it.effect.each(["pending", "action-required"] as const)("recovers %s watches", (initialStatus) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -6442,6 +6700,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { // Events come from a queue that exists before the reactor subscribes, so none is missed. Layer.mock(Orchestrator.OrchestratorV2)({ dispatch: orchestrator.dispatch, + getThreadShell: orchestrator.getThreadShell, streamDomainEvents: Stream.fromQueue(domainEvents), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index d5a4d85b3f5ca..8574b00a27ff2 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -432,6 +432,20 @@ can take a steer without interrupting the tool in progress, and otherwise waits for the next run. The stored setting records who changed it. A thread cannot change its own: the caller has to be another thread or a client. +`set_redirect` retires a thread behind a replacement: `replacedByThreadId` names +the replacement, and `null` clears the tombstone. A retired thread takes no +provider turn. Every `t3_thread_send`, scheduled task, pull request watch and +event subscription aimed at it goes to the live thread at the end of its chain +(at most 8 hops) and appends one line to the redirect ledger, +`/retired-thread-redirects.jsonl` unless `RETIRED_REDIRECT_LEDGER` +names another file. A line holds ids, the source kind and a timestamp, never +message text. The write is refused for a self-redirect, a missing or deleted +replacement, or a link that would close a loop or lengthen a chain past the +limit. A chain that cannot be resolved later fails closed: the wake is dropped +or refused, never delivered to the retired thread. Work already queued or +running when the tombstone is written is not cancelled, and a continuation of a +retired thread's own run is refused rather than redirected. + The result includes the command ID and durable event sequence together with the resultant title, title-regeneration marker, and linked pull request. Reusing a `clientRequestId` for the same action and thread replays the same command diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index a105f5a65fe1c..c702a4a709888 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -52,6 +52,7 @@ export * from "./eventSubscription.ts"; export * from "./threadSearch.ts"; export * from "./threadTags.ts"; export * from "./threadStanding.ts"; +export * from "./threadRedirect.ts"; export * from "./delegationNudge.ts"; export * from "./threadTitle.ts"; export * from "./t3ProjectFile.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6230383c9a84c..ac769e2ef0653 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -571,6 +571,13 @@ export const OrchestrationV2AppThread = Schema.Struct({ standing: Schema.optional(StoredThreadStanding), /** Opt-in reminder to delegate once the thread does work itself; absent or null is off. */ delegationNudge: Schema.optional(StoredThreadDelegationNudge), + /** + * Retirement tombstone. When set, the thread is retired: no wake may start a provider turn on it, + * and every wake aimed at it is redirected to this thread (following its own chain). + */ + replacedByThreadId: Schema.optional(Schema.NullOr(ThreadId)), + /** When the tombstone was written; absent or null on a live thread. */ + retiredAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), @@ -2613,6 +2620,9 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ standing: Schema.optional(StoredThreadStanding), /** Opt-in reminder to delegate; absent or null is off. */ delegationNudge: Schema.optional(StoredThreadDelegationNudge), + /** Retirement tombstone; see the app thread. */ + replacedByThreadId: Schema.optional(Schema.NullOr(ThreadId)), + retiredAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), /** Per-founder read cursors. Older servers omit them; clients then keep the shared cursor. */ visitsByFounder: Schema.optional(FounderVisits), @@ -2805,6 +2815,7 @@ export const OrchestrationV2AppThreadJson = OrchestrationV2AppThread.mapFields(( lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), + retiredAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), lastVisitedAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), @@ -3275,6 +3286,7 @@ export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFiel snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), + retiredAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), visitsByFounder: Schema.optional(FounderVisitsJson), titleRegeneration: Schema.optional( @@ -3689,6 +3701,8 @@ export const OrchestrationV2Command = Schema.Union([ limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)), /** Link (object) or unlink (null) a pull request; absent leaves it unchanged. */ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + /** Retire the thread behind this replacement (stamps `retiredAt`), or null to clear the tombstone. */ + replacedByThreadId: Schema.optional(Schema.NullOr(ThreadId)), }), Schema.Struct({ type: Schema.Literal("thread.pull-request.link"), diff --git a/packages/contracts/src/threadMetadataMcp.ts b/packages/contracts/src/threadMetadataMcp.ts index e0b5058e520f4..650c620edcdb0 100644 --- a/packages/contracts/src/threadMetadataMcp.ts +++ b/packages/contracts/src/threadMetadataMcp.ts @@ -51,6 +51,7 @@ export const ThreadMetadataMcpAction = Schema.Literals([ "resolve_decision", "set_standing", "set_delegation_nudge", + "set_redirect", ]); export type ThreadMetadataMcpAction = typeof ThreadMetadataMcpAction.Type; @@ -72,6 +73,12 @@ export const ThreadMetadataMcpUpdateInput = Schema.Struct({ "Required only when action is set_delegation_nudge: {enabled, thresholds?}. When on, the thread is reminded to delegate after that many of its own tool calls in one request (default [5, 10]). A thread cannot change its own setting.", }), ), + replacedByThreadId: Schema.optional( + Schema.NullOr(ThreadId).annotate({ + description: + "Required only when action is set_redirect: the live thread that replaces this retired one. Every wake aimed at this thread (t3_thread_send, schedules, PR watches, event subscriptions) is redirected there and no provider turn ever starts here. null clears the tombstone. Self-redirects and cycles are rejected.", + }), + ), clientRequestId: Schema.optional(ThreadMetadataClientRequestId), }).check( Schema.makeFilter((input) => @@ -79,9 +86,10 @@ export const ThreadMetadataMcpUpdateInput = Schema.Struct({ (input.action === "route") === (input.inboxRouting !== undefined) && (input.action === "request_decision") === (input.decision !== undefined) && (input.action === "set_standing") === (input.standing !== undefined) && - (input.action === "set_delegation_nudge") === (input.delegationNudge !== undefined) + (input.action === "set_delegation_nudge") === (input.delegationNudge !== undefined) && + (input.action === "set_redirect") === (input.replacedByThreadId !== undefined) ? true - : "rename requires title; route requires inboxRouting; request_decision requires decision; set_standing requires standing; set_delegation_nudge requires delegationNudge; other actions reject those fields.", + : "rename requires title; route requires inboxRouting; request_decision requires decision; set_standing requires standing; set_delegation_nudge requires delegationNudge; set_redirect requires replacedByThreadId (null clears); other actions reject those fields.", ), ); export type ThreadMetadataMcpUpdateInput = typeof ThreadMetadataMcpUpdateInput.Type; @@ -97,6 +105,8 @@ export const ThreadMetadataMcpUpdateResult = Schema.Struct({ inbox: Schema.optionalKey(ThreadInbox), standing: Schema.optionalKey(StoredThreadStanding), delegationNudge: Schema.optionalKey(StoredThreadDelegationNudge), + replacedByThreadId: Schema.optionalKey(Schema.NullOr(ThreadId)), + retiredAt: Schema.optionalKey(Schema.NullOr(IsoDateTime)), updatedAt: IsoDateTime, }); export type ThreadMetadataMcpUpdateResult = typeof ThreadMetadataMcpUpdateResult.Type; diff --git a/packages/contracts/src/threadRedirect.test.ts b/packages/contracts/src/threadRedirect.test.ts new file mode 100644 index 0000000000000..d12e68b04a887 --- /dev/null +++ b/packages/contracts/src/threadRedirect.test.ts @@ -0,0 +1,173 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { ThreadId } from "./baseSchemas.ts"; +import { + MAX_REDIRECT_HOPS, + redirectLinkError, + resolveActiveThreadTargetWith, + type ThreadRedirectNode, +} from "./threadRedirect.ts"; + +const id = (name: string) => ThreadId.make(`thread:${name}`); + +/** A thread table: `name -> replacement name` for a retired thread, `null` for a live one. */ +const table = (links: Record, deleted: ReadonlyArray = []) => { + const lookups: string[] = []; + const lookup = (threadId: ThreadId) => + Effect.sync((): ThreadRedirectNode | null => { + lookups.push(threadId); + const name = threadId.replace("thread:", ""); + if (!(name in links)) return null; + const next = links[name]; + return { + replacedByThreadId: next === null || next === undefined ? null : id(next), + deletedAt: deleted.includes(name) ? "2026-01-01T00:00:00.000Z" : null, + }; + }); + return { lookup, lookups }; +}; + +const chain = (length: number) => + Object.fromEntries( + Array.from({ length: length + 1 }, (_, index) => [ + `n${index}`, + index === length ? null : `n${index + 1}`, + ]), + ); + +describe("resolveActiveThreadTargetWith", () => { + it.effect("resolves a live thread to itself in one read", () => + Effect.gen(function* () { + const { lookup, lookups } = table({ live: null }); + const target = yield* resolveActiveThreadTargetWith(lookup, id("live")); + expect(target).toEqual({ threadId: id("live"), hopCount: 0, retiredChain: [] }); + expect(lookups).toHaveLength(1); + }), + ); + + it.effect("leaves a missing thread to the caller's own not-found handling", () => + Effect.gen(function* () { + const { lookup } = table({}); + const target = yield* resolveActiveThreadTargetWith(lookup, id("ghost")); + expect(target.threadId).toBe(id("ghost")); + expect(target.hopCount).toBe(0); + }), + ); + + it.effect("follows several hops to the live replacement", () => + Effect.gen(function* () { + const { lookup } = table({ a: "b", b: "c", c: "d", d: null }); + const target = yield* resolveActiveThreadTargetWith(lookup, id("a")); + expect(target).toEqual({ + threadId: id("d"), + hopCount: 3, + retiredChain: [id("a"), id("b"), id("c")], + }); + }), + ); + + it.effect("follows exactly the maximum number of hops", () => + Effect.gen(function* () { + const { lookup } = table(chain(MAX_REDIRECT_HOPS)); + const target = yield* resolveActiveThreadTargetWith(lookup, id("n0")); + expect(target.threadId).toBe(id(`n${MAX_REDIRECT_HOPS}`)); + expect(target.hopCount).toBe(MAX_REDIRECT_HOPS); + }), + ); + + it.effect("fails closed past the maximum number of hops", () => + Effect.gen(function* () { + const { lookup } = table(chain(MAX_REDIRECT_HOPS + 1)); + const error = yield* Effect.flip(resolveActiveThreadTargetWith(lookup, id("n0"))); + expect(error._tag).toBe("ThreadRedirectError"); + expect(error.reason).toBe("too_deep"); + }), + ); + + it.effect("fails closed on a cycle", () => + Effect.gen(function* () { + const { lookup } = table({ a: "b", b: "c", c: "a" }); + const error = yield* Effect.flip(resolveActiveThreadTargetWith(lookup, id("a"))); + expect(error.reason).toBe("cycle"); + expect(error.chain).toEqual([id("a"), id("b"), id("c"), id("a")]); + }), + ); + + it.effect("fails closed on a self-redirect", () => + Effect.gen(function* () { + const { lookup } = table({ a: "a" }); + const error = yield* Effect.flip(resolveActiveThreadTargetWith(lookup, id("a"))); + expect(error.reason).toBe("cycle"); + }), + ); + + it.effect("fails closed when the replacement is missing", () => + Effect.gen(function* () { + const { lookup } = table({ a: "gone" }); + const error = yield* Effect.flip(resolveActiveThreadTargetWith(lookup, id("a"))); + expect(error.reason).toBe("dead_end"); + }), + ); + + it.effect("fails closed when the replacement is deleted", () => + Effect.gen(function* () { + const { lookup } = table({ a: "b", b: null }, ["b"]); + const error = yield* Effect.flip(resolveActiveThreadTargetWith(lookup, id("a"))); + expect(error.reason).toBe("dead_end"); + }), + ); +}); + +describe("redirectLinkError", () => { + it.effect("accepts a live replacement", () => + Effect.gen(function* () { + const { lookup } = table({ old: null, next: null }); + expect(yield* redirectLinkError(lookup, id("old"), id("next"))).toBeNull(); + }), + ); + + it.effect("refuses a self-redirect", () => + Effect.gen(function* () { + const { lookup } = table({ old: null }); + expect(yield* redirectLinkError(lookup, id("old"), id("old"))).toMatch(/itself/); + }), + ); + + it.effect("refuses a missing or deleted replacement", () => + Effect.gen(function* () { + const { lookup } = table({ old: null, gone: null }, ["gone"]); + expect(yield* redirectLinkError(lookup, id("old"), id("nowhere"))).toMatch(/not found/); + expect(yield* redirectLinkError(lookup, id("old"), id("gone"))).toMatch(/not found/); + }), + ); + + it.effect("refuses a link that would close a loop", () => + Effect.gen(function* () { + // b -> c already; retiring c behind b would loop. + const { lookup } = table({ b: "c", c: null }); + expect(yield* redirectLinkError(lookup, id("c"), id("b"))).toMatch(/cycle/); + }), + ); + + it.effect("refuses a link that would make the chain too long", () => + Effect.gen(function* () { + const { lookup } = table({ head: null, ...chain(MAX_REDIRECT_HOPS + 1) }); + expect(yield* redirectLinkError(lookup, id("head"), id("n0"))).toMatch(/longer/); + }), + ); + + it.effect("refuses a link whose replacement already has the longest chain", () => + Effect.gen(function* () { + const { lookup } = table({ head: null, ...chain(MAX_REDIRECT_HOPS) }); + expect(yield* redirectLinkError(lookup, id("head"), id("n0"))).toMatch(/longer/); + }), + ); + + it.effect("accepts a link that lands exactly on the limit", () => + Effect.gen(function* () { + const { lookup } = table({ head: null, ...chain(MAX_REDIRECT_HOPS - 1) }); + expect(yield* redirectLinkError(lookup, id("head"), id("n0"))).toBeNull(); + }), + ); +}); diff --git a/packages/contracts/src/threadRedirect.ts b/packages/contracts/src/threadRedirect.ts new file mode 100644 index 0000000000000..4f935bb6e5779 --- /dev/null +++ b/packages/contracts/src/threadRedirect.ts @@ -0,0 +1,128 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { ThreadId } from "./baseSchemas.ts"; + +/** + * A retired thread carries a tombstone: `replacedByThreadId` names the thread that took over. + * Every wake aimed at a retired thread follows that chain to the live thread at its end, and no + * wake ever starts a provider turn on a retired one. + */ + +/** The longest chain a wake follows before it fails closed. */ +export const MAX_REDIRECT_HOPS = 8; + +/** Which wake entrypoint reached a retired thread; recorded in the redirect ledger. */ +export const RedirectSourceKind = Schema.Literals(["thread_send", "schedule", "pr_watch", "event"]); +export type RedirectSourceKind = typeof RedirectSourceKind.Type; + +/** + * - `cycle`: the chain revisits a thread. + * - `too_deep`: the chain is longer than `MAX_REDIRECT_HOPS`. + * - `dead_end`: a replacement is missing or deleted, so there is no live thread to deliver to. + */ +export const ThreadRedirectFailureReason = Schema.Literals(["cycle", "too_deep", "dead_end"]); +export type ThreadRedirectFailureReason = typeof ThreadRedirectFailureReason.Type; + +export class ThreadRedirectError extends Schema.TaggedError()( + "ThreadRedirectError", + { + threadId: ThreadId, + reason: ThreadRedirectFailureReason, + /** The retired threads visited, in order, ending at the one that failed. */ + chain: Schema.Array(ThreadId), + }, +) { + override get message(): string { + const path = this.chain.join(" -> "); + switch (this.reason) { + case "cycle": + return `Thread ${this.threadId} is retired and its redirect chain loops (${path}).`; + case "too_deep": + return `Thread ${this.threadId} is retired and its redirect chain is longer than ${MAX_REDIRECT_HOPS} hops (${path}).`; + case "dead_end": + return `Thread ${this.threadId} is retired and its replacement is missing or deleted (${path}).`; + } + } +} + +/** The part of a thread the resolver reads. `null` from a lookup means the thread does not exist. */ +export interface ThreadRedirectNode { + readonly replacedByThreadId?: ThreadId | null | undefined; + readonly deletedAt?: unknown; +} + +export interface ResolvedThreadTarget { + /** The live thread to deliver to; the input thread itself when it is not retired. */ + readonly threadId: ThreadId; + /** Number of redirects followed; 0 when the thread is not retired. */ + readonly hopCount: number; + /** Every retired thread passed through, in order. Empty when `hopCount` is 0. */ + readonly retiredChain: ReadonlyArray; +} + +/** + * Follows `replacedByThreadId` from `threadId` to the live thread at the end of the chain. + * Fails closed with a `ThreadRedirectError` on a cycle, a chain longer than `MAX_REDIRECT_HOPS`, + * or a replacement that is missing or deleted. A thread that is not retired resolves to itself, + * even if it is missing: the caller's own not-found handling applies there, not a redirect. + */ +export const resolveActiveThreadTargetWith = ( + lookup: (threadId: ThreadId) => Effect.Effect, + threadId: ThreadId, +): Effect.Effect => + Effect.gen(function* () { + const retiredChain: ThreadId[] = []; + const seen = new Set(); + let current = threadId; + let node = yield* lookup(current); + for (;;) { + const next = node?.replacedByThreadId ?? null; + if (next === null) { + return { threadId: current, hopCount: retiredChain.length, retiredChain }; + } + seen.add(current); + retiredChain.push(current); + const fail = (reason: ThreadRedirectFailureReason) => + new ThreadRedirectError({ threadId, reason, chain: [...retiredChain, next] }); + if (seen.has(next)) return yield* fail("cycle"); + if (retiredChain.length > MAX_REDIRECT_HOPS) return yield* fail("too_deep"); + const target = yield* lookup(next); + if (target === null || (target.deletedAt ?? null) !== null) { + return yield* fail("dead_end"); + } + current = next; + node = target; + } + }); + +/** + * Write-time check for retiring `threadId` behind `replacementId`. Returns the reason the link is + * refused, or `null` when it is safe. A self-redirect or a replacement whose chain leads back to + * `threadId` would loop; a missing or deleted replacement would dead-end every wake. + */ +export const redirectLinkError = ( + lookup: (threadId: ThreadId) => Effect.Effect, + threadId: ThreadId, + replacementId: ThreadId, +): Effect.Effect => + Effect.gen(function* () { + if (replacementId === threadId) return "A thread cannot be redirected to itself."; + const replacement = yield* lookup(replacementId); + if (replacement === null || (replacement.deletedAt ?? null) !== null) { + return `Replacement thread ${replacementId} was not found.`; + } + // Pretend the link exists and walk from the replacement: reaching threadId would close a loop. + const seen = new Set([threadId]); + let current = replacementId; + // The new link adds one hop in front of the replacement's own chain. + for (let hop = 0; hop < MAX_REDIRECT_HOPS; hop += 1) { + if (seen.has(current)) return "That redirect would create a cycle."; + seen.add(current); + const node = yield* lookup(current); + const next = node?.replacedByThreadId ?? null; + if (next === null) return null; + current = next; + } + return `That redirect chain would be longer than ${MAX_REDIRECT_HOPS} hops.`; + }); From 266c139e996f5ba0d352f6d5bdfdb456d6b9935e Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:12:02 +0000 Subject: [PATCH 2/2] fix(server): gate set_redirect to admins, re-check limits on redirected sends, typecheck clean Addresses the cross-family review of the retired-thread redirect (CLO-1001): - F1: set_redirect (set or clear) now needs a full-access, default-mode caller (thread and client ceiling). thread_send re-validates the resolved live replacement against the caller's runtime/interaction limits and live-caller check before sending, so a redirect cannot reach a wider-mode thread. - F2: server typecheck exits 0. Ledger code uses Effect Config/FileSystem/Path instead of node builtins and process.env; tests use a shared withRedirectLedger helper; PullRequestWatchReactor narrows `route`, imports ThreadId; ModelAlertReactor takes the orchestrator's getThreadShell type. - F3: thread_send returns the live thread that took the message and retries failed worktree setup against it. - F4: redirectLinkError walks downstream and rejects a chain ending at a missing or deleted thread. Regression tests: set_redirect authority matrix, resolved-target limit refusal, live-thread result and setup retry, downstream chain validation. Model: claude-sonnet-5-5 Task: CLO-1001 Agent: claude-code Co-Authored-By: Claude Sonnet 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 121 +++++ apps/server/src/mcp/OrchestratorMcpService.ts | 40 +- .../src/mcp/ThreadMetadataMcpService.test.ts | 182 ++++++++ .../src/mcp/ThreadMetadataMcpService.ts | 38 +- .../ModelAlertReactor.test.ts | 27 +- .../src/orchestration-v2/ModelAlertReactor.ts | 5 +- .../PullRequestWatchReactor.ts | 3 +- .../RetiredThreadRedirect.test.ts | 76 +-- .../orchestration-v2/RetiredThreadRedirect.ts | 59 ++- .../ThreadManagementService.test.ts | 123 +++-- .../src/orchestration-v2/runtimeLayer.test.ts | 436 ++++++++---------- .../testkit/RedirectLedger.ts | 63 +++ packages/contracts/src/threadRedirect.test.ts | 14 + packages/contracts/src/threadRedirect.ts | 9 +- 14 files changed, 778 insertions(+), 418 deletions(-) create mode 100644 apps/server/src/mcp/ThreadMetadataMcpService.test.ts create mode 100644 apps/server/src/orchestration-v2/testkit/RedirectLedger.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f1fea0ef040f7..93fe7203f909a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -4876,6 +4876,127 @@ describe("OrchestratorMcpService thread lookup", () => { }), ); + describe("sending to a retired thread", () => { + const retiredShell = ( + replacedBy: ThreadId, + modes: Parameters[1] = {}, + ) => ({ + ...liveThreadShell(ThreadId.make("thread:retired-bot"), { activeRunId: null, ...modes }), + replacedByThreadId: replacedBy, + }); + const asThread = (threadId: ThreadId): McpInvocationScope => ({ + ...client, + requestNamespace: `provider:${threadId}`, + thread: { + threadId, + providerSessionId: `provider:${threadId}`, + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + }); + + it.effect("refuses a redirect whose live replacement is above the caller's limits", () => + Effect.gen(function* () { + const caller = liveThreadShell(ThreadId.make("thread:limited-caller"), { + runtimeMode: "auto", + }); + const live = liveThreadShell(ThreadId.make("thread:wide-replacement"), { + activeRunId: null, + runtimeMode: "full-access", + }); + // The retired thread itself is within the caller's limits; only its replacement is not. + const retired = retiredShell(live.id, { runtimeMode: "auto" }); + const sent = yield* Ref.make(0); + const error = yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* mcp + .sendToThread(asThread(caller.id), { threadId: retired.id, message: "hello" }) + .pipe(Effect.flip); + }).pipe( + Effect.provide( + service([caller, retired, live], sent, { + getThreadRecords: () => Effect.succeed(idleThreadProjection(caller)), + getProjectThreadRecords: (input) => + Effect.succeed( + idleThreadProjection(input.threadId === retired.id ? retired : live), + ), + }), + ), + ); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.include(error.message, live.id); + assert.include(error.message, "above this caller's"); + assert.equal(yield* Ref.get(sent), 0); + }), + ); + + it.effect("reports the live thread that took the message and retries setup there", () => + Effect.gen(function* () { + const live = liveThreadShell(ThreadId.make("thread:live-replacement"), { + activeRunId: null, + }); + const retired = retiredShell(live.id); + const failedRunId = RunId.make("run:replacement-setup-failed"); + const retried: Array = []; + const recordsRead: Array = []; + const sent = yield* Ref.make(0); + const result = yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* mcp.sendToThread(client, { threadId: retired.id, message: "hello" }); + }).pipe( + Effect.provide( + service( + [retired, live], + sent, + { + getProjectThreadRecords: () => Effect.succeed(idleThreadProjection(live)), + getThreadRecords: (threadId) => { + recordsRead.push(threadId); + return Effect.succeed({ + thread: { ...live, id: threadId, worktreePath: null }, + runs: [ + { + id: failedRunId, + status: "failed", + startedAt: null, + workspacePreparation: { type: "worktree" }, + }, + ], + } as never); + }, + sendToThread: () => + Effect.succeed({ + run: { + id: RunId.make("run:replacement-held"), + threadId: live.id, + status: "queued", + queueHeld: true, + }, + delivery: "queued", + } as never), + }, + { + retryPreparation: (input) => { + retried.push(input); + return Effect.succeed({} as never); + }, + }, + ), + ), + ); + // The result names the thread that took the turn, not the retired one the caller aimed at. + assert.equal(result.threadId, live.id); + assert.include(result.link ?? "", live.id); + assert.notInclude(result.link ?? "", retired.id); + assert.deepStrictEqual(recordsRead, [live.id]); + assert.deepStrictEqual( + retried.map((input) => [input.threadId, input.runId]), + [[live.id, failedRunId]], + ); + }), + ); + }); + it.effect("refuses waiting without orchestration capability before reading the target", () => Effect.gen(function* () { const sent = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index d9764faba2c5b..1f8c24c1af1e1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,4 +1,4 @@ -import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts"; +import { BACKGROUND_WAIT_STALE_MINUTES, resolveActiveThreadTargetWith } from "@t3tools/contracts"; import { staleTimeoutMs, waitActivityMs, @@ -3620,9 +3620,29 @@ const make = Effect.gen(function* () { } satisfies OrchestratorMcpThreadReadResult; }), sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) { - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]); - yield* assertLiveCallerForOtherThread(scope, parent, target); - yield* assertTargetWithinLimits(limits, target.thread); + const { + parent, + limits, + target: requested, + } = yield* loadScopedThread(scope, input.threadId, ["runs"]); + yield* assertLiveCallerForOtherThread(scope, parent, requested); + yield* assertTargetWithinLimits(limits, requested.thread); + // A retired thread forwards the message to its live replacement, so the replacement is the + // thread that takes the turn: the caller must reach it and stay within its modes too. + const resolved = yield* resolveActiveThreadTargetWith( + (id) => threadManagement.getThreadShell(id), + input.threadId, + ).pipe(Effect.mapError(threadManagementFailure)); + const target = + resolved.hopCount === 0 + ? requested + : parent !== undefined && resolved.threadId === parent.thread.id + ? parent + : yield* loadTargetThread(scope, resolved.threadId); + if (resolved.hopCount > 0) { + yield* assertLiveCallerForOtherThread(scope, parent, target); + yield* assertTargetWithinLimits(limits, target.thread); + } const mode = input.mode ?? "auto"; // A message to another thread rides in that thread's next digest unless the sender @@ -3630,7 +3650,7 @@ const make = Effect.gen(function* () { const deliveryClass = input.deliveryClass ?? (input.digestCategory !== undefined || - (parent !== undefined && parent.thread.id !== input.threadId) + (parent !== undefined && parent.thread.id !== target.thread.id) ? "digest" : undefined); if ( @@ -3694,8 +3714,10 @@ const make = Effect.gen(function* () { ), ), ); + // The thread that took the message: the replacement when the target was retired. + const liveThreadId = result.run.threadId ?? target.thread.id; if (result.run.status === "queued" && result.run.queueHeld === true) { - yield* threadManagement.getThreadRecords(input.threadId, ["runs"]).pipe( + yield* threadManagement.getThreadRecords(liveThreadId, ["runs"]).pipe( Effect.flatMap(({ thread, runs }) => { const failed = latestExecutedRun(runs); return thread.worktreePath === null && @@ -3705,7 +3727,7 @@ const make = Effect.gen(function* () { commandId: CommandId.make( `${stableCommandId({ scope, requestKey: key, operation: "thread-send" })}:retry-preparation`, ), - threadId: input.threadId, + threadId: liveThreadId, runId: failed.id, }) : Effect.void; @@ -3716,8 +3738,8 @@ const make = Effect.gen(function* () { ); } return { - threadId: input.threadId, - link: threadLinkFor(scope, input.threadId, target.thread.title), + threadId: liveThreadId, + link: threadLinkFor(scope, liveThreadId, target.thread.title), messageId, runId: result.run.id, ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.test.ts b/apps/server/src/mcp/ThreadMetadataMcpService.test.ts new file mode 100644 index 0000000000000..b971171f36089 --- /dev/null +++ b/apps/server/src/mcp/ThreadMetadataMcpService.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from "@effect/vitest"; +import { + EnvironmentId, + type OrchestrationV2ThreadShell, + ProviderInstanceId, + ThreadId, + type ThreadMetadataMcpUpdateInput, +} from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import type { McpInvocationScope } from "./McpInvocationContext.ts"; +import { liveThreadShell } from "./McpToolAccess.testkit.ts"; +import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts"; + +const retired = ThreadId.make("thread:redirect-gate:retired"); +const live = ThreadId.make("thread:redirect-gate:live"); +const fullAccessCaller = ThreadId.make("thread:redirect-gate:full-access"); +const supervisedCaller = ThreadId.make("thread:redirect-gate:supervised"); +const planCaller = ThreadId.make("thread:redirect-gate:plan"); + +const shells = new Map([ + [retired, liveThreadShell(retired, { activeRunId: null })], + [live, liveThreadShell(live, { activeRunId: null })], + [fullAccessCaller, liveThreadShell(fullAccessCaller)], + [supervisedCaller, liveThreadShell(supervisedCaller, { runtimeMode: "approval-required" })], + [planCaller, liveThreadShell(planCaller, { interactionMode: "plan" })], +]); + +const scopeFor = ( + thread: ThreadId | undefined, + client?: McpInvocationScope["client"], +): McpInvocationScope => ({ + environmentId: EnvironmentId.make("environment"), + requestNamespace: "test:redirect-gate", + thread: + thread === undefined + ? undefined + : { + threadId: thread, + providerSessionId: `provider:${thread}`, + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client, + capabilities: new Set(["orchestration"]), + issuedAt: 0, +}); + +const client = ( + access: "read-only" | "approval-required" | "full-access", + narrowedTo?: { runtimeMode: "auto" | "full-access"; interactionMode: "plan" | "default" }, +): NonNullable => ({ + sessionId: "session", + label: "Test client", + access, + ...(narrowedTo === undefined ? {} : { narrowedTo }), +}); + +const setRedirect = (replacedByThreadId: ThreadId | null): ThreadMetadataMcpUpdateInput => ({ + threadId: retired, + action: "set_redirect", + replacedByThreadId, + clientRequestId: "redirect-request", +}); + +const run = (scope: McpInvocationScope, input: ThreadMetadataMcpUpdateInput) => { + const dispatched: Array = []; + const layer = ThreadMetadataMcpService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(SecureRandom.SecureRandom)({}), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + ), + ); + return Effect.gen(function* () { + const service = yield* ThreadMetadataMcpService.ThreadMetadataMcpService; + const outcome = yield* service.update(scope, input).pipe( + Effect.map(() => "updated" as const), + Effect.catch((error) => Effect.succeed(error.code)), + ); + return { outcome, dispatched }; + }).pipe(Effect.provide(layer)); +}; + +describe("ThreadMetadataMcpService set_redirect authority", () => { + it.effect("lets a full-access, default-mode thread set and clear a redirect", () => + Effect.gen(function* () { + const set = yield* run(scopeFor(fullAccessCaller), setRedirect(live)); + expect(set.outcome).toBe("updated"); + expect(set.dispatched).toHaveLength(1); + const cleared = yield* run(scopeFor(fullAccessCaller), setRedirect(null)); + expect(cleared.outcome).toBe("updated"); + }), + ); + + it.effect("lets a full-access client without a thread set a redirect", () => + Effect.gen(function* () { + const set = yield* run(scopeFor(undefined, client("full-access")), setRedirect(live)); + expect(set.outcome).toBe("updated"); + }), + ); + + it.effect("refuses a caller thread in a narrower runtime mode", () => + Effect.gen(function* () { + for (const input of [setRedirect(live), setRedirect(null)]) { + const denied = yield* run(scopeFor(supervisedCaller), input); + expect(denied.outcome).toBe("capability_denied"); + expect(denied.dispatched).toHaveLength(0); + } + }), + ); + + it.effect("refuses a caller thread in plan mode", () => + Effect.gen(function* () { + const denied = yield* run(scopeFor(planCaller), setRedirect(live)); + expect(denied.outcome).toBe("capability_denied"); + expect(denied.dispatched).toHaveLength(0); + }), + ); + + it.effect("refuses a client below full access, or narrowed below it", () => + Effect.gen(function* () { + const scopes = [ + scopeFor(undefined, client("approval-required")), + scopeFor(undefined, client("read-only")), + scopeFor( + undefined, + client("full-access", { runtimeMode: "auto", interactionMode: "default" }), + ), + scopeFor( + undefined, + client("full-access", { runtimeMode: "full-access", interactionMode: "plan" }), + ), + // A full-access thread behind a narrowed client keeps the client's cap. + scopeFor( + fullAccessCaller, + client("full-access", { runtimeMode: "auto", interactionMode: "default" }), + ), + // No thread and no client is the lowest ceiling. + scopeFor(undefined), + ]; + for (const scope of scopes) { + const denied = yield* run(scope, setRedirect(live)); + expect(denied.outcome).toBe("capability_denied"); + expect(denied.dispatched).toHaveLength(0); + } + }), + ); + + it.effect("refuses when the calling thread cannot be read", () => + Effect.gen(function* () { + const denied = yield* run( + scopeFor(ThreadId.make("thread:redirect-gate:unknown")), + setRedirect(live), + ); + expect(denied.outcome).toBe("capability_denied"); + expect(denied.dispatched).toHaveLength(0); + }), + ); + + it.effect("leaves other metadata updates open to a narrower caller", () => + Effect.gen(function* () { + const renamed = yield* run(scopeFor(supervisedCaller), { + threadId: retired, + action: "rename", + title: "Renamed", + clientRequestId: "rename-request", + }); + expect(renamed.outcome).toBe("updated"); + }), + ); +}); diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 9f8f07b8be845..56ef646d9862c 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -20,7 +20,11 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; -import { isLegacyInboxPeer, type McpInvocationScope } from "./McpInvocationContext.ts"; +import { + clientModeCeiling, + isLegacyInboxPeer, + type McpInvocationScope, +} from "./McpInvocationContext.ts"; import { threadNotFound } from "./threadAccess.ts"; export class ThreadMetadataMcpService extends Context.Service< @@ -246,6 +250,38 @@ const make = Effect.gen(function* () { "A thread cannot change its own delegation nudge. Ask from another thread or the client.", ); } + if (input.action === "set_redirect") { + // A redirect moves every wake aimed at a thread onto another one, so it is an admin act: + // only a full-access, default-mode caller (thread or client) may set or clear it. A narrower + // caller could otherwise hijack a thread's wakes or point them at a wider-mode thread. + const callerShell = + scope.thread === undefined + ? null + : yield* threadManagement + .getThreadShell(scope.thread.threadId) + .pipe(Effect.orElseSucceed(() => null)); + const modes = + scope.thread === undefined + ? [clientModeCeiling(scope.client)] + : callerShell === null + ? [] + : [ + callerShell, + // A linked client's approval narrows the thread it speaks for. + ...(scope.client === undefined ? [] : [clientModeCeiling(scope.client)]), + ]; + if ( + modes.length === 0 || + modes.some( + (mode) => mode.runtimeMode !== "full-access" || mode.interactionMode !== "default", + ) + ) { + return yield* failure( + "capability_denied", + "Setting or clearing a thread redirect needs a full-access caller in default mode.", + ); + } + } if (input.action === "set_redirect" && input.replacedByThreadId != null) { // Same check the orchestrator repeats at commit; failing here gives the caller a clear reason. const linkError = yield* redirectLinkError( diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts index 107c9a59aa6d2..b1de060b05417 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts @@ -1,7 +1,3 @@ -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - import { assert, it } from "@effect/vitest"; import { EnvironmentId, type OrchestrationV2Run, ThreadId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -32,7 +28,7 @@ import { watcherAlertMessage, } from "./ModelAlertReactor.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; -import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; +import { withRedirectLedger } from "./testkit/RedirectLedger.ts"; import { alertIsStale, expectsAutoResume, replacedBySibling } from "./UsageLimitIncidents.ts"; import type { ThreadEventAlert, ThreadEventKind, ThreadFinding } from "./ThreadEventAlerts.ts"; @@ -411,12 +407,8 @@ it.effect("forwards a thread event to a watcher on another environment with one ); it.effect("sends an alert for a retired watcher to its replacement and records the redirect", () => - Effect.gen(function* () { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-alert-")); - const ledger = NodePath.join(dir, "redirects.jsonl"); - const previous = process.env[REDIRECT_LEDGER_ENV]; - process.env[REDIRECT_LEDGER_ENV] = ledger; - try { + withRedirectLedger((ledger) => + Effect.gen(function* () { const dispatched: Array<{ threadId: string }> = []; const tombstones: Record = { old: "new", new: null, loop: "loop" }; const deps = { @@ -444,10 +436,7 @@ it.effect("sends an alert for a retired watcher to its replacement and records t dispatched.map((command) => command.threadId), ["new"], ); - const records = NodeFS.readFileSync(ledger, "utf8") - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); + const records = yield* ledger.records; assert.equal(records.length, 1); assert.equal(records[0]!.sourceKind, "event"); assert.equal(records[0]!.retiredThreadId, "old"); @@ -456,12 +445,8 @@ it.effect("sends an alert for a retired watcher to its replacement and records t // A watcher that cannot be resolved drops the alert: nothing is dispatched anywhere. yield* deliverAlertToWatcher(deps, alert, watcher("loop"), here); assert.equal(dispatched.length, 1); - } finally { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - } - }), + }), + ), ); const limitInput = ( diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index fa631e91b56b1..91b4f7d8030c4 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -13,7 +13,6 @@ import { OrchestrationV2WorkerAlertReason, OrchestratorMcpThreadSendResult, ThreadId, - type ThreadRedirectNode, } from "@t3tools/contracts"; import { runModelSignals, workerAlert } from "@t3tools/provider-core/server/subagentProjection"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; @@ -857,9 +856,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( readonly call: PeerMcpClient.PeerMcpClient["Service"]["call"]; readonly sha256Hex: (identity: string) => Effect.Effect; /** Reads a thread's redirect tombstone; an alert for a retired watcher goes to its replacement. */ - readonly getThreadShell?: ( - threadId: ThreadId, - ) => Effect.Effect; + readonly getThreadShell?: Orchestrator.OrchestratorV2["Service"]["getThreadShell"]; }, alert: WatcherAlert, watcher: ModelAlertWatcher, diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 6257d584f7c3c..911f7f37e4f90 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -6,6 +6,7 @@ import { type PullRequestComment, type PullRequestRef, type PullRequestThreadCommentsResult, + type ThreadId, type ThreadPullRequestLink, type ThreadPullRequestWatch, } from "@t3tools/contracts"; @@ -370,7 +371,7 @@ export const make = Effect.gen(function* () { : {}), }), }); - if (wake !== undefined && route !== "here" && route !== "dropped") { + if (wake !== undefined && route !== undefined && route !== "here" && route !== "dropped") { // Sent after the sync commits, so a watch that ended while it was read sends nothing. The // wake has no pull request stamp: the replacement thread does not watch this pull request. yield* engine diff --git a/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts b/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts index 469d7b3bd167b..dba721168c1b0 100644 --- a/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts +++ b/apps/server/src/orchestration-v2/RetiredThreadRedirect.test.ts @@ -1,7 +1,3 @@ -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - import { assert, it } from "@effect/vitest"; import { CommandId, @@ -20,12 +16,9 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; -import { - REDIRECT_LEDGER_ENV, - recordRedirectHit, - resolveWakeTarget, -} from "./RetiredThreadRedirect.ts"; +import { recordRedirectHit, resolveWakeTarget } from "./RetiredThreadRedirect.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import { withRedirectLedger } from "./testkit/RedirectLedger.ts"; const instanceId = ProviderInstanceId.make("codex"); const adapter = { @@ -97,32 +90,6 @@ const sendMessage = (threadId: ThreadId) => }); }); -/** Runs the body with the redirect ledger pointed at a fresh temporary file, then removes it. */ -const withLedger = (body: (path: string) => Effect.Effect) => - Effect.acquireUseRelease( - Effect.sync(() => { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-ledger-")); - const previous = process.env[REDIRECT_LEDGER_ENV]; - process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); - return { dir, previous }; - }), - ({ dir }) => body(NodePath.join(dir, "redirects.jsonl")), - ({ dir, previous }) => - Effect.sync(() => { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - }), - ); - -const readLedger = (path: string) => - NodeFS.existsSync(path) - ? NodeFS.readFileSync(path, "utf8") - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record) - : []; - it.layer(layerTest)("retired thread tombstone", (it) => { it.effect("sets and clears the tombstone, keeping the original retirement time", () => Effect.gen(function* () { @@ -194,7 +161,7 @@ it.layer(layerTest)("retired thread tombstone", (it) => { ); it.effect("resolves multi-hop chains and records one ledger line with ids only", () => - withLedger((path) => + withRedirectLedger((ledger) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const a = ThreadId.make("thread:chain-a"); @@ -215,7 +182,7 @@ it.layer(layerTest)("retired thread tombstone", (it) => { assert.equal(wake.hopCount, 2); assert.isTrue(wake.redirected); - const lines = readLedger(path); + const lines = yield* ledger.records; assert.equal(lines.length, 1); assert.deepEqual(Object.keys(lines[0]!).toSorted(), [ "callerThreadId", @@ -237,13 +204,13 @@ it.layer(layerTest)("retired thread tombstone", (it) => { sourceKind: "event", }); assert.isFalse(live.redirected); - assert.equal(readLedger(path).length, 1); + assert.equal((yield* ledger.records).length, 1); }), ), ); it.effect("fails closed on a dead end and writes no ledger line", () => - withLedger((path) => + withRedirectLedger((ledger) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const old = ThreadId.make("thread:dead-old"); @@ -260,7 +227,7 @@ it.layer(layerTest)("retired thread tombstone", (it) => { resolveWakeTarget((id) => orchestrator.getThreadShell(id), old, { sourceKind: "event" }), ); assert.equal(error._tag, "ThreadRedirectError"); - assert.equal(readLedger(path).length, 0); + assert.equal((yield* ledger.records).length, 0); }), ), ); @@ -289,30 +256,21 @@ it.layer(layerTest)("retired thread tombstone", (it) => { }); it.effect("recordRedirectHit never fails the wake when the ledger cannot be written", () => - Effect.gen(function* () { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-ledger-")); - const previous = process.env[REDIRECT_LEDGER_ENV]; - // A file where a directory is needed: the append must fail. - const blocker = NodePath.join(dir, "blocker"); - NodeFS.writeFileSync(blocker, ""); - process.env[REDIRECT_LEDGER_ENV] = NodePath.join(blocker, "nested", "redirects.jsonl"); - try { - yield* recordRedirectHit({ + // The ledger path sits under a regular file, so the append must fail. + withRedirectLedger( + () => + recordRedirectHit({ retiredThreadId: ThreadId.make("thread:ledger-old"), redirectedToThreadId: ThreadId.make("thread:ledger-new"), sourceKind: "pr_watch", hopCount: 1, - }); - } finally { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - } - }), + }), + { blocked: true }, + ), ); it.effect("recordRedirectHit appends one line per hit and clips long fields", () => - withLedger((path) => + withRedirectLedger((ledger) => Effect.gen(function* () { yield* recordRedirectHit({ retiredThreadId: ThreadId.make("thread:l-old"), @@ -329,12 +287,12 @@ it.effect("recordRedirectHit appends one line per hit and clips long fields", () taskId: "task:1", hopCount: 1, }); - const lines = readLedger(path); + const lines = yield* ledger.records; assert.equal(lines.length, 2); assert.equal((lines[0]!.subscriptionId as string).length, 512); assert.equal(lines[0]!.prUrl, "https://github.com/o/r/pull/1"); assert.equal(lines[1]!.taskId, "task:1"); - assert.equal(NodeFS.statSync(path).mode & 0o777, 0o600); + assert.equal(yield* ledger.mode, 0o600); }), ), ); diff --git a/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts b/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts index a8dee8a28e1d2..2e87a1666ce58 100644 --- a/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts +++ b/apps/server/src/orchestration-v2/RetiredThreadRedirect.ts @@ -1,6 +1,3 @@ -import * as NodeFSP from "node:fs/promises"; -import * as NodePath from "node:path"; - import { type RedirectSourceKind, type ResolvedThreadTarget, @@ -9,9 +6,13 @@ import { type ThreadRedirectNode, resolveActiveThreadTargetWith, } from "@t3tools/contracts"; -import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; @@ -52,24 +53,33 @@ const appendLock = Semaphore.makeUnsafe(1); const clip = (value: string) => value.length > MAX_FIELD_LENGTH ? value.slice(0, MAX_FIELD_LENGTH) : value; +const encodeLine = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + /** The ledger path: the override when set, else the server's state directory. */ const ledgerPath = Effect.gen(function* () { - const override = process.env[REDIRECT_LEDGER_ENV]?.trim(); - if (override) return override; + const override = yield* Config.String(REDIRECT_LEDGER_ENV).pipe( + Config.option, + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isSome(override) && override.value.trim() !== "") return override.value.trim(); const config = yield* Effect.serviceOption(ServerConfig.ServerConfig); - return Option.isSome(config) ? NodePath.join(config.value.stateDir, LEDGER_FILE) : undefined; + const path = yield* Effect.serviceOption(Path.Path); + return Option.isSome(config) && Option.isSome(path) + ? path.value.join(config.value.stateDir, LEDGER_FILE) + : undefined; }); -const appendLine = (path: string, line: string) => - Effect.tryPromise(async () => { - await NodeFSP.mkdir(NodePath.dirname(path), { recursive: true }); - const size = await NodeFSP.stat(path).then( - (stat) => stat.size, - () => 0, - ); - if (size >= MAX_LEDGER_BYTES) await NodeFSP.rename(path, `${path}.1`); - await NodeFSP.appendFile(path, line, { encoding: "utf8", mode: 0o600 }); - }); +const appendLine = Effect.fnUntraced(function* (path: string, line: string) { + const fs = yield* FileSystem.FileSystem; + const { dirname } = yield* Path.Path; + yield* fs.makeDirectory(dirname(path), { recursive: true }); + const size = yield* fs.stat(path).pipe( + Effect.map((info) => Number(info.size)), + Effect.orElseSucceed(() => 0), + ); + if (size >= MAX_LEDGER_BYTES) yield* fs.rename(path, `${path}.1`); + yield* fs.writeFileString(path, line, { flag: "a", mode: 0o600 }); +}); /** * Appends one redirect-hit record. Never fails and never waits long: a ledger that cannot be @@ -82,7 +92,7 @@ export const recordRedirectHit = Effect.fn("RetiredThreadRedirect.recordRedirect if (path === undefined) { return yield* Effect.logWarning("retired-thread redirect not recorded: no ledger path"); } - const timestamp = new Date(yield* Clock.currentTimeMillis).toISOString(); + const timestamp = DateTime.formatIso(yield* DateTime.now); const entry: RedirectLedgerRecord = { timestamp, retiredThreadId: clip(record.retiredThreadId) as ThreadId, @@ -96,9 +106,20 @@ export const recordRedirectHit = Effect.fn("RetiredThreadRedirect.recordRedirect ...(record.prUrl === undefined ? {} : { prUrl: clip(record.prUrl) }), hopCount: record.hopCount, }; + const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); + const pathService = yield* Effect.serviceOption(Path.Path); + if (Option.isNone(fileSystem) || Option.isNone(pathService)) { + return yield* Effect.logWarning("retired-thread redirect not recorded: no file system"); + } + const line = yield* encodeLine(entry).pipe(Effect.option); + if (Option.isNone(line)) { + return yield* Effect.logWarning("retired-thread redirect not recorded: entry not encodable"); + } yield* appendLock - .withPermits(1)(appendLine(path, `${JSON.stringify(entry)}\n`)) + .withPermits(1)(appendLine(path, `${line.value}\n`)) .pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem.value), + Effect.provideService(Path.Path, pathService.value), Effect.timeout(APPEND_TIMEOUT), Effect.catchCause((cause) => Effect.logWarning("retired-thread redirect ledger append failed", cause), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index af6ee628dec97..8099091d2317f 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -1,7 +1,3 @@ -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - import { describe, expect, it } from "@effect/vitest"; import { CommandId, @@ -19,6 +15,7 @@ import { ProjectId, ProviderInstanceId, RunId, + ScheduledTaskId, ThreadId, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -43,7 +40,7 @@ import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; -import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; +import { withRedirectLedger } from "./testkit/RedirectLedger.ts"; import type { ServerProvider } from "@t3tools/contracts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; @@ -1193,49 +1190,52 @@ describe("sendToThread to a retired thread", () => { [live, { projectId, replacedByThreadId: null }], ]); - const run = (input: { readonly scheduledTaskId?: string; readonly senderThreadId?: ThreadId }) => - Effect.gen(function* () { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-send-")); - const ledger = NodePath.join(dir, "redirects.jsonl"); - const previous = process.env[REDIRECT_LEDGER_ENV]; - process.env[REDIRECT_LEDGER_ENV] = ledger; - const dispatched: Array<{ type: string; threadId: string }> = []; - const layerTest = ThreadManagementService.layer.pipe( - Layer.provide(ProviderRegistryMock.layer()), - Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), - Layer.provide( - Layer.mock(Orchestrator.OrchestratorV2)({ - getThreadShell: (threadId) => - Effect.succeed( - (shells.get(threadId) as unknown as OrchestrationV2ThreadShell | undefined) ?? null, - ), - getThreadRecords: (threadId) => - Effect.succeed({ - thread: { - id: threadId, - projectId, - deletedAt: null, - archivedAt: null, - worktreePath: null, - branch: null, - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" }, - }, - runs: [], - providerTurns: [], - messages: [], - turnItems: [], - } as unknown as OrchestrationV2ThreadProjection), - dispatch: (command) => - Effect.sync(() => { - dispatched.push({ type: command.type, threadId: (command as never)["threadId"] }); - return { sequence: 1, storedEvents: [] } as never; - }), - }), - ), - Layer.provide(ServerSettings.layerTest()), - Layer.provide(layerReceiptsTest), - ); - try { + const run = (input: { + readonly scheduledTaskId?: ScheduledTaskId; + readonly senderThreadId?: ThreadId; + }) => + withRedirectLedger((ledger) => + Effect.gen(function* () { + const dispatched: Array<{ type: string; threadId: string }> = []; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(ProviderRegistryMock.layer()), + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadShell: (threadId) => + Effect.succeed( + (shells.get(threadId) as unknown as OrchestrationV2ThreadShell | undefined) ?? + null, + ), + getThreadRecords: (threadId) => + Effect.succeed({ + thread: { + id: threadId, + projectId, + deletedAt: null, + archivedAt: null, + worktreePath: null, + branch: null, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "test", + }, + }, + runs: [], + providerTurns: [], + messages: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push({ type: command.type, threadId: (command as never)["threadId"] }); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); const threads = yield* ThreadManagementService.ThreadManagementService.pipe( Effect.provide(layerTest), ); @@ -1253,20 +1253,9 @@ describe("sendToThread to a retired thread", () => { ...input, }), ); - return { - dispatched, - records: NodeFS.existsSync(ledger) - ? NodeFS.readFileSync(ledger, "utf8") - .split("\n") - .filter((line) => line.length > 0) - : [], - }; - } finally { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - } - }); + return { dispatched, records: yield* ledger.records }; + }), + ); it.effect("delivers a thread_send to the live replacement and records the redirect", () => Effect.gen(function* () { @@ -1276,22 +1265,24 @@ describe("sendToThread to a retired thread", () => { expect(dispatched.map((command) => command.threadId)).toEqual([live]); expect(dispatched[0]?.type).toBe("message.dispatch"); expect(records).toHaveLength(1); - expect(JSON.parse(records[0]!)).toMatchObject({ + expect(records[0]).toMatchObject({ retiredThreadId: retired, redirectedToThreadId: live, sourceKind: "thread_send", callerThreadId: caller, hopCount: 2, }); - expect(records[0]).not.toContain("Secret message body"); + expect(JSON.stringify(records)).not.toContain("Secret message body"); }), ); it.effect("delivers a scheduled wake to the live replacement and records the task", () => Effect.gen(function* () { - const { dispatched, records } = yield* run({ scheduledTaskId: "task:nightly" }); + const { dispatched, records } = yield* run({ + scheduledTaskId: ScheduledTaskId.make("task:nightly"), + }); expect(dispatched.map((command) => command.threadId)).toEqual([live]); - expect(JSON.parse(records[0]!)).toMatchObject({ + expect(records[0]).toMatchObject({ retiredThreadId: retired, redirectedToThreadId: live, sourceKind: "schedule", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 3074db95fba0d..fc12c4e5f3c13 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,9 +1,6 @@ -import * as NodeFS from "node:fs"; import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; import { prepareSubscribe } from "./eventSubscription.ts"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import { REDIRECT_LEDGER_ENV } from "./RetiredThreadRedirect.ts"; +import { withRedirectLedger } from "./testkit/RedirectLedger.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; import { makeThreadInbox } from "@t3tools/contracts"; import * as HttpClient from "effect/http/HttpClient"; @@ -5898,254 +5895,221 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ); it.effect("redirects a pull request watch wake from a retired thread to its replacement", () => - Effect.acquireUseRelease( - Effect.sync(() => { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-pr-watch-")); - const previous = process.env[REDIRECT_LEDGER_ENV]; - process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); - return { dir, previous }; - }), - ({ dir }) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const retiredId = ThreadId.make("runtime-pull-request-watch-retired"); - const liveId = ThreadId.make("runtime-pull-request-watch-replacement"); - const projectId = ProjectId.make("pr-watch-retired-project"); - yield* seedProject({ - projectId, - title: "Watch retired", - workspaceRoot: "/workspace/watch-retired", - defaultModelSelection: null, - createdAt: "2026-10-01T00:00:00.000Z", - }); - for (const id of [retiredId, liveId]) { - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`pr-watch-retired-create-${id}`), - threadId: id, - projectId, - title: id, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - }); - } - const prUrl = "https://github.com/pingdotgg/t3code/pull/31"; - yield* orchestrator.dispatch({ - type: "thread.pull-request.watch", - commandId: CommandId.make("pr-watch-retired-start"), - threadId: retiredId, - host: "github.com", - repository: "pingdotgg/t3code", - number: 31, - watching: true, - link: { url: prUrl, source: "agent" }, - }); + withRedirectLedger((ledger) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const retiredId = ThreadId.make("runtime-pull-request-watch-retired"); + const liveId = ThreadId.make("runtime-pull-request-watch-replacement"); + const projectId = ProjectId.make("pr-watch-retired-project"); + yield* seedProject({ + projectId, + title: "Watch retired", + workspaceRoot: "/workspace/watch-retired", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + for (const id of [retiredId, liveId]) { yield* orchestrator.dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make("pr-watch-retired-tombstone"), - threadId: retiredId, - replacedByThreadId: liveId, + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-retired-create-${id}`), + threadId: id, + projectId, + title: id, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, }); + } + const prUrl = "https://github.com/pingdotgg/t3code/pull/31"; + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-retired-start"), + threadId: retiredId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 31, + watching: true, + link: { url: prUrl, source: "agent" }, + }); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("pr-watch-retired-tombstone"), + threadId: retiredId, + replacedByThreadId: liveId, + }); - let status: "pending" | "success" = "pending"; - const host = Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - Layer.mock(PullRequestService.PullRequestService)({ - detail: () => - Effect.sync(() => ({ - ...watchedPullRequestDetail({ - projectId, - number: 31, - at: "2026-10-02T12:00:00.000Z", - }), - headSha: "retired31aaa", - checks: [{ name: "test", status, description: null, url: null, required: true }], - })), - activity: () => - Effect.succeed({ - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads: [], - commits: [], + let status: "pending" | "success" = "pending"; + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Effect.sync(() => ({ + ...watchedPullRequestDetail({ + projectId, + number: 31, + at: "2026-10-02T12:00:00.000Z", }), - }), + headSha: "retired31aaa", + checks: [{ name: "test", status, description: null, url: null, required: true }], + })), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const summaries = (threadId: ThreadId) => + Effect.map(orchestrator.getThreadRecords(threadId, ["messages"]), ({ messages }) => + messages.flatMap((message) => message.notification?.summary ?? []), ); - const summaries = (threadId: ThreadId) => - Effect.map(orchestrator.getThreadRecords(threadId, ["messages"]), ({ messages }) => - messages.flatMap((message) => message.notification?.summary ?? []), - ); - const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); - yield* reactor.sweep; - yield* worker.drain(); - status = "success"; - yield* TestClock.adjust("10 minutes"); - yield* reactor.sweep; - yield* worker.drain(); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + yield* worker.drain(); + status = "success"; + yield* TestClock.adjust("10 minutes"); + yield* reactor.sweep; + yield* worker.drain(); - assert.deepEqual(yield* summaries(liveId), ["#31: checks passed"]); - // The retired thread took no message and no run. - const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); - assert.lengthOf(retired.messages, 0); - assert.lengthOf(retired.runs, 0); - - const ledger = NodePath.join(dir, "redirects.jsonl"); - const records = NodeFS.readFileSync(ledger, "utf8") - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); - assert.isAtLeast(records.length, 1); - for (const record of records) { - assert.equal(record.sourceKind, "pr_watch"); - assert.equal(record.retiredThreadId, retiredId); - assert.equal(record.redirectedToThreadId, liveId); - assert.equal(record.prUrl, prUrl); - } - }), - ({ dir, previous }) => - Effect.sync(() => { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - }), + assert.deepEqual(yield* summaries(liveId), ["#31: checks passed"]); + // The retired thread took no message and no run. + const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); + assert.lengthOf(retired.messages, 0); + assert.lengthOf(retired.runs, 0); + + const records = yield* ledger.records; + assert.isAtLeast(records.length, 1); + for (const record of records) { + assert.equal(record.sourceKind, "pr_watch"); + assert.equal(record.retiredThreadId, retiredId); + assert.equal(record.redirectedToThreadId, liveId); + assert.equal(record.prUrl, prUrl); + } + }), ), ); it.effect("redirects a pull request event subscription wake from a retired thread", () => - Effect.acquireUseRelease( - Effect.sync(() => { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-redirect-pr-event-")); - const previous = process.env[REDIRECT_LEDGER_ENV]; - process.env[REDIRECT_LEDGER_ENV] = NodePath.join(dir, "redirects.jsonl"); - return { dir, previous }; - }), - ({ dir }) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const retiredId = ThreadId.make("runtime-pr-event-retired"); - const liveId = ThreadId.make("runtime-pr-event-replacement"); - const projectId = ProjectId.make("pr-event-retired-project"); - yield* seedProject({ - projectId, - title: "Event retired", - workspaceRoot: "/workspace/event-retired", - defaultModelSelection: null, - createdAt: "2026-10-01T00:00:00.000Z", - }); - for (const id of [retiredId, liveId]) { - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`pr-event-create-${id}`), - threadId: id, - projectId, - title: id, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - }); - } - const prUrl = "https://github.com/pingdotgg/t3code/pull/32"; - const prepared = prepareSubscribe({ - id: "evt_retired_1", - subscriberThreadId: retiredId, - selector: { entity: "pull_request", by: "url", url: prUrl }, - events: [{ name: "merged" }], - createdAt: "2026-10-02T11:00:00.000Z", - }); - assert.isTrue(prepared.ok); - if (!prepared.ok) return; - // The subscription table lives in its own in-memory database, shared by the put and the reactor. - const store = yield* EventSubscriptionStore.EventSubscriptionStore.pipe( - Effect.provide( - EventSubscriptionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), - ), - ); - yield* store.put(prepared.subscription); - // The subscription rides on the thread's pull request watch. - yield* orchestrator.dispatch({ - type: "thread.pull-request.watch", - commandId: CommandId.make("pr-event-watch"), - threadId: retiredId, - host: "github.com", - repository: "pingdotgg/t3code", - number: 32, - watching: true, - link: { url: prUrl, source: "agent" }, - }); + withRedirectLedger((ledger) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const retiredId = ThreadId.make("runtime-pr-event-retired"); + const liveId = ThreadId.make("runtime-pr-event-replacement"); + const projectId = ProjectId.make("pr-event-retired-project"); + yield* seedProject({ + projectId, + title: "Event retired", + workspaceRoot: "/workspace/event-retired", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + for (const id of [retiredId, liveId]) { yield* orchestrator.dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make("pr-event-tombstone"), - threadId: retiredId, - replacedByThreadId: liveId, + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-event-create-${id}`), + threadId: id, + projectId, + title: id, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, }); + } + const prUrl = "https://github.com/pingdotgg/t3code/pull/32"; + const prepared = prepareSubscribe({ + id: "evt_retired_1", + subscriberThreadId: retiredId, + selector: { entity: "pull_request", by: "url", url: prUrl }, + events: [{ name: "merged" }], + createdAt: "2026-10-02T11:00:00.000Z", + }); + assert.isTrue(prepared.ok); + if (!prepared.ok) return; + // The subscription table lives in its own in-memory database, shared by the put and the reactor. + const store = yield* EventSubscriptionStore.EventSubscriptionStore.pipe( + Effect.provide( + EventSubscriptionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), + ); + yield* store.put(prepared.subscription); + // The subscription rides on the thread's pull request watch. + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-event-watch"), + threadId: retiredId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 32, + watching: true, + link: { url: prUrl, source: "agent" }, + }); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("pr-event-tombstone"), + threadId: retiredId, + replacedByThreadId: liveId, + }); - const host = Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - Layer.succeed(EventSubscriptionStore.EventSubscriptionStore, store), - Layer.mock(PullRequestService.PullRequestService)({ - detail: () => - Effect.succeed({ - ...watchedPullRequestDetail({ - projectId, - number: 32, - at: "2026-10-02T12:00:00.000Z", - }), - state: "merged" as const, - mergedAt: "2026-10-02T12:00:00.000Z", - }), - activity: () => - Effect.succeed({ - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads: [], - commits: [], + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(EventSubscriptionStore.EventSubscriptionStore, store), + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Effect.succeed({ + ...watchedPullRequestDetail({ + projectId, + number: 32, + at: "2026-10-02T12:00:00.000Z", }), - }), - ); - const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); - yield* reactor.sweep; - yield* worker.drain(); + state: "merged" as const, + mergedAt: "2026-10-02T12:00:00.000Z", + }), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + yield* reactor.sweep; + yield* worker.drain(); - const delivered = yield* orchestrator.getThreadRecords(liveId, ["messages"]); - assert.isAtLeast(delivered.messages.length, 1); - const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); - assert.lengthOf(retired.messages, 0); - assert.lengthOf(retired.runs, 0); - - const records = NodeFS.readFileSync(NodePath.join(dir, "redirects.jsonl"), "utf8") - .split("\n") - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as Record); - assert.isAtLeast(records.length, 1); - for (const record of records) { - assert.equal(record.sourceKind, "event"); - assert.equal(record.subscriptionId, "evt_retired_1"); - assert.equal(record.retiredThreadId, retiredId); - assert.equal(record.redirectedToThreadId, liveId); - assert.equal(record.prUrl, prUrl); - } - }), - ({ dir, previous }) => - Effect.sync(() => { - if (previous === undefined) delete process.env[REDIRECT_LEDGER_ENV]; - else process.env[REDIRECT_LEDGER_ENV] = previous; - NodeFS.rmSync(dir, { recursive: true, force: true }); - }), + const delivered = yield* orchestrator.getThreadRecords(liveId, ["messages"]); + assert.isAtLeast(delivered.messages.length, 1); + const retired = yield* orchestrator.getThreadRecords(retiredId, ["messages", "runs"]); + assert.lengthOf(retired.messages, 0); + assert.lengthOf(retired.runs, 0); + + const records = yield* ledger.records; + assert.isAtLeast(records.length, 1); + for (const record of records) { + assert.equal(record.sourceKind, "event"); + assert.equal(record.subscriptionId, "evt_retired_1"); + assert.equal(record.retiredThreadId, retiredId); + assert.equal(record.redirectedToThreadId, liveId); + assert.equal(record.prUrl, prUrl); + } + }), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/RedirectLedger.ts b/apps/server/src/orchestration-v2/testkit/RedirectLedger.ts new file mode 100644 index 0000000000000..660d741e915c7 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/RedirectLedger.ts @@ -0,0 +1,63 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import type { PlatformError } from "effect/PlatformError"; +import * as Schema from "effect/Schema"; + +import { REDIRECT_LEDGER_ENV } from "../RetiredThreadRedirect.ts"; + +const decodeLine = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +); + +export interface TestRedirectLedger { + readonly path: string; + /** Every record appended so far; empty while the file does not exist. */ + readonly records: Effect.Effect< + ReadonlyArray>, + PlatformError | Schema.SchemaError + >; + /** The ledger file's permission bits. */ + readonly mode: Effect.Effect; +} + +/** + * Runs `body` with the redirect ledger pointed at a file in a fresh temporary directory, which is + * removed afterwards. `blocked` puts the path under a regular file, so every append fails. + */ +export const withRedirectLedger = ( + body: (ledger: TestRedirectLedger) => Effect.Effect, + options: { readonly blocked?: boolean } = {}, +) => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-redirect-ledger-" }); + let file = path.join(dir, "redirects.jsonl"); + if (options.blocked === true) { + const blocker = path.join(dir, "blocker"); + yield* fs.writeFileString(blocker, ""); + file = path.join(blocker, "nested", "redirects.jsonl"); + } + const ledger: TestRedirectLedger = { + path: file, + records: Effect.gen(function* () { + if (!(yield* fs.exists(file))) return []; + const text = yield* fs.readFileString(file); + return yield* Effect.forEach( + text.split("\n").filter((line) => line.length > 0), + (line) => decodeLine(line), + ); + }), + mode: fs.stat(file).pipe(Effect.map((info) => info.mode & 0o777)), + }; + return yield* body(ledger).pipe( + Effect.provide( + ConfigProvider.layer(ConfigProvider.fromUnknown({ [REDIRECT_LEDGER_ENV]: file })), + ), + ); + }), + ).pipe(Effect.provide(NodeServices.layer)); diff --git a/packages/contracts/src/threadRedirect.test.ts b/packages/contracts/src/threadRedirect.test.ts index d12e68b04a887..5da4613152564 100644 --- a/packages/contracts/src/threadRedirect.test.ts +++ b/packages/contracts/src/threadRedirect.test.ts @@ -142,6 +142,20 @@ describe("redirectLinkError", () => { }), ); + it.effect("refuses a replacement whose downstream chain is missing or deleted", () => + Effect.gen(function* () { + const { lookup } = table({ old: null, a: "b", b: "gone", gone: null, c: "nowhere" }, [ + "gone", + ]); + expect(yield* redirectLinkError(lookup, id("old"), id("a"))).toMatch( + /chain ends at thread:gone/, + ); + expect(yield* redirectLinkError(lookup, id("old"), id("c"))).toMatch( + /chain ends at thread:nowhere/, + ); + }), + ); + it.effect("refuses a link that would close a loop", () => Effect.gen(function* () { // b -> c already; retiring c behind b would loop. diff --git a/packages/contracts/src/threadRedirect.ts b/packages/contracts/src/threadRedirect.ts index 4f935bb6e5779..63a6b6fc3301c 100644 --- a/packages/contracts/src/threadRedirect.ts +++ b/packages/contracts/src/threadRedirect.ts @@ -99,7 +99,8 @@ export const resolveActiveThreadTargetWith = ( /** * Write-time check for retiring `threadId` behind `replacementId`. Returns the reason the link is * refused, or `null` when it is safe. A self-redirect or a replacement whose chain leads back to - * `threadId` would loop; a missing or deleted replacement would dead-end every wake. + * `threadId` would loop; a missing or deleted replacement, or one further down its chain, would + * dead-end every wake. */ export const redirectLinkError = ( lookup: (threadId: ThreadId) => Effect.Effect, @@ -120,7 +121,11 @@ export const redirectLinkError = ( if (seen.has(current)) return "That redirect would create a cycle."; seen.add(current); const node = yield* lookup(current); - const next = node?.replacedByThreadId ?? null; + // A downstream link to a missing or deleted thread would dead-end every wake. + if (node === null || (node.deletedAt ?? null) !== null) { + return `The redirect chain ends at ${current}, which was not found.`; + } + const next = node.replacedByThreadId ?? null; if (next === null) return null; current = next; }