From d7f47cd6748333dd55eabdfe8e8b083ef8e01236 Mon Sep 17 00:00:00 2001 From: Maxwell Weinzierl Date: Fri, 13 Nov 2026 16:12:41 -0800 Subject: [PATCH] t4: release manager and owners stop polling, waiters, smaller tool outputs, urgent-only interrupts, bot PR comments (AI-93) - release_queue: compact rows with 'changed since your last read', owners see their own PRs (and ones they wait on) unless all; waitFor/stopWaiting; staging/shipped/failed reach waiters - handoffs and run-watch wakes to a release manager open with its queue and debts; no t3_owed footer for it; owners whose PR sits 2 h in one state are told where it is - staging: notice says don't settle yet - pure fyi, staging notices, run-watch notices, fyi digests and plain t3_thread_send wait for a running turn instead of steering in (no cut tool calls); done/ask/restart steer - t3_handoff runs once per clientRequestId (or same message within an hour); write tool calls are logged, and the restart note lists cut ones and ones that finished unseen - t3_thread_list compact rows (detail for full), t3_thread_read 1,500 chars per item with remainingChars, list_scheduled_tasks compact rows (scheduledTaskId for one in full) - PR watch ignores bot conversation comments and outdated review comments - rm-safety decline note for non-rm commands says to save the script and run the file - worktree creation serialized per repo, retried once; preview timeouts point to playwright Claude Opus 5.5 via Claude Code (T3) --- apps/server/src/cli/thread.ts | 8 +- apps/server/src/mcp/McpHttpServer.ts | 50 +- .../OrchestratorMcpService.activity.test.ts | 2 + .../src/mcp/OrchestratorMcpService.test.ts | 6 +- apps/server/src/mcp/OrchestratorMcpService.ts | 108 ++- ...OrchestratorMcpToolkit.integration.test.ts | 50 +- .../server/src/mcp/PreviewAutomationBroker.ts | 9 +- apps/server/src/mcp/toolkits/core.test.ts | 158 +++- .../src/mcp/toolkits/orchestrator/handlers.ts | 29 +- .../src/mcp/toolkits/orchestrator/tools.ts | 8 +- apps/server/src/mcp/toolkits/t4/handlers.ts | 800 +++++++++++------- .../src/mcp/toolkits/t4/release.test.ts | 105 ++- apps/server/src/mcp/toolkits/t4/tools.ts | 45 +- .../Adapters/ClaudeAdapterV2.ts | 5 +- .../PullRequestWatchReactor.ts | 16 +- .../orchestration-v2/RestartContinuation.ts | 15 +- .../orchestration-v2/pullRequestWatch.test.ts | 16 +- .../src/orchestration-v2/pullRequestWatch.ts | 21 +- apps/server/src/peer/PeerForwarding.test.ts | 1 + .../src/provider/agentContextBudget.json | 6 +- apps/server/src/t4/T4Delivery.test.ts | 66 ++ apps/server/src/t4/T4Delivery.ts | 25 +- apps/server/src/t4/T4Jobs.ts | 2 + apps/server/src/t4/T4Migrations.ts | 30 + apps/server/src/t4/T4Releases.ts | 191 +++++ apps/server/src/t4/T4RunWatch.ts | 36 +- apps/server/src/t4/T4Store.test.ts | 53 ++ apps/server/src/t4/T4Store.ts | 167 ++++ .../server/src/t4/declineSafetyChecks.test.ts | 21 + apps/server/src/t4/declineSafetyChecks.ts | 17 +- apps/server/src/t4/fyiDigest.ts | 1 + apps/server/src/t4/toolCallLog.ts | 109 +++ apps/server/src/t4/worktreeNaming.test.ts | 72 +- apps/server/src/t4/worktreeNaming.ts | 27 + apps/server/src/vcs/GitVcsDriverCore.ts | 251 +++--- docs/t4/DESIGN.md | 38 +- packages/contracts/src/orchestratorMcp.ts | 75 +- .../src/server/orchestrationInstructions.ts | 2 +- 38 files changed, 2066 insertions(+), 575 deletions(-) create mode 100644 apps/server/src/t4/T4Releases.ts create mode 100644 apps/server/src/t4/declineSafetyChecks.test.ts create mode 100644 apps/server/src/t4/toolCallLog.ts diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 80dfad018e158..32440e9eacd7b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -581,7 +581,13 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { + projectId: project.id, + includeSubagents: false, + limit: 100, + cursor, + detail: flags.json, + }, OrchestratorMcpThreadListResult, ); threads.push(...page.threads); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 2fa4e53f8e870..da02cd988bbb4 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -71,6 +71,8 @@ import * as WorktreeMcpService from "./WorktreeMcpService.ts"; import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts"; import * as T4Handlers from "./toolkits/t4/handlers.ts"; import { T4Toolkit } from "./toolkits/t4/tools.ts"; +import * as ToolCallLog from "../t4/toolCallLog.ts"; +import * as T4Store from "../t4/T4Store.ts"; import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts"; import * as DeviceHandlers from "./toolkits/device/handlers.ts"; import { @@ -1136,6 +1138,50 @@ const withAdvertisedSchemas = Effect.fn("McpHttpServer.withAdvertisedSchemas")(f return yield* registration.pipe(Effect.provideService(McpServer.McpServer, advertisingServer)); }); +/** + * t4 fork: write calls a restart can cut are logged as they start and end, so the restart note + * tells the agent which went through (t4/toolCallLog.ts, AI-93). + */ +const withT4CallLog = Effect.fn("McpHttpServer.withT4CallLog")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const store = Option.getOrUndefined(yield* Effect.serviceOption(T4Store.T4Store)); + if (store === undefined) return yield* registration; + const loggingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + if (!ToolCallLog.LOGGED_TOOLS.has(options.tool.name)) return server.addTool(options); + return server.addTool({ + ...options, + handle: (payload) => + Effect.serviceOption(McpInvocationContext.McpInvocationContext).pipe( + Effect.flatMap((invocation) => { + const threadId = Option.getOrUndefined(invocation)?.thread?.threadId; + return threadId === undefined + ? options.handle(payload) + : ToolCallLog.logged( + store, + { threadId, tool: options.tool.name, args: payload }, + options.handle(payload), + (result) => + result instanceof McpSchema.InputRequired + ? "asked for input" + : toolOutcome(result).outcome === "ok" + ? "done" + : `failed: ${String( + (result.content[0] as { readonly text?: unknown } | undefined) + ?.text ?? "", + ).slice(0, 120)}`, + ); + }), + ), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, loggingServer)); +}); + /** Hands each call the services its registration was built with; the request's own still win. */ const provideRegistrationServices = () => McpServer.middleware<{ provides: Services }>()( @@ -1160,7 +1206,9 @@ export const toolkitRegistration = , EX, Layer.effectDiscard( withToolAnalytics( withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withT4CallLog( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index c42315cd0e90b..a38ebc5107439 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -296,7 +296,9 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn text, textTruncated: index < expected.length - 1, nextTextOffset: index < expected.length - 1 ? textOffset : null, + ...(index < expected.length - 1 ? { remainingChars: "a😀bc".length - textOffset } : {}), }); + expect("remainingChars" in result.items[0]!).toBe(index < expected.length - 1); } } }).pipe(Effect.provide(layer), Effect.runPromise); diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 4df2cfa6655cf..307f1af67ca9b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3591,10 +3591,14 @@ describe("OrchestratorMcpService thread list", () => { allProjects: true, projectId: ProjectId.make("project:a"), snoozed: true, + detail: true, }); assert.equal(listed.projectId, null); assert.deepStrictEqual( - listed.threads.map((thread) => [thread.threadId, thread.projectId]), + listed.threads.map((thread): ReadonlyArray => [ + thread.threadId, + thread.projectId, + ]), [ ["thread:a-snoozed", "project:a"], ["thread:b-snoozed", "project:b"], diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 508c65b1845dc..21e83e1d5b345 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -27,7 +27,7 @@ import { type OrchestratorMcpRequestSecretInput, type OrchestratorMcpRequestSecretResult, type OrchestratorMcpDeleteScheduledTaskResult, - type OrchestratorMcpListScheduledTasksResult, + type OrchestratorMcpScheduledTaskRow, type OrchestratorMcpScheduledTask, type OrchestratorMcpScheduleTaskInput, type OrchestratorMcpScheduleTaskResult, @@ -164,7 +164,9 @@ const secretRequestResult = ( const DEFAULT_THREAD_LIST_LIMIT = 50; const DEFAULT_THREAD_READ_LIMIT = 50; const DEFAULT_THREAD_RUN_LIMIT = 10; -const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000; +// t4 fork (AI-93): long items cost agents their context; a cut item says how to read on. +const DEFAULT_THREAD_ITEM_MAX_CHARS = 1_500; +const SCHEDULED_TASK_PROMPT_PREVIEW_CHARS = 120; interface ResolvedTarget { readonly modelSelection: ModelSelection; @@ -204,7 +206,10 @@ export interface OrchestratorMcpServiceShape { readonly listScheduledTasks: ( scope: McpInvocationScope, input: OrchestratorMcpListScheduledTasksInput, - ) => Effect.Effect; + ) => Effect.Effect< + { readonly tasks: ReadonlyArray }, + OrchestratorMcpFailure + >; readonly updateScheduledTask: ( scope: McpInvocationScope, input: OrchestratorMcpUpdateScheduledTaskInput, @@ -640,6 +645,7 @@ function pageIncludesTerminalTaskResult(input: { "thread" | "runs" | "contextTransfers" | "messages" | "turnItems" | "providerTurns" >; readonly maxChars: number; + readonly textOffset: number; }): boolean { const transfer = taskResultTransfer(input.parentThreadId, input.target, input.task); if (transfer === undefined) return false; @@ -662,7 +668,7 @@ function pageIncludesTerminalTaskResult(input: { if (!matchesResult) return false; const text = turnItemText(row.item); - return text !== null && text.length <= textPageEnd(text, 0, input.maxChars); + return text !== null && text.length <= textPageEnd(text, input.textOffset, input.maxChars); }); } @@ -785,7 +791,7 @@ function threadTitle(input: { function threadSettlement( thread: Pick, -): Pick { +): Pick { const settled = thread.settledOverride === "settled"; return { settled, @@ -796,7 +802,7 @@ function threadSettlement( function threadSnooze( thread: Parameters[0], nowMs: number, -): Pick { +): Pick { const snoozed = isSnoozed(thread, nowMs); return { snoozed, @@ -831,6 +837,62 @@ function threadPullRequest( }; } +/** t4 fork (AI-93): what agents pick a thread by; `detail: true` gives the full row. */ +function compactListItemFromShell( + scope: McpInvocationScope, + shell: OrchestrationV2ThreadShell, + nowMs: number, +): OrchestratorMcpThreadListItem { + return { + threadId: shell.id, + title: shell.title, + link: threadLinkFor(scope, shell.id), + status: shell.activityRunStatus ?? shell.status, + updatedAt: DateTime.formatIso(shell.updatedAt), + ...(shell.linkedPullRequest == null ? {} : { linkedPullRequest: shell.linkedPullRequest }), + ...(threadSettlement(shell).settled ? { settled: true } : {}), + ...(isSnoozed(shell, nowMs) ? { snoozed: true } : {}), + ...(shell.lineage.parentThreadId === null + ? {} + : { parentThreadId: shell.lineage.parentThreadId }), + }; +} + +const COMPACT_THREAD_LIST_MORE = + "Compact rows. `detail: true` gives full rows; t3_thread_read gives one thread in full."; + +/** t4 fork (AI-93): list rows cut the prompt to a preview; `scheduledTaskId` reads one in full. */ +export function scheduledTaskRows(tasks: ReadonlyArray): { + readonly tasks: ReadonlyArray; + readonly more?: string; +} { + const rows = tasks.map((task): OrchestratorMcpScheduledTaskRow => ({ + scheduledTaskId: task.scheduledTaskId, + title: task.title, + enabled: task.enabled, + boundThreadId: task.boundThreadId, + schedule: task.schedule, + nextRunAt: task.nextRunAt, + lastRunStatus: task.lastRunStatus, + promptPreview: task.prompt.slice( + 0, + textPageEnd(task.prompt, 0, SCHEDULED_TASK_PROMPT_PREVIEW_CHARS), + ), + promptLength: task.prompt.length, + ...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }), + })); + const cut = tasks.some( + (task) => + task.prompt.length > SCHEDULED_TASK_PROMPT_PREVIEW_CHARS || task.webhookUrl !== undefined, + ); + return cut + ? { + tasks: rows, + more: `Prompts are cut to ${SCHEDULED_TASK_PROMPT_PREVIEW_CHARS} chars (promptLength is the whole). Pass \`scheduledTaskId\` for one task in full, with its webhook URL.`, + } + : { tasks: rows }; +} + function listItemFromShell( scope: McpInvocationScope, shell: OrchestrationV2ThreadShell, @@ -1057,6 +1119,7 @@ function timelineItem(input: { text: text === null ? null : text.slice(offset, end), textTruncated, nextTextOffset: textTruncated ? end : null, + ...(textTruncated ? { remainingChars: text.length - end } : {}), updatedAt: DateTime.formatIso(input.row.item.updatedAt), }; } @@ -2089,10 +2152,20 @@ const make = Effect.gen(function* () { failure("orchestration_error", `Could not list scheduled tasks: ${error.message}`), ), ); + const wanted = tasks.filter((task) => + input.scheduledTaskId !== undefined + ? task.id === input.scheduledTaskId + : projectId === undefined || task.projectId === projectId, + ); + if (input.scheduledTaskId !== undefined && wanted.length === 0) { + return yield* failure( + "task_not_found", + `Scheduled task ${input.scheduledTaskId} was not found.`, + ); + } return { - tasks: yield* Effect.forEach( - tasks.filter((task) => projectId === undefined || task.projectId === projectId), - (task) => summarizeScheduledTask(scope, { parent, limits }, task), + tasks: yield* Effect.forEach(wanted, (task) => + summarizeScheduledTask(scope, { parent, limits }, task), ), }; }, @@ -3054,9 +3127,14 @@ const make = Effect.gen(function* () { return { projectId, currentThreadId: parent?.thread.id ?? null, - threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)), + threads: page.map((shell) => + input.detail === true + ? listItemFromShell(scope, shell, nowMs) + : compactListItemFromShell(scope, shell, nowMs), + ), nextCursor, total: filtered.length, + ...(input.detail === true || page.length === 0 ? {} : { more: COMPACT_THREAD_LIST_MORE }), } satisfies OrchestratorMcpThreadListResult; }), readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) { @@ -3108,12 +3186,9 @@ const make = Effect.gen(function* () { target, returnedRunIds, ); - if ( - parent !== undefined && - scope.thread !== undefined && - tasks.length > 0 && - (input.textOffset ?? 0) === 0 - ) { + // A cut result is delivered once a read reaches its end (itemId + textOffset). + const textOffset = input.itemId === undefined ? 0 : (input.textOffset ?? 0); + if (parent !== undefined && scope.thread !== undefined && tasks.length > 0) { for (const task of tasks) { const transfer = taskResultTransfer(parent.thread.id, target, task); const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id; @@ -3133,6 +3208,7 @@ const make = Effect.gen(function* () { task, target: { ...target, ...resultRecords }, maxChars, + textOffset, }) ) { yield* readTask( diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index bbeac142dfebb..988086b2469a3 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -10,6 +10,7 @@ import { type ModelSelection, OrchestratorMcpDelegateTaskResult, OrchestratorMcpThreadInterruptResult, + type OrchestratorMcpThreadReadResult, OrchestratorMcpThreadSendResult, ProjectId, ProviderDriverKind, @@ -196,10 +197,22 @@ const layerUnusedScheduledTaskStub = Layer.succeed( describe("orchestrator MCP toolkit", () => { it.live.each([ - { label: "distinct", result: queuedFollowupResult, latestSummary: queuedFollowupResult }, - { label: "identical", result: delegatedResult, latestSummary: null }, - { label: "emoji", result: "😀", latestSummary: "😀" }, - ])("reports $label child results", ({ result, latestSummary }) => + { + label: "distinct", + result: queuedFollowupResult, + latestSummary: queuedFollowupResult, + pageChars: 20_000, + }, + { label: "identical", result: delegatedResult, latestSummary: null, pageChars: 20_000 }, + { label: "emoji", result: "😀", latestSummary: "😀", pageChars: 1 }, + // A result cut across pages is delivered once a read reaches its end. + { + label: "paged", + result: queuedFollowupResult, + latestSummary: queuedFollowupResult, + pageChars: 10, + }, + ])("reports $label child results", ({ label, result, latestSummary, pageChars }) => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace("delegated-task-status"); @@ -709,7 +722,7 @@ describe("orchestrator MCP toolkit", () => { { threadId: delegated.childThreadId, limit: 100, - maxCharsPerItem: result === "😀" ? 1 : 20_000, + maxCharsPerItem: pageChars, }, { ...invocation, thread: undefined }, ).pipe(Effect.withTracer(tracer)); @@ -724,11 +737,36 @@ describe("orchestrator MCP toolkit", () => { const read = yield* invoke("t3_thread_read", { threadId: delegated.childThreadId, limit: 100, - maxCharsPerItem: result === "😀" ? 1 : 20_000, + maxCharsPerItem: pageChars, }).pipe(Effect.withTracer(tracer)); expect(read.isError).not.toBe(true); expect(transferReads.length).toBeGreaterThan(0); expect(read.structuredContent).toEqual(parentlessRead.structuredContent); + let cut = ( + read.structuredContent as OrchestratorMcpThreadReadResult | undefined + )?.items.find((item) => item.textTruncated && item.text === result.slice(0, pageChars)); + if (label === "paged") { + expect(cut).toMatchObject({ + remainingChars: result.length - pageChars, + nextTextOffset: pageChars, + }); + } + while (cut !== undefined) { + const afterCut = yield* orchestrator.getThreadProjection(parentThreadId); + expect( + afterCut.subagents.find((task) => task.id === queuedFollowup.taskId) + ?.completionDelivery?.state, + ).toBe("claimed"); + const next = yield* invoke("t3_thread_read", { + threadId: delegated.childThreadId, + itemId: cut.itemId, + textOffset: cut.nextTextOffset, + maxCharsPerItem: pageChars, + }).pipe(Effect.withTracer(tracer)); + cut = (next.structuredContent as OrchestratorMcpThreadReadResult).items.find( + (item) => item.textTruncated, + ); + } // The acknowledgement reads the task and its spawning run by id, not the parent's history. expect(acknowledgementReads.length).toBeGreaterThan(0); expect( diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index 85646d387160d..605dc206928bb 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -197,6 +197,10 @@ function remoteDetailKind(detail: unknown): RemoteDetailKind { } } +// t4 fork: most of these timeouts were a host that had gone away (the desktop app closed). +const NO_HOST_ANSWER_REASON = + "The browser never answered: no T3 browser may be attached (the T3 desktop app is closed or asleep). Use headless playwright instead (the `playwright` skill)."; + const readRemoteTimeoutMs = (detail: unknown): number | undefined => { if (typeof detail !== "object" || detail === null || !("timeoutMs" in detail)) return undefined; const timeoutMs = detail.timeoutMs; @@ -665,7 +669,10 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { if (input.updateCurrentTab !== false) { yield* disconnect(connection.clientId, connection.queue, true); } - return yield* new PreviewAutomationTimeoutError(requestContext); + return yield* new PreviewAutomationTimeoutError({ + ...requestContext, + reason: NO_HOST_ANSWER_REASON, + }); }), onSome: (value) => Effect.succeed(value as A), }); diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 711160533c568..75dbc78722a84 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1056,6 +1056,42 @@ it.effect("only the caller that prepared a pending upload can discard it", () => ), ); +const layerOrchestratorToolkitWith = (mocks: { + readonly threads?: Partial; + readonly scheduledTasks?: Partial; +}) => + layerOrchestratorToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)(mocks.threads ?? {})), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})), + Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})), + Layer.provide( + Layer.mock(ScheduledTaskService.ScheduledTaskService)(mocks.scheduledTasks ?? {}), + ), + Layer.provide(Layer.mock(ProjectService.ProjectService)({})), + Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), + ); + +const callAsClient = (name: string, args: Record) => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + return yield* server + .callTool({ name, arguments: args }) + .pipe( + Effect.provideService( + McpInvocationContext.McpInvocationContext, + clientScope("full-access"), + ), + Effect.provideService(McpSchema.McpServerClient, client), + ); + }); + it.effect( "t3_thread_list settled:false with an empty statuses list lists the unsettled threads", () => { @@ -1065,46 +1101,100 @@ it.effect( settledOverride: "settled", } as const; return Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const result = yield* server - .callTool({ - name: "t3_thread_list", - arguments: { projectId: unsettled.projectId, settled: false, statuses: [] }, - }) - .pipe( - Effect.provideService( - McpInvocationContext.McpInvocationContext, - clientScope("full-access"), - ), - Effect.provideService(McpSchema.McpServerClient, client), - ); + const args = { projectId: unsettled.projectId, settled: false, statuses: [] }; + const result = yield* callAsClient("t3_thread_list", args); expect(result.isError).toBe(false); - expect(result.structuredContent).toMatchObject({ - threads: [{ threadId: unsettled.id, settled: false }], + // Compact rows: what agents pick a thread by, and where the rest is. + expect(result.structuredContent).toEqual({ + projectId: unsettled.projectId, + currentThreadId: null, + threads: [ + { + threadId: unsettled.id, + title: unsettled.title, + link: expect.any(String), + status: "running", + updatedAt: expect.any(String), + }, + ], + nextCursor: null, total: 1, + more: expect.stringContaining("`detail: true`"), }); + + const detailed = yield* callAsClient("t3_thread_list", { ...args, detail: true }); + expect(detailed.structuredContent).toMatchObject({ + threads: [ + { + threadId: unsettled.id, + projectId: unsettled.projectId, + model: "gpt-5", + runtimeMode: "full-access", + settled: false, + createdAt: expect.any(String), + }, + ], + total: 1, + }); + expect(detailed.structuredContent).not.toHaveProperty("more"); }).pipe( Effect.provide( - layerOrchestratorToolkit.pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provide(NodeCrypto.layer), - Layer.provide( - Layer.mock(ThreadManagement.ThreadManagementService)({ - listProjectThreads: () => Effect.succeed([unsettled, settled]), - }), - ), - Layer.provide(ServerSettings.layerTest()), - Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})), - Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})), - Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), - Layer.provide(Layer.mock(ProjectService.ProjectService)({})), - Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), - Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), - Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), - Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), - Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), - ), + layerOrchestratorToolkitWith({ + threads: { listProjectThreads: () => Effect.succeed([unsettled, settled]) }, + }), ), ); }, ); + +it.effect("list_scheduled_tasks rows preview each prompt and read one task in full by id", () => { + const longPrompt = `WAKE note: ${"check the deploy and report. ".repeat(40)}`; + const tasks = [ + { + ...(scheduledTask("task-long", "auto") as object), + prompt: longPrompt, + webhook: { path: "/hooks/x", url: "https://t3.example/hooks/x", hasSecret: false }, + }, + scheduledTask("task-short", "auto"), + ] as never; + return Effect.gen(function* () { + const listed = yield* callAsClient("list_scheduled_tasks", {}); + expect(listed.isError).toBe(false); + expect(listed.structuredContent).toEqual({ + tasks: [ + { + scheduledTaskId: "task-long", + title: "task-long", + enabled: true, + boundThreadId: null, + schedule: { type: "interval", everyMs: 3_600_000 }, + nextRunAt: null, + lastRunStatus: "never", + promptPreview: longPrompt.slice(0, 120), + promptLength: longPrompt.length, + }, + expect.objectContaining({ promptPreview: "Check the build", promptLength: 15 }), + ], + more: expect.stringContaining("`scheduledTaskId`"), + }); + + const full = yield* callAsClient("list_scheduled_tasks", { scheduledTaskId: "task-long" }); + expect(full.structuredContent).toEqual({ + tasks: [], + task: expect.objectContaining({ + scheduledTaskId: "task-long", + prompt: longPrompt, + webhookUrl: "https://t3.example/hooks/x", + }), + }); + + const missing = yield* callAsClient("list_scheduled_tasks", { scheduledTaskId: "task-gone" }); + expect(declaredFailure(missing)).toMatchObject({ code: "task_not_found" }); + }).pipe( + Effect.provide( + layerOrchestratorToolkitWith({ + scheduledTasks: { list: () => Effect.succeed({ tasks }) }, + }), + ), + ); +}); diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 811d4ba5aae8b..eba506e91a4fe 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -181,14 +181,16 @@ const handlers = { const scope = yield* McpInvocationContext.McpInvocationContext; const service = yield* OrchestratorMcpService.OrchestratorMcpService; const result = yield* service.listScheduledTasks(scope, input); + // t4 fork (AI-93): one task in full by id; list rows are compact. + if (input.scheduledTaskId !== undefined) return { tasks: [], task: result.tasks[0] }; // t4 fork: a thread sees its own pending tasks unless it asks for all. const { caller } = yield* readCaller(); - if (all === true || caller === undefined || input.projectId !== undefined) return result; - return { - tasks: result.tasks.filter( - (task) => task.boundThreadId === caller.id && task.nextRunAt !== null, - ), - }; + if (all === true || caller === undefined || input.projectId !== undefined) { + return OrchestratorMcpService.scheduledTaskRows(result.tasks); + } + return OrchestratorMcpService.scheduledTaskRows( + result.tasks.filter((task) => task.boundThreadId === caller.id && task.nextRunAt !== null), + ); }), ), delete_scheduled_task: McpToolAccess.writes((input) => @@ -225,7 +227,13 @@ const handlers = { ...result, threads: result.threads.map((thread) => { const t4 = facts.get(thread.threadId); - return t4 === undefined ? thread : { ...thread, t4 }; + if (t4 === undefined) return thread; + // t4 fork (AI-93): a compact row leaves out a parent it does not have. + const { parentThreadId, ...rest } = t4; + return { + ...thread, + t4: input.detail === true || parentThreadId !== null ? t4 : rest, + }; }), }; }), @@ -266,8 +274,11 @@ const handlers = { .getThreadShell(input.threadId) .pipe(Effect.mapError(unavailable)); if (target !== null) { + // t4 fork: a plain message from another thread waits for a running turn + // to end instead of cutting the command it runs; `steer`/`restart` cut in (AI-93). + const mode = (input.mode ?? "auto") === "auto" ? ("queue" as const) : input.mode; const message = yield* t4.value - .decorate({ sender: caller, target, text: input.message }) + .decorate({ sender: caller, target, text: input.message, queued: mode === "queue" }) .pipe( Effect.mapError( (error) => @@ -277,7 +288,7 @@ const handlers = { }), ), ); - return yield* service.sendToThread(scope, { ...input, message }); + return yield* service.sendToThread(scope, { ...input, message, mode }); } } return yield* service.sendToThread(scope, input); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 692b1505236d5..ad8ff029ed942 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -175,7 +175,7 @@ const ScheduleTaskTool = Tool.make("schedule_task", { const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", { parameters: OrchestratorMcpListScheduledTasksInput, description: - "List scheduled tasks. Omit `projectId` for this thread's project. Pass a `scheduledTaskId` to `schedule_task` or `delete_scheduled_task`. In a scheduled run, do not call this to find your task. Do the prompt.", + "List scheduled tasks. Omit `projectId` for this thread's project. Rows show the first 120 chars of each prompt and its `promptLength`; pass `scheduledTaskId` here to read one task in full (`task`, with its webhook URL). Pass a `scheduledTaskId` to `schedule_task` or `delete_scheduled_task`. In a scheduled run, do not call this to find your task. Do the prompt.", success: OrchestratorMcpListScheduledTasksResult, failure: OrchestratorMcpFailure, failureMode: "return", @@ -227,7 +227,7 @@ const CreateThreadsTool = Tool.make("create_threads", { const ThreadListTool = Tool.make("t3_thread_list", { description: - "List threads newest first, in one project or with `allProjects`. Page with `cursor`. Each thread's `t4` gives its state (running, waiting-you, settled, snoozed, idle), whether it is the release manager, the handoffs it owes and is owed (t3_owed), and its linked issues.", + "List threads newest first, in one project or with `allProjects`. Page with `cursor`. Rows are compact; `detail: true` adds model, modes, creator and timestamps, and `t3_thread_read` shows one thread in full. Each thread's `t4` gives its state (running, waiting-you, settled, snoozed, idle), whether it is the release manager, the handoffs it owes and is owed (t3_owed), and its linked issues.", parameters: OrchestratorMcpThreadListInput, success: OrchestratorMcpThreadListResult, failure: OrchestratorMcpFailure, @@ -241,7 +241,7 @@ const ThreadListTool = Tool.make("t3_thread_list", { const ThreadReadTool = Tool.make("t3_thread_read", { description: - "Read any thread by id. `messages` (default): user and assistant messages and plans. `activity`: all timeline items. Keep reads small: low `limit` and `maxCharsPerItem`. Page with `afterPosition=nextPosition`. Cut-off text: `itemId` with `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. In your reply, name it as its `link` verbatim.", + "Read any thread by id. `messages` (default): user and assistant messages and plans. `activity`: all timeline items. Keep reads small: low `limit`. Page with `afterPosition=nextPosition`. Item text past `maxCharsPerItem` (default 1500) is cut: the item has `textTruncated`, `remainingChars` and `nextTextOffset`; read on with `itemId` and `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. In your reply, name it as its `link` verbatim.", parameters: OrchestratorMcpThreadReadInput, success: OrchestratorMcpThreadReadResult, failure: OrchestratorMcpFailure, @@ -273,7 +273,7 @@ const ThreadUpdateTool = Tool.make("t3_thread_update", { const ThreadSendTool = Tool.make("t3_thread_send", { description: - "Send a message to any thread. The target cannot run with broader modes than yours. `mode:'auto'` starts an idle thread, steers a running turn, or queues. `queue`: new turn. `steer`: mid-turn update. `restart`: interrupt and restart. A send to a finished child thread starts a fresh task and returns its `taskId`. In your reply, name it as its `link` verbatim.", + "Send a message to any thread. The target cannot run with broader modes than yours. `mode:'auto'` starts an idle thread; a running one gets it when its turn ends, so the command it runs is never cut. `queue`: new turn. `steer`: into the running turn now, which can cancel its running tool call - only when it must change course. `restart`: interrupt and restart. A send to a finished child thread starts a fresh task and returns its `taskId`. In your reply, name it as its `link` verbatim.", parameters: OrchestratorMcpThreadSendInput, success: OrchestratorMcpThreadSendResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/mcp/toolkits/t4/handlers.ts b/apps/server/src/mcp/toolkits/t4/handlers.ts index 62b87541f0433..4dcf75c06b0bf 100644 --- a/apps/server/src/mcp/toolkits/t4/handlers.ts +++ b/apps/server/src/mcp/toolkits/t4/handlers.ts @@ -16,6 +16,8 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import type { Tool } from "effect/ai"; import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts"; import * as Project from "../../../project/ProjectService.ts"; @@ -25,8 +27,10 @@ import * as T4Decisions from "../../../t4/T4Decisions.ts"; import * as T4Delivery from "../../../t4/T4Delivery.ts"; import * as FyiDigest from "../../../t4/fyiDigest.ts"; import * as T4Ledger from "../../../t4/T4Ledger.ts"; +import * as T4Releases from "../../../t4/T4Releases.ts"; import * as T4RunWatch from "../../../t4/T4RunWatch.ts"; import * as T4Store from "../../../t4/T4Store.ts"; +import * as ToolCallLog from "../../../t4/toolCallLog.ts"; import { ago, issueIdIn, @@ -39,7 +43,7 @@ import { } from "../../../t4/T4Threads.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { readCaller, unavailable } from "../../threadAccess.ts"; -import { T4Toolkit } from "./tools.ts"; +import { HandoffTool, T4Toolkit } from "./tools.ts"; type Shell = OrchestrationV2ThreadShell; @@ -201,23 +205,35 @@ export const prOfHandoff = (body: string): number | undefined => { return Number.isInteger(pr) && pr > 0 ? pr : undefined; }; -/** One release notice per owner and state (release_queue). */ -export const releaseNotice = ( - state: "staging" | "shipped" | "failed", - prs: ReadonlyArray, - note: string | null, -) => { - const list = prs.map((pr) => `#${pr}`).join(", "); - const plural = prs.length === 1 ? "PR" : "PRs"; - switch (state) { - case "staging": - return `staging: ${plural} ${list} ${prs.length === 1 ? "is" : "are"} on staging. Verify there.${note ? ` ${note}` : ""}`; - case "shipped": - return `shipped: ${plural} ${list} live in production. Verify, close your Linear.${note ? ` ${note}` : ""}`; - case "failed": - return `release failed on your ${plural} ${list}: ${note ?? "see the release manager's thread"}`; +export const releaseNotice = T4Releases.releaseNotice; + +/** When each thread last read release_queue, for its rows' `changed` flag. */ +const lastReads = new Map(); + +/** A project by id or title (case-insensitive, unique partial), default the caller's. */ +const projectOf = Effect.fn("t4.projectOf")(function* (ref: string | undefined, fallback: string) { + const projects = yield* Project.ProjectService; + if (ref === undefined || ref.trim() === "") { + const own = Option.getOrUndefined( + yield* projects.getById(fallback as never).pipe(Effect.mapError(unavailable)), + ); + if (own === undefined) return yield* invalid("Your thread's project was not found."); + return { id: own.id as string, title: own.title }; } -}; + const shells = yield* projects.listShells().pipe(Effect.mapError(unavailable)); + const needle = ref.trim().toLowerCase(); + const exact = shells.filter( + (shell) => shell.id === ref.trim() || shell.title.toLowerCase() === needle, + ); + const matches = + exact.length > 0 ? exact : shells.filter((shell) => shell.title.toLowerCase().includes(needle)); + if (matches.length === 1) return { id: matches[0]!.id as string, title: matches[0]!.title }; + return yield* invalid( + matches.length === 0 + ? `no project matches '${ref}'` + : `'${ref}' matches several projects: ${matches.map((shell) => shell.title).join(", ")}`, + ); +}); const releaseEntryOf = (row: T4Store.T4ReleaseRow, world: T4Ledger.T4World, now: number) => { const owner = row.ownerThreadId === null ? undefined : world.byId.get(row.ownerThreadId); @@ -276,283 +292,358 @@ const queueHandedOffPr = Effect.fn("t4.queueHandedOffPr")(function* (me: Shell, return pr; }); -export const layer = McpToolAccess.toLayer(T4Toolkit, { - t3_handoff: McpToolAccess.actsAsCaller((input) => - Effect.gen(function* () { - const ledger = yield* T4Ledger.T4Ledger; - const store = yield* T4Store.T4Store; - const delivery = yield* T4Delivery.T4Delivery; - const config = yield* T4Config.T4ServerConfig; - const projects = yield* Project.ProjectService; - const now = yield* nowMs; - const me = yield* callerThread; - const world = yield* ledger.world().pipe(Effect.mapError(ledgerUnavailable)); - const project = Option.getOrUndefined( - yield* projects.getById(me.projectId).pipe(Effect.mapError(unavailable)), - ); - if (project === undefined) return yield* invalid("Your thread's project was not found."); - const includeRetired = input.includeRetired === true; +type HandoffInput = Tool.Parameters; +const HandoffResultJson = Schema.fromJsonString(HandoffTool.successSchema); +const decodeHandoffResult = Schema.decodeUnknownOption(HandoffResultJson); +const encodeHandoffResult = Schema.encodeSync(HandoffResultJson); - if (input.check === true) { - const rm = yield* ledger - .findReleaseManager(world, project.id, includeRetired) - .pipe(Effect.mapError(ledgerUnavailable)); - return { - to: rm === undefined ? null : summaryOf(rm, now), - isReleaseManager: rm !== undefined, - createdReleaseManager: false, - delivery: null, - settled: 0, - nowOwesYou: false, - youStillOweThem: false, - notes: [ - rm === undefined - ? "no release manager for this project" - : `release manager: ${rm.title}`, - ], - }; - } +/** A short stable hash for a handoff's retry key. */ +const fnv1a = (text: string) => { + let hash = 0x811c9dc5; + for (let index = 0; index < text.length; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, 0x01000193); + } + return (hash >>> 0).toString(16); +}; - let done = input.done === true; - let ask = input.ask === true; - let fyi = input.fyi === true; - if (fyi && ask) - return yield* invalid("`fyi` asks for nothing; `ask` asks for a reply - pick one"); - if (input.to !== undefined && !(done || ask || fyi)) { - return yield* invalid( - "say what this handoff does to the ledger:\n" + - " done it answers what you owe them (settles their handoff to you)\n" + - " ask they owe you a reply (`t3_owed` shows it on their side)\n" + - " fyi neither - nothing settled, nothing asked\n" + - "`done` combines with `ask` (finished, and now asking something new) or `fyi` (finished, nothing more).", - ); - } - if (input.to === undefined && fyi) { - return yield* invalid( - "a handoff to the release manager asks it to release - for information only, use `t3_thread_send`", - ); - } - const body = input.message?.trim() ?? ""; - if (body.length === 0) return yield* invalid("empty handoff: pass `message`"); +const SAME_MESSAGE_WINDOW_MS = 60 * 60_000; - const notes: Array = []; - const meIsRm = ledger.isReleaseManager(world, me); - let target: Shell | undefined; - if (input.to !== undefined) { - target = yield* resolveRef(input.to, world); - if (target.id === me.id) return yield* invalid("that is this thread"); - if (ledger.isReleaseManager(world, target) && !meIsRm && !ask) { - // Anything an owner hands the release manager is a release request. - notes.push( - "a handoff to the release manager always asks it to release - recorded as a request", - ); - ask = true; - fyi = false; - } - } else { - if (meIsRm) { - return yield* invalid( - "you are the release manager - answer owners with `t3_handoff` and `to`", - ); - } - target = yield* ledger - .findReleaseManager(world, project.id, includeRetired) - .pipe(Effect.mapError(ledgerUnavailable)); - ask = true; - } +/** + * t4 fork: a handoff runs once per retry key (AI-93). A T3 restart cut handoffs mid-call and the + * agent could not tell whether it had gone out; repeating it now returns the first result. + */ +const handoffOnce = Effect.fn("t4.handoffOnce")(function* (input: HandoffInput) { + const body = input.message?.trim() ?? ""; + if (input.check === true || body.length === 0) return yield* handoff(input); + const store = yield* T4Store.T4Store; + const me = yield* callerThread; + const now = yield* nowMs; + const explicit = input.clientRequestId?.trim() || undefined; + const key = `handoff:${me.id}:${ + explicit ?? + `m${fnv1a([input.to ?? "", input.done, input.ask, input.fyi, input.interrupt, body].join("\u0000"))}` + }`; + const earlier = yield* store.toolCall(key).pipe(Effect.orElseSucceed(() => undefined)); + const recent = + earlier !== undefined && + (explicit !== undefined || now - Date.parse(earlier.startedAt) < SAME_MESSAGE_WINDOW_MS); + if (recent && earlier.finishedAt === null && earlier.current) { + return yield* invalid("this same handoff is being sent right now - don't send it again"); + } + const first = + recent && earlier.result !== null + ? Option.getOrUndefined(decodeHandoffResult(earlier.result)) + : undefined; + if (first !== undefined && earlier !== undefined) { + return { + ...first, + notes: [ + `already handed over ${ago(Date.parse(earlier.startedAt), now)} ago with this same ${explicit === undefined ? "message" : "clientRequestId"} - not sent again`, + ...first.notes, + ], + }; + } + yield* store + .startToolCall({ + id: key, + threadId: me.id, + tool: "t3_handoff", + summary: ToolCallLog.callSummary("t3_handoff", input), + }) + .pipe(Effect.ignoreCause({ log: true })); + return yield* handoff(input).pipe( + Effect.onExit((exit) => + store + .finishToolCall(key, exit._tag === "Success" ? encodeHandoffResult(exit.value) : "failed") + .pipe(Effect.ignoreCause({ log: true })), + ), + ); +}); - const labels = [ - ...(done ? ["answers your handoff"] : []), - ask ? "reply expected" : "no reply needed", - ]; - const toReleaseManager = - !meIsRm && (target === undefined || ledger.isReleaseManager(world, target)); - const userWord = toReleaseManager ? yield* latestUserWord(me, now) : ""; - const header = handoffHeader(me, labels) + userWord; - const footer = ask - ? `\n\n---\nAnswer with \`t3_handoff\` (to: "${shortId(me.id)}", done: true; add fyi: true if you ask nothing back). \`t3_owed\` lists what you still owe.` - : ""; - const summary = (body.split("\n")[0] ?? "").slice(0, 160); - - if (target === undefined) { - // No release manager yet: start one with this handoff as its first turn. - const crypto = yield* SecureRandom.SecureRandom; - const launches = yield* ThreadLaunch.ThreadLaunchService; - const id = yield* crypto.uuidV4().pipe(Effect.orDie); - const title = `${config.releaseManagerTitlePrefix}: ${project.title}`; - const repo = project.workspaceRoot.split("/").filter(Boolean).at(-1) ?? project.title; - const intro = - `You are the release manager for ${project.title}: this project's one persistent release thread. ` + - `Load the \`release-manager\` skill, and the repo's \`${repo}-release-manager\` skill if there is one, and ` + - `follow them. You run in the main checkout and never archive or settle this thread.\n\n`; - const modelSelection = - config.releaseManagerModel ?? project.defaultModelSelection ?? me.modelSelection; - const launched = yield* launches - .launch({ - commandId: CommandId.make(`t4:rm:${id}`), - threadId: ThreadId.make(`t4-rm-${id}`), - projectId: project.id, - title, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - workspaceStrategy: { type: "root" }, - initialMessage: { - messageId: MessageId.make(`t4:rm:${id}`), - senderThreadId: me.id, - text: intro + header + body + footer, - attachments: [], - }, - createdBy: "agent", - creationSource: "mcp", - }) - .pipe(Effect.mapError(unavailable)); - const rmId = launched.projection.thread.id; - const threads = (yield* readCaller()).threads; - yield* threads - .dispatch({ - type: "thread.pin", - commandId: CommandId.make(`t4:rm-pin:${id}`), - threadId: rmId, - }) - .pipe(Effect.ignore); - yield* store.setReleaseManager(project.id, rmId).pipe(Effect.mapError(ledgerUnavailable)); - yield* store - .recordHandoff({ - kind: "handoff", - fromThreadId: me.id, - fromTitle: me.title, - toThreadId: rmId, - projectId: project.id, - summary, - }) - .pipe(Effect.mapError(ledgerUnavailable)); - yield* queueHandedOffPr(me, body); - notes.push( - `no release manager for ${project.title} - started "${title}", pinned, and handed it this`, - ); - const rmShell = yield* threads.getThreadShell(rmId).pipe(Effect.mapError(unavailable)); - return { - to: - rmShell === null - ? { threadId: rmId, shortId: shortId(rmId), title, state: "running" } - : summaryOf(rmShell, now), - isReleaseManager: true, - createdReleaseManager: true, - delivery: "started", - settled: 0, - nowOwesYou: true, - youStillOweThem: false, - notes, - }; - } +const handoff = Effect.fn("t4.handoff")(function* (input: HandoffInput) { + const ledger = yield* T4Ledger.T4Ledger; + const store = yield* T4Store.T4Store; + const delivery = yield* T4Delivery.T4Delivery; + const config = yield* T4Config.T4ServerConfig; + const projects = yield* Project.ProjectService; + const now = yield* nowMs; + const me = yield* callerThread; + const world = yield* ledger.world().pipe(Effect.mapError(ledgerUnavailable)); + const project = Option.getOrUndefined( + yield* projects.getById(me.projectId).pipe(Effect.mapError(unavailable)), + ); + if (project === undefined) return yield* invalid("Your thread's project was not found."); + const includeRetired = input.includeRetired === true; - const settled = done - ? yield* store - .settleHandoffs({ fromThreadId: target.id, toThreadId: me.id }) - .pipe(Effect.mapError(ledgerUnavailable)) - : 0; - // An answer to a thread whose work is closed has no one to read it: the debt is void. - if (done && !ask && isRetired(target)) { - return { - to: summaryOf(target, now), - isReleaseManager: ledger.isReleaseManager(world, target), - createdReleaseManager: false, - delivery: null, - settled, - nowOwesYou: false, - youStillOweThem: false, - notes: [ - `"${target.title}" is ${target.archivedAt === null ? "settled" : "archived"} - its work is closed, so nothing was delivered and anything you owed it is void`, - ], - }; - } - // t4 fork: a pure fyi soon after the last one to this thread is bundled (fyiDigest). - const pureFyi = !done && !ask && input.interrupt !== true; - if ( - pureFyi && - (yield* FyiDigest.queueIfRecent({ - from: me.id, - fromTitle: me.title, - to: target.id, - body, - })) - ) { - return { - to: summaryOf(target, now), - isReleaseManager: ledger.isReleaseManager(world, target), - createdReleaseManager: false, - delivery: "bundled", - settled: 0, - nowOwesYou: false, - youStillOweThem: false, - notes: [ - `bundled: "${target.title}" gets your no-reply-needed updates at most every 10 minutes, as one message - send fyi only for changes it acts on`, - ], - }; - } - // t4 fork: owners schedule a check for `shipped:`; 31 of 59 such wakes - // fired after it had arrived (usa-rs, 2026-10-30). Name them so the owner - // deletes the ones that were only for this release. - const wakesNote = - meIsRm && done && !ledger.isReleaseManager(world, target) - ? yield* pendingWakesNote(target.id, now) - : ""; - const delivered = yield* delivery - .deliver({ - target, - text: header + body + footer + wakesNote, + if (input.check === true) { + const rm = yield* ledger + .findReleaseManager(world, project.id, includeRetired) + .pipe(Effect.mapError(ledgerUnavailable)); + return { + to: rm === undefined ? null : summaryOf(rm, now), + isReleaseManager: rm !== undefined, + createdReleaseManager: false, + delivery: null, + settled: 0, + nowOwesYou: false, + youStillOweThem: false, + notes: [ + rm === undefined ? "no release manager for this project" : `release manager: ${rm.title}`, + ], + }; + } + + let done = input.done === true; + let ask = input.ask === true; + let fyi = input.fyi === true; + if (fyi && ask) + return yield* invalid("`fyi` asks for nothing; `ask` asks for a reply - pick one"); + if (input.to !== undefined && !(done || ask || fyi)) { + return yield* invalid( + "say what this handoff does to the ledger:\n" + + " done it answers what you owe them (settles their handoff to you)\n" + + " ask they owe you a reply (`t3_owed` shows it on their side)\n" + + " fyi neither - nothing settled, nothing asked\n" + + "`done` combines with `ask` (finished, and now asking something new) or `fyi` (finished, nothing more).", + ); + } + if (input.to === undefined && fyi) { + return yield* invalid( + "a handoff to the release manager asks it to release - for information only, use `t3_thread_send`", + ); + } + const body = input.message?.trim() ?? ""; + if (body.length === 0) return yield* invalid("empty handoff: pass `message`"); + + const notes: Array = []; + const meIsRm = ledger.isReleaseManager(world, me); + let target: Shell | undefined; + if (input.to !== undefined) { + target = yield* resolveRef(input.to, world); + if (target.id === me.id) return yield* invalid("that is this thread"); + if (ledger.isReleaseManager(world, target) && !meIsRm && !ask) { + // Anything an owner hands the release manager is a release request. + notes.push( + "a handoff to the release manager always asks it to release - recorded as a request", + ); + ask = true; + fyi = false; + } + } else { + if (meIsRm) { + return yield* invalid( + "you are the release manager - answer owners with `t3_handoff` and `to`", + ); + } + target = yield* ledger + .findReleaseManager(world, project.id, includeRetired) + .pipe(Effect.mapError(ledgerUnavailable)); + ask = true; + } + + const labels = [ + ...(done ? ["answers your handoff"] : []), + ask ? "reply expected" : "no reply needed", + ]; + const toReleaseManager = + !meIsRm && (target === undefined || ledger.isReleaseManager(world, target)); + const userWord = toReleaseManager ? yield* latestUserWord(me, now) : ""; + // t4 fork: a release manager's queue and debts ride on the handoff, and it answers through + // release_queue, so it gets no footer (AI-93: 984 queue reads and 514 t3_owed in 98 h). + // Queued first, so the brief the release manager reads already lists it. + const queuedPr = + toReleaseManager && target !== undefined ? yield* queueHandedOffPr(me, body) : undefined; + if (queuedPr !== undefined) notes.push(`PR #${queuedPr} is in the release manager's queue`); + const rmBrief = + toReleaseManager && target !== undefined + ? yield* T4Releases.releaseManagerBriefFor(target, world, ask ? me : undefined) + : ""; + const header = rmBrief + handoffHeader(me, labels) + userWord; + const footer = + ask && !toReleaseManager + ? `\n\n---\nAnswer with \`t3_handoff\` (to: "${shortId(me.id)}", done: true; add fyi: true if you ask nothing back). \`t3_owed\` lists what you still owe.` + : ""; + const summary = (body.split("\n")[0] ?? "").slice(0, 160); + + if (target === undefined) { + // No release manager yet: start one with this handoff as its first turn. + const crypto = yield* SecureRandom.SecureRandom; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const id = yield* crypto.uuidV4().pipe(Effect.orDie); + const title = `${config.releaseManagerTitlePrefix}: ${project.title}`; + const repo = project.workspaceRoot.split("/").filter(Boolean).at(-1) ?? project.title; + const intro = + `You are the release manager for ${project.title}: this project's one persistent release thread. ` + + `Load the \`release-manager\` skill, and the repo's \`${repo}-release-manager\` skill if there is one, and ` + + `follow them. You run in the main checkout and never archive or settle this thread.\n\n`; + const modelSelection = + config.releaseManagerModel ?? project.defaultModelSelection ?? me.modelSelection; + const launched = yield* launches + .launch({ + commandId: CommandId.make(`t4:rm:${id}`), + threadId: ThreadId.make(`t4-rm-${id}`), + projectId: project.id, + title, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + initialMessage: { + messageId: MessageId.make(`t4:rm:${id}`), senderThreadId: me.id, - interrupt: input.interrupt === true, - notice: !ask, - }) - .pipe(Effect.mapError((error) => invalid(error.message))); - if (pureFyi) yield* FyiDigest.noteDelivered(me.id, target.id); - if (ask) { - yield* store - .recordHandoff({ - kind: "handoff", - fromThreadId: me.id, - fromTitle: me.title, - toThreadId: target.id, - projectId: target.projectId, - summary, - }) - .pipe(Effect.mapError(ledgerUnavailable)); - } - const targetIsRm = ledger.isReleaseManager(world, target); - if (targetIsRm && !meIsRm) { - const pr = yield* queueHandedOffPr(me, body); - if (pr !== undefined) notes.push(`PR #${pr} is in the release manager's queue`); - } - if (done) { - notes.push( - settled > 0 - ? `settled ${settled} open handoff(s) from "${target.title}"` - : `"${target.title}" had no open handoff to you - done settled nothing`, - ); - } - if (ask) notes.push(`"${target.title}" now owes you a reply (\`t3_owed\` with all)`); - const youStillOweThem = - !done && - world.live.some((entry) => entry.fromThreadId === target.id && entry.toThreadId === me.id); - if (youStillOweThem) { - notes.push( - `you still owe "${target.title}" an answer - pass done on the handoff that finishes it`, - ); - } - return { - to: summaryOf(target, now), - isReleaseManager: targetIsRm, - createdReleaseManager: false, - delivery: delivered.how, - settled, - nowOwesYou: ask, - youStillOweThem, - notes, - }; - }), - ), + text: intro + header + body + footer, + attachments: [], + }, + createdBy: "agent", + creationSource: "mcp", + }) + .pipe(Effect.mapError(unavailable)); + const rmId = launched.projection.thread.id; + const threads = (yield* readCaller()).threads; + yield* threads + .dispatch({ + type: "thread.pin", + commandId: CommandId.make(`t4:rm-pin:${id}`), + threadId: rmId, + }) + .pipe(Effect.ignore); + yield* store.setReleaseManager(project.id, rmId).pipe(Effect.mapError(ledgerUnavailable)); + yield* store + .recordHandoff({ + kind: "handoff", + fromThreadId: me.id, + fromTitle: me.title, + toThreadId: rmId, + projectId: project.id, + summary, + }) + .pipe(Effect.mapError(ledgerUnavailable)); + yield* queueHandedOffPr(me, body); + notes.push( + `no release manager for ${project.title} - started "${title}", pinned, and handed it this`, + ); + const rmShell = yield* threads.getThreadShell(rmId).pipe(Effect.mapError(unavailable)); + return { + to: + rmShell === null + ? { threadId: rmId, shortId: shortId(rmId), title, state: "running" } + : summaryOf(rmShell, now), + isReleaseManager: true, + createdReleaseManager: true, + delivery: "started", + settled: 0, + nowOwesYou: true, + youStillOweThem: false, + notes, + }; + } + + const settled = done + ? yield* store + .settleHandoffs({ fromThreadId: target.id, toThreadId: me.id }) + .pipe(Effect.mapError(ledgerUnavailable)) + : 0; + // An answer to a thread whose work is closed has no one to read it: the debt is void. + if (done && !ask && isRetired(target)) { + return { + to: summaryOf(target, now), + isReleaseManager: ledger.isReleaseManager(world, target), + createdReleaseManager: false, + delivery: null, + settled, + nowOwesYou: false, + youStillOweThem: false, + notes: [ + `"${target.title}" is ${target.archivedAt === null ? "settled" : "archived"} - its work is closed, so nothing was delivered and anything you owed it is void`, + ], + }; + } + // t4 fork: a pure fyi soon after the last one to this thread is bundled (fyiDigest). + const pureFyi = !done && !ask && input.interrupt !== true; + if ( + pureFyi && + (yield* FyiDigest.queueIfRecent({ + from: me.id, + fromTitle: me.title, + to: target.id, + body, + })) + ) { + return { + to: summaryOf(target, now), + isReleaseManager: ledger.isReleaseManager(world, target), + createdReleaseManager: false, + delivery: "bundled", + settled: 0, + nowOwesYou: false, + youStillOweThem: false, + notes: [ + `bundled: "${target.title}" gets your no-reply-needed updates at most every 10 minutes, as one message - send fyi only for changes it acts on`, + ], + }; + } + // t4 fork: owners schedule a check for `shipped:`; 31 of 59 such wakes + // fired after it had arrived (usa-rs, 2026-10-30). Name them so the owner + // deletes the ones that were only for this release. + const wakesNote = + meIsRm && done && !ledger.isReleaseManager(world, target) + ? yield* pendingWakesNote(target.id, now) + : ""; + const delivered = yield* delivery + .deliver({ + target, + text: header + body + footer + wakesNote, + senderThreadId: me.id, + interrupt: input.interrupt === true, + patient: pureFyi, + notice: !ask, + }) + .pipe(Effect.mapError((error) => invalid(error.message))); + if (pureFyi) yield* FyiDigest.noteDelivered(me.id, target.id); + if (ask) { + yield* store + .recordHandoff({ + kind: "handoff", + fromThreadId: me.id, + fromTitle: me.title, + toThreadId: target.id, + projectId: target.projectId, + summary, + }) + .pipe(Effect.mapError(ledgerUnavailable)); + } + const targetIsRm = ledger.isReleaseManager(world, target); + if (done) { + notes.push( + settled > 0 + ? `settled ${settled} open handoff(s) from "${target.title}"` + : `"${target.title}" had no open handoff to you - done settled nothing`, + ); + } + if (ask) notes.push(`"${target.title}" now owes you a reply (\`t3_owed\` with all)`); + const youStillOweThem = + !done && + world.live.some((entry) => entry.fromThreadId === target.id && entry.toThreadId === me.id); + if (youStillOweThem) { + notes.push( + `you still owe "${target.title}" an answer - pass done on the handoff that finishes it`, + ); + } + return { + to: summaryOf(target, now), + isReleaseManager: targetIsRm, + createdReleaseManager: false, + delivery: delivered.how, + settled, + nowOwesYou: ask, + youStillOweThem, + notes, + }; +}); + +export const layer = McpToolAccess.toLayer(T4Toolkit, { + t3_handoff: McpToolAccess.actsAsCaller(handoffOnce), t3_owed: McpToolAccess.reads((input) => Effect.gen(function* () { @@ -861,11 +952,36 @@ export const layer = McpToolAccess.toLayer(T4Toolkit, { const now = yield* nowMs; const me = yield* callerThread; const world = yield* ledger.world().pipe(Effect.mapError(ledgerUnavailable)); + const meIsRm = ledger.isReleaseManager(world, me); const notes: Array = []; const notified: Array = []; + + // Waiting on a PR this thread doesn't own (AI-93): it hears staging and shipped too. + for (const [ref, stop] of [ + [input.waitFor, false], + [input.stopWaiting, true], + ] as const) { + if (ref === undefined) continue; + if (!Number.isInteger(ref.pr) || ref.pr <= 0) { + return yield* invalid(`'${ref.pr}' is not a PR number`); + } + const project = yield* projectOf(ref.project, me.projectId); + const waiter = { projectId: project.id, pr: ref.pr, threadId: me.id }; + const changed = yield* ( + stop ? store.removeReleaseWaiter(waiter) : store.addReleaseWaiter(waiter) + ).pipe(Effect.mapError(ledgerUnavailable)); + notes.push( + stop + ? changed + ? `no longer waiting on PR #${ref.pr} in ${project.title}` + : `you weren't waiting on PR #${ref.pr} in ${project.title}` + : `waiting on PR #${ref.pr} in ${project.title}: you get its staging and shipped notices as they happen - end your turn, no wake needed`, + ); + } + const updates = input.prs ?? []; if (updates.length > 0) { - if (!ledger.isReleaseManager(world, me)) { + if (!meIsRm) { return yield* invalid( "only this project's release manager records releases - hand your PR over with `t3_handoff` (no `to`)", ); @@ -958,6 +1074,7 @@ export const layer = McpToolAccess.toLayer(T4Toolkit, { target, text: header + body + footer + wakesNote, senderThreadId: me.id, + patient: !done, notice: !ask, }) .pipe(Effect.result); @@ -979,22 +1096,101 @@ export const layer = McpToolAccess.toLayer(T4Toolkit, { } notified.push(`${state}: "${target.title}" (${prs.map((pr) => `#${pr}`).join(", ")})`); } + // Threads waiting on these PRs hear it too, never twice with their owner's notice. + const projectTitle = + Option.getOrUndefined( + yield* Project.ProjectService.pipe( + Effect.flatMap((projects) => projects.getById(me.projectId)), + Effect.orElseSucceed(() => Option.none()), + ), + )?.title ?? "this project"; + for (const row of changed) { + if (row.state !== "staging" && row.state !== "shipped" && row.state !== "failed") + continue; + const waiters = yield* store + .releaseWaiters({ projectId: row.projectId, pr: row.pr }) + .pipe(Effect.orElseSucceed(() => [])); + for (const waiter of waiters) { + if (row.state === "shipped") { + yield* store.removeReleaseWaiter(waiter).pipe(Effect.ignore); + } + const target = world.byId.get(waiter.threadId); + if (target === undefined || isRetired(target) || target.id === row.ownerThreadId) + continue; + const sent = yield* delivery + .deliver({ + target, + text: T4Releases.waiterNotice(row.state, row, projectTitle), + senderThreadId: me.id, + patient: true, + notice: true, + }) + .pipe(Effect.result); + if (Result.isSuccess(sent)) { + notified.push(`${row.state} (waiting): "${target.title}" (#${row.pr})`); + } + } + } } } - const rows = yield* store - .releaseQueue({ - projectId: me.projectId, - shippedSince: - input.all === true - ? DateTime.formatIso(DateTime.makeUnsafe(now - 7 * 86_400_000)) - : undefined, - }) + + // Reads: a release manager sees its whole queue; anyone else its own PRs and the ones it + // waits on, unless `all`. Rows are compact unless `detail` (AI-93: reads were 84 KB). + const shippedSince = + input.all === true + ? DateTime.formatIso(DateTime.makeUnsafe(now - 7 * 86_400_000)) + : undefined; + const projectRows = yield* store + .releaseQueue({ projectId: me.projectId, shippedSince }) .pipe(Effect.mapError(ledgerUnavailable)); - return { - entries: rows.map((row) => releaseEntryOf(row, world, now)), - notified, - notes, - }; + const waited = yield* store + .releaseWaiters({ threadId: me.id }) + .pipe(Effect.mapError(ledgerUnavailable)); + const waitedElsewhere = waited.filter((waiter) => waiter.projectId !== me.projectId); + const otherRows = + waitedElsewhere.length === 0 + ? [] + : (yield* store + .releaseQueue({ + shippedSince: + shippedSince ?? DateTime.formatIso(DateTime.makeUnsafe(now - 86_400_000)), + }) + .pipe(Effect.mapError(ledgerUnavailable))).filter((row) => + waitedElsewhere.some( + (waiter) => waiter.projectId === row.projectId && waiter.pr === row.pr, + ), + ); + const isWaited = (row: T4Store.T4ReleaseRow) => + waited.some((waiter) => waiter.projectId === row.projectId && waiter.pr === row.pr); + const scoped = + meIsRm || input.all === true + ? projectRows + : projectRows.filter((row) => row.ownerThreadId === me.id || isWaited(row)); + const rows = [...scoped, ...otherRows]; + const hidden = projectRows.length - scoped.length; + if (hidden > 0) { + notes.push( + `${hidden} other PR${hidden === 1 ? "" : "s"} in this project's queue not shown - pass \`all\` to see the whole queue`, + ); + } + const lastReadAt = lastReads.get(me.id); + lastReads.set(me.id, DateTime.formatIso(DateTime.makeUnsafe(now))); + if (input.detail === true) { + return { + entries: rows.map((row) => releaseEntryOf(row, world, now)), + notified, + notes, + }; + } + const entries = rows.map((row) => T4Releases.compactEntry(row, world, now, lastReadAt)); + if ( + lastReadAt !== undefined && + entries.length > 0 && + entries.every((entry) => !entry.changed) + ) { + notes.push(`nothing changed since your last read ${ago(Date.parse(lastReadAt), now)} ago`); + } + return { entries, notified, notes }; }), ), }); diff --git a/apps/server/src/mcp/toolkits/t4/release.test.ts b/apps/server/src/mcp/toolkits/t4/release.test.ts index 13e6d74b99aba..294e6c260316c 100644 --- a/apps/server/src/mcp/toolkits/t4/release.test.ts +++ b/apps/server/src/mcp/toolkits/t4/release.test.ts @@ -34,7 +34,7 @@ describe("t4 release queue helpers", () => { it("writes one notice per owner and state", () => { expect(releaseNotice("staging", [12], null)).toBe( - "staging: PR #12 is on staging. Verify there.", + "staging: PR #12 is on staging. Verify there. Don't settle yet: `shipped:` comes when it is live.", ); expect(releaseNotice("shipped", [12, 14], null)).toBe( "shipped: PRs #12, #14 live in production. Verify, close your Linear.", @@ -46,9 +46,13 @@ describe("t4 release queue helpers", () => { }); const OWNER = ThreadId.make("t4-owner-0001"); +const OTHER = ThreadId.make("t4-owner-0002"); +const WAITER = ThreadId.make("t4-waiter-0001"); const RM = ThreadId.make("t4-rm-0001"); const shells = new Map([ [OWNER, { ...McpToolAccessTestkit.liveThreadShell(OWNER), title: "USA-9 Fix" }], + [OTHER, { ...McpToolAccessTestkit.liveThreadShell(OTHER), title: "USA-10 Other" }], + [WAITER, { ...McpToolAccessTestkit.liveThreadShell(WAITER), title: "USA-455 Waits" }], [ RM, { @@ -84,7 +88,7 @@ const scopeOf = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => capabilities: new Set(["orchestration"]), }); -const delivered: Array<{ to: string; text: string; notice: boolean }> = []; +const delivered: Array<{ to: string; text: string; notice: boolean; patient: boolean }> = []; const ledgerLayer = Layer.effect( T4Ledger.T4Ledger, @@ -127,6 +131,7 @@ const layer = McpHttpServer.layerT4Toolkit.pipe( to: input.target.id, text: input.text, notice: input.notice === true, + patient: input.patient === true, }); return { delivery: "started", how: "started a turn" } as never; }), @@ -134,6 +139,10 @@ const layer = McpHttpServer.layerT4Toolkit.pipe( Layer.mock(Project.ProjectService)({ getById: (id) => Effect.succeedSome({ id, title: "app", workspaceRoot: "/srv/Code/app" } as never), + listShells: () => + Effect.succeed([ + { id: McpToolAccessTestkit.liveThreadShell(OWNER).projectId, title: "app" }, + ] as never), }), Layer.mock(ThreadLaunch.ThreadLaunchService)({}), Layer.mock(T4RunWatch.T4RunWatch)({}), @@ -173,8 +182,29 @@ it.effect( const queued = yield* call(RM, "release_queue", {}); expect(queued.body.entries).toMatchObject([ - { pr: 2340, state: "queued", issue: "USA-9", owner: { title: "USA-9 Fix" } }, + { pr: 2340, state: "queued", issue: "USA-9", owner: "USA-9 Fix (owner-00)", changed: true }, ]); + const detail = yield* call(RM, "release_queue", { detail: true }); + expect(detail.body.entries[0]).toMatchObject({ owner: { title: "USA-9 Fix" } }); + // Read again with nothing moved: the rows say so. + const again = yield* call(RM, "release_queue", {}); + expect(again.body.entries[0].changed).toBe(false); + expect(again.body.notes[0]).toMatch(/^nothing changed since your last read/); + + // Another owner's PR, and a thread waiting on a PR it doesn't own. + yield* call(OTHER, "t3_handoff", { message: "PR #2399 ready, merge word given" }); + const waiting = yield* call(WAITER, "release_queue", { waitFor: { pr: 2340 } }); + expect(waiting.body.notes[0]).toMatch(/^waiting on PR #2340 in app/); + // Owners see their own PRs (and the ones they wait on), not the whole queue. + const mine = yield* call(OWNER, "release_queue", {}); + expect(mine.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2340]); + expect(mine.body.notes).toContain( + "1 other PR in this project's queue not shown - pass `all` to see the whole queue", + ); + const theirs = yield* call(WAITER, "release_queue", {}); + expect(theirs.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2340]); + const everything = yield* call(OWNER, "release_queue", { all: true }); + expect(everything.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2340, 2399]); // Owners can read the queue but not move it. const refused = yield* call(OWNER, "release_queue", { @@ -195,18 +225,25 @@ it.effect( { pr: 2341, state: "staging", owner: "USA-9 Fix" }, ], }); - expect(staged.body.notified).toEqual(['staging: "USA-9 Fix" (#2340, #2341)']); - expect(delivered).toHaveLength(1); - expect(delivered[0]).toMatchObject({ to: OWNER, notice: true }); + expect(staged.body.notified).toEqual([ + 'staging: "USA-9 Fix" (#2340, #2341)', + 'staging (waiting): "USA-455 Waits" (#2340)', + ]); + expect(delivered).toHaveLength(2); + // staging asks nothing: it waits for a running turn instead of cutting its command. + expect(delivered[0]).toMatchObject({ to: OWNER, notice: true, patient: true }); + expect(delivered[1]).toMatchObject({ to: WAITER, notice: true, patient: true }); + expect(delivered[1]!.text).toContain("PR #2340"); + expect(delivered[1]!.text).toContain("which you are waiting on, is on staging"); expect(delivered[0]!.text).toContain( "staging: PRs #2340, #2341 are on staging. Verify there.", ); // staging is fyi: the owner's handoff stays open. - expect((yield* store.openHandoffs()).map((h) => h.fromThreadId)).toEqual([OWNER]); + expect((yield* store.openHandoffs()).map((h) => h.fromThreadId)).toEqual([OWNER, OTHER]); // The same state again sends nothing. yield* call(RM, "release_queue", { prs: [{ pr: 2340, state: "staging" }] }); - expect(delivered).toHaveLength(1); + expect(delivered).toHaveLength(2); const failedWithoutNote = yield* call(RM, "release_queue", { prs: [{ pr: 2341, state: "failed" }], @@ -219,13 +256,53 @@ it.effect( { pr: 2341, state: "shipped" }, ], }); - expect(shipped.body.notified).toEqual(['shipped: "USA-9 Fix" (#2340, #2341)']); - expect(delivered[1]!.text).toContain("answers your handoff"); - expect(delivered[1]!.text).toContain("shipped: PRs #2340, #2341 live in production"); - expect(yield* store.openHandoffs()).toEqual([]); - expect(shipped.body.entries).toEqual([]); + expect(shipped.body.notified).toEqual([ + 'shipped: "USA-9 Fix" (#2340, #2341)', + 'shipped (waiting): "USA-455 Waits" (#2340)', + ]); + // shipped answers the owner's handoff, so it reaches a running turn at once. + expect(delivered[2]).toMatchObject({ to: OWNER, patient: false }); + expect(delivered[2]!.text).toContain("answers your handoff"); + expect(delivered[2]!.text).toContain("shipped: PRs #2340, #2341 live in production"); + expect(delivered[3]!.text).toContain("You are no longer waiting on it"); + expect((yield* store.openHandoffs()).map((h) => h.fromThreadId)).toEqual([OTHER]); + expect(shipped.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2399]); + expect(yield* store.releaseWaiters({ threadId: WAITER })).toEqual([]); const recent = yield* call(RM, "release_queue", { all: true }); - expect(recent.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2340, 2341]); + expect(recent.body.entries.map((e: { pr: number }) => e.pr)).toEqual([2340, 2341, 2399]); expect(recent.body.entries[0]).toMatchObject({ commit: "abc1234", state: "shipped" }); }).pipe(Effect.provide(layer)), ); + +it.effect( + "a handoff to the release manager carries its queue and no footer, and runs once per key", + () => + Effect.gen(function* () { + delivered.length = 0; + const message = "PR #77 is green - merge word given (USA-9)"; + const first = yield* call(OWNER, "t3_handoff", { message }); + expect(first.isError).toBe(false); + expect(delivered).toHaveLength(1); + const text = delivered[0]!.text; + expect(text).toMatch(/^\(t4: Your queue: \d+ open - .*#77 queued/); + expect(text).toContain("You owe 1 thread an answer"); + expect(text).not.toContain("t3_owed` lists what you still owe"); + + // The same handoff again (a retry after a cut connection) is not sent twice. + const repeat = yield* call(OWNER, "t3_handoff", { message }); + expect(repeat.isError).toBe(false); + expect(repeat.body.notes[0]).toMatch(/^already handed over .* with this same message/); + expect(delivered).toHaveLength(1); + const keyed = yield* call(OWNER, "t3_handoff", { + message: "PR #78 too", + clientRequestId: "k1", + }); + const keyedAgain = yield* call(OWNER, "t3_handoff", { + message: "PR #78 too (retry)", + clientRequestId: "k1", + }); + expect(keyed.isError).toBe(false); + expect(keyedAgain.body.notes[0]).toMatch(/clientRequestId - not sent again$/); + expect(delivered).toHaveLength(2); + }).pipe(Effect.provide(layer)), +); diff --git a/apps/server/src/mcp/toolkits/t4/tools.ts b/apps/server/src/mcp/toolkits/t4/tools.ts index 119af38a2c098..f31c16df55e27 100644 --- a/apps/server/src/mcp/toolkits/t4/tools.ts +++ b/apps/server/src/mcp/toolkits/t4/tools.ts @@ -50,19 +50,25 @@ const ThreadSummary = Schema.Struct({ state: Schema.String, }); -const HandoffTool = Tool.make("t3_handoff", { +export const HandoffTool = Tool.make("t3_handoff", { ...common, description: [ "Hand work to another thread with an explicit effect on the handoff ledger (who owes whom an answer). The ledger moves only on these flags, never on wording.", "Without `to`: hand your finished work to this project's release manager. That always asks it to release (it then owes you an answer); a release manager is created and pinned if the project has none. The release manager itself must name `to`.", "With `to`: say what the handoff does - `done` answers what you owe that thread (settles its handoff to you), `ask` makes it owe you a reply, `fyi` does neither. `done` combines with `ask` (finished, and asking something new) or `fyi` (finished, nothing more). A handoff to a release manager from any other thread is always a request.", - "`interrupt` stops the recipient's running turn and restarts it with your message; otherwise a running turn gets it steered in.", + "A running recipient gets `done`/`ask` steered into its turn at once; a pure `fyi` waits until that turn ends, so the command it runs is never cut. `interrupt` stops its running turn and restarts it with your message.", "`check` returns the project's release manager without sending anything.", ].join(" "), parameters: Schema.Struct({ message: Schema.optional( Schema.String.annotate({ description: "What you hand over. Required unless `check`." }), ), + clientRequestId: Schema.optional( + Schema.String.annotate({ + description: + "Retry key: a handoff repeated with it (or with the same message within an hour) is sent once; the repeat returns the first result.", + }), + ), to: Schema.optional(ThreadRef), done: Schema.optional(Schema.Boolean), ask: Schema.optional(Schema.Boolean), @@ -273,12 +279,32 @@ const ReleaseEntry = Schema.Struct({ shippedAt: Schema.NullOr(Schema.String), }); +const CompactReleaseEntry = Schema.Struct({ + pr: Schema.Number, + state: ReleaseState, + since: Schema.String.annotate({ description: "How long it has been in this state." }), + title: Schema.NullOr(Schema.String), + issue: Schema.NullOr(Schema.String), + owner: Schema.NullOr(Schema.String), + note: Schema.NullOr(Schema.String), + commit: Schema.NullOr(Schema.String), + changed: Schema.Boolean.annotate({ description: "Changed since your last read." }), +}); + +const PrRef = Schema.Struct({ + pr: Schema.Number, + project: Schema.optional( + Schema.String.annotate({ description: "Its project's title or id. Default: yours." }), + ), +}); + const ReleaseQueueTool = Tool.make("release_queue", { ...common, description: [ - "The release manager's queue, kept by t4 (the dashboard shows it as what is on staging). Without `prs`: this project's PRs not yet shipped, oldest first - read it instead of keeping a queue file.", + "The release manager's queue, kept by t4 (the dashboard shows it as what is on staging). Without `prs`: the PRs not yet shipped, oldest first, as compact rows (`changed` marks rows changed since your last read; `detail` for full rows). A release manager sees its whole queue; any other thread sees its own PRs and those it waits on (`all`: the whole project, plus PRs shipped in the last 7 days). Owners hear `staging:` and `shipped:` without reading it, and a PR sitting 2 h in one state gets its owner a note - no wakes to check.", + "`waitFor` (a PR, of any project, that blocks your work): you get its staging and shipped notices too; `stopWaiting` undoes it.", "With `prs` (release manager only): record each PR's state - queued (handed off, not merged), merged (on the release branch, not deployed), staging (deployed to staging), held (waiting on the user, e.g. a production promotion they gate), shipped (live in production), failed (its release failed). An owner's handoff that names its PR queues it for you.", - "Moving a PR to staging, shipped or failed also sends its owner the notice (staging: fyi; shipped: done + fyi; failed: done + ask, with `note` as the cause) - one message per owner per call; `notify: false` records only.", + "Moving a PR to staging, shipped or failed also sends its owner the notice (staging: fyi; shipped: done + fyi; failed: done + ask, with `note` as the cause), and threads waiting on it theirs - one message per owner per call; `notify: false` records only.", ].join(" "), parameters: Schema.Struct({ prs: Schema.optional( @@ -304,11 +330,18 @@ const ReleaseQueueTool = Tool.make("release_queue", { ), notify: Schema.optional(Schema.Boolean), all: Schema.optional( - Schema.Boolean.annotate({ description: "Also list PRs shipped in the last 7 days." }), + Schema.Boolean.annotate({ + description: "The whole project's queue, plus PRs shipped in the last 7 days.", + }), + ), + detail: Schema.optional( + Schema.Boolean.annotate({ description: "Full rows (owner ids, every timestamp)." }), ), + waitFor: Schema.optional(PrRef), + stopWaiting: Schema.optional(PrRef), }), success: Schema.Struct({ - entries: Schema.Array(ReleaseEntry), + entries: Schema.Array(Schema.Union([CompactReleaseEntry, ReleaseEntry])), notified: Schema.Array(Schema.String), notes: Schema.Array(Schema.String), }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5bf5ba1e230dc..7ad4549d249a4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -10690,7 +10690,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Effect.logInfo("t4.claude-safety-check-declined", { toolName, reason }); return { behavior: "deny", - message: safetyCheckDeclinedNote(reason), + message: safetyCheckDeclinedNote( + reason, + typeof command === "string" ? command : undefined, + ), toolUseID: callbackOptions.toolUseID, } satisfies PermissionResult; } diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 2a963ca12ef4c..282eefd4ba24e 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -39,6 +39,7 @@ import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import { evaluatePullRequestWatch, + type PullRequestWatchRemark, PULL_REQUEST_WATCH_NO_CHECKS_MS, pullRequestWatchMessage, } from "./pullRequestWatch.ts"; @@ -352,7 +353,14 @@ export const make = Effect.gen(function* () { string, { count: number; comments: ReadonlyArray } >(); - const remarks = [...activity.comments]; + const outdated = new Set( + activity.reviewThreads + .filter((thread) => thread.isOutdated) + .flatMap((thread) => thread.comments.map((comment) => comment.id)), + ); + const remarks: Array = activity.comments.map((comment) => + outdated.has(comment.id) ? { ...comment, outdated: true } : comment, + ); for (const thread of paginated) { let cursor = thread.nextCommentsCursor ?? null; const count = thread.commentCount ?? 0; @@ -384,7 +392,11 @@ export const make = Effect.gen(function* () { tail = { count, comments: [...comments.values()] }; } tails.set(thread.id, tail); - remarks.push(...tail.comments); + remarks.push( + ...(thread.isOutdated + ? tail.comments.map((comment) => ({ ...comment, outdated: true })) + : tail.comments), + ); } threadTails.set(key, { fetchedAt: reuse ? cached.fetchedAt : now, diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 8b0fc503ba87d..d04f30758202b 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -17,6 +17,7 @@ import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts"; import * as ServerSettings from "../serverSettings.ts"; import { isNativeMaintenanceCommand } from "./CommandPolicy.ts"; +import { restartToolCallsNote } from "../t4/toolCallLog.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import { awaitingProviderThreadId, @@ -320,6 +321,8 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta (message) => message.id === source.userMessageId, ); if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return; + // t4 fork: the T3 tool calls the restart cut, and those that finished unseen (AI-93). + const t4Calls = yield* restartToolCallsNote(input.threadId); // t4 fork: the provider never took this run's prompt, so "continue" would go on from the // turn before and the message itself - a wake, a handoff - would be lost. Send it again (AI-88). if (redeliversMessage(source, sourceMessage, projection.providerTurns)) { @@ -329,9 +332,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`), threadId: input.threadId, messageId, - text: sourceMessage.text.startsWith(REDELIVERY_NOTE) - ? sourceMessage.text - : `${REDELIVERY_NOTE}\n\n${sourceMessage.text}`, + text: [ + ...(sourceMessage.text.startsWith(REDELIVERY_NOTE) ? [] : [REDELIVERY_NOTE]), + ...(t4Calls === "" ? [] : [t4Calls]), + sourceMessage.text, + ].join("\n\n"), notification: { source: { kind: "system" }, outcome: "updated", @@ -359,8 +364,10 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta projection.providerTurns, projection.attempts, ); - const noteText = + const workNote = note.work.length === 0 ? undefined : restartCancelledBackgroundWorkNote(note.work); + const noteText = + t4Calls === "" ? workNote : workNote === undefined ? t4Calls : `${workNote}\n\n${t4Calls}`; const text = noteText === undefined ? CONTINUE_PROMPT diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index dece3e3449831..93a20b83f8bf3 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -463,16 +463,28 @@ describe("evaluatePullRequestWatch", () => { assert.deepEqual(evaluatePullRequestWatch(watch(), noViewer, [reply]).changes, []); }); - it("reports remarks from others once and never the agent's own", () => { + it("reports remarks from others once and never the agent's own, bot chatter or outdated ones", () => { const comments = [ remark("agent-user", "2026-10-02T12:05:00Z", "Fixed in the latest push."), remark("macroscope-app[bot]", "2026-10-02T12:06:00Z"), remark("reviewer", "2026-10-02T11:00:00Z", "Older than the watch."), + { ...remark("Linear-Code[bot]", "2026-10-02T12:07:00Z"), kind: "issue-comment" as const }, + { + ...remark("blacksmith-sh", "2026-10-02T12:07:00Z"), + kind: "issue-comment" as const, + author: { login: "blacksmith-sh", name: null, avatarUrl: null, isBot: true }, + }, + { ...remark("reviewer", "2026-10-02T12:08:00Z"), outdated: true }, ]; const report = evaluatePullRequestWatch(watch(), detail(), comments); assert.deepEqual(report.changes, [{ kind: "remarks", remarks: [comments[1]!] }]); - assert.equal(report.next.remarksThrough, "2026-10-02T12:06:00Z"); + assert.equal(report.next.remarksThrough, "2026-10-02T12:08:00Z"); + assert.deepEqual(report.next.remarkIds, [comments[5]!.id]); assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); + const quiet = evaluatePullRequestWatch(watch(), detail(), comments.slice(3)); + assert.deepEqual(quiet.changes, []); + assert.equal(quiet.next.remarksThrough, "2026-10-02T12:08:00Z"); + assert.equal(quiet.next.wakes, 0); }); it("cuts a long remark in the wake message without splitting an emoji", () => { diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index 046c48e1858bc..68036214a09e2 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -22,6 +22,17 @@ export type PullRequestWatchChange = | { readonly kind: "no-checks"; readonly minutes: number } | { readonly kind: "conflicting" }; +/** `outdated`: a review comment whose thread no longer matches the diff. */ +export type PullRequestWatchRemark = PullRequestComment & { readonly outdated?: boolean }; + +// Bot conversation comments (issue trackers, CI summaries) are chatter; bot reviews and review +// comments are findings the agent acts on, so they still wake. +const isQuietRemark = (remark: PullRequestWatchRemark) => + remark.outdated === true || + (remark.kind === "issue-comment" && + (remark.author?.isBot === true || + remark.author?.login.toLowerCase().endsWith("[bot]") === true)); + export interface PullRequestWatchReport { readonly changes: ReadonlyArray; readonly next: ThreadPullRequestWatch; @@ -41,7 +52,7 @@ export function evaluatePullRequestWatch( PullRequestDetail, "capabilities" | "headSha" | "checks" | "mergeability" | "viewer" | "author" >, - remarks: ReadonlyArray | null, + remarks: ReadonlyArray | null, now: number, ): PullRequestWatchReport { const changes: Array = []; @@ -161,16 +172,18 @@ export function evaluatePullRequestWatch( const through = Date.parse(watch.remarksThrough); const activeAt = (remark: PullRequestComment) => remark.editedAt ?? remark.createdAt; // Hosts can stamp remarks to the second, so remarks at the boundary time are told apart by ID. - const fresh = (remarks ?? []).filter((remark) => { + const unseen = (remarks ?? []).filter((remark) => { const at = Date.parse(activeAt(remark)); return ( (at > through || (at === through && !watch.remarkIds.includes(remark.id))) && remark.author?.login.toLowerCase() !== own ); }); + // Quiet remarks never wake, but still move the watermark so they never wake later either. + const fresh = unseen.filter((remark) => !isQuietRemark(remark)); if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); - const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark)))); - const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest); + const latest = Math.max(through, ...unseen.map((remark) => Date.parse(activeAt(remark)))); + const atLatest = unseen.filter((remark) => Date.parse(activeAt(remark)) === latest); const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!); const remarkIds = [ ...(latest === through ? watch.remarkIds : []), diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 4e15b02d04e53..54c8fc69d4c5a 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -381,6 +381,7 @@ it.effect("an agent here works on a linked environment's threads within its own const threads = yield* a.call("thread:laptop-full", "t3_thread_list", { environmentId: box.environmentId, projectId: boxProject, + detail: true, }); expect(threads.isError).toBe(false); expect(threads.structuredContent).toMatchObject({ diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 92a4e09e8bf88..e7bca26515e1d 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 8962, - "codexAdditionalContextBytes": 10697, - "mcpToolListJsonBytes": 58614 + "claudeSystemAppendBytes": 9001, + "codexAdditionalContextBytes": 10736, + "mcpToolListJsonBytes": 60640 } diff --git a/apps/server/src/t4/T4Delivery.test.ts b/apps/server/src/t4/T4Delivery.test.ts index 2e9c2e116b659..8b80dbadf76e5 100644 --- a/apps/server/src/t4/T4Delivery.test.ts +++ b/apps/server/src/t4/T4Delivery.test.ts @@ -1,5 +1,15 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, describe, it } from "@effect/vitest"; +import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as McpToolAccessTestkit from "../mcp/McpToolAccess.testkit.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as T4Config from "./T4Config.ts"; +import * as T4Delivery from "./T4Delivery.ts"; +import * as T4Ledger from "./T4Ledger.ts"; +import * as T4Store from "./T4Store.ts"; import { CANCELLED_TOOL_NOTE, deliveryNotes, @@ -39,3 +49,59 @@ describe("deliveryNotes", () => { assert.notInclude(OPEN_QUESTION_NOTE(["Launch wave 2 now?"]), "ask the question again with"); }); }); + +const CLAUDE = ProviderInstanceId.make("claudeAgent"); +const running = { + ...McpToolAccessTestkit.liveThreadShell(ThreadId.make("t4-target")), + providerInstanceId: CLAUDE, + modelSelection: { instanceId: CLAUDE, model: "claude-opus-5-5" }, +}; +const sent: Array<{ mode: string; text: string }> = []; +const deliveryLayer = T4Delivery.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: () => Effect.succeed(running), + sendToThread: (input) => + Effect.sync(() => { + sent.push({ mode: input.mode, text: input.text }); + return { delivery: input.mode === "queue" ? "queued" : "steered" } as never; + }), + }), + Layer.mock(T4Store.T4Store)({ addNotice: () => Effect.void }), + Layer.mock(T4Ledger.T4Ledger)({ + world: () => Effect.succeed({} as never), + isReleaseManager: () => false, + facts: () => Effect.die("unused"), + } as never), + Layer.succeed(T4Config.T4ServerConfig, T4Config.defaultT4ServerConfig), + NodeCrypto.layer, + ), + ), +); + +describe("deliver", () => { + it.effect("queues a patient message behind a running turn, so no tool call is cut", () => + Effect.gen(function* () { + sent.length = 0; + const delivery = yield* T4Delivery.T4Delivery; + const patient = yield* delivery.deliver({ target: running, text: "fyi", patient: true }); + const urgent = yield* delivery.deliver({ target: running, text: "done" }); + const restart = yield* delivery.deliver({ + target: running, + text: "stop", + patient: true, + interrupt: true, + }); + assert.deepEqual( + sent.map((entry) => entry.mode), + ["queue", "auto", "restart"], + ); + assert.notInclude(sent[0]!.text, CANCELLED_TOOL_NOTE); + assert.include(sent[1]!.text, CANCELLED_TOOL_NOTE); + assert.include(patient.how, "waits until that turn ends"); + assert.equal(urgent.delivery, "steered"); + assert.equal(restart.delivery, "steered"); + }).pipe(Effect.provide(deliveryLayer)), + ); +}); diff --git a/apps/server/src/t4/T4Delivery.ts b/apps/server/src/t4/T4Delivery.ts index 120c460a7beee..b3730c829e878 100644 --- a/apps/server/src/t4/T4Delivery.ts +++ b/apps/server/src/t4/T4Delivery.ts @@ -32,6 +32,11 @@ export interface T4DeliverInput { readonly text: string; readonly senderThreadId?: ThreadId; readonly interrupt?: boolean; + /** + * Not urgent: a running turn finishes first (queued), so a command it runs is never cut. + * 185 steered notes cancelled tool calls in a week, mostly test runs re-run (AI-93). + */ + readonly patient?: boolean; /** Skip the delivery notes (the server's own relays). */ readonly force?: boolean; /** Asks nothing of the recipient: a pending settle stands. */ @@ -57,6 +62,8 @@ export interface T4DeliveryShape { readonly sender: OrchestrationV2ThreadShell; readonly target: OrchestrationV2ThreadShell; readonly text: string; + /** Sent with mode `queue`: the delivery notes for a cut tool call don't apply. */ + readonly queued?: boolean; }) => Effect.Effect; } @@ -150,17 +157,18 @@ const make = Effect.gen(function* () { Effect.orElseSucceed(() => noQuestions), ); - /** The delivery notes, prepended when they apply. */ + /** The delivery notes, prepended when they apply; a queued message cancels nothing. */ const withNotes = Effect.fn("t4.T4Delivery.withNotes")(function* ( target: OrchestrationV2ThreadShell, text: string, + queued: boolean, ) { const questions = yield* pendingQuestions(target); const notes = deliveryNotes({ settled: isSettled(target), questions: questions.live, openQuestions: questions.open, - claudeRunning: target.providerInstanceId.startsWith("claude") && isRunning(target), + claudeRunning: !queued && target.providerInstanceId.startsWith("claude") && isRunning(target), }); return notes.length === 0 ? text @@ -176,7 +184,7 @@ const make = Effect.gen(function* () { }); } const header = `Message from thread "${input.sender.title}" (${shortId(input.sender.id)}):\n\n`; - return yield* withNotes(input.target, header + input.text); + return yield* withNotes(input.target, header + input.text, input.queued === true); }); const deliver: T4DeliveryShape["deliver"] = Effect.fn("t4.T4Delivery.deliver")(function* ( @@ -193,7 +201,10 @@ const make = Effect.gen(function* () { .getThreadShell(input.target.id) .pipe(Effect.orElseSucceed(() => null))) ?? input.target; const running = isRunning(target); - const text = input.force === true ? input.text : yield* withNotes(target, input.text); + const restart = input.interrupt === true && running; + const queued = !restart && input.patient === true; + const text = + input.force === true ? input.text : yield* withNotes(target, input.text, queued && running); const world = yield* ledger.world().pipe(Effect.mapError(fail("t4 ledger unavailable"))); const rmModel = config.releaseManagerModel; @@ -218,7 +229,7 @@ const make = Effect.gen(function* () { text, attachments: [], ...(modelSelection === undefined ? {} : { modelSelection }), - mode: input.interrupt === true && running ? "restart" : "auto", + mode: restart ? "restart" : queued ? "queue" : "auto", createdBy: input.createdBy ?? "agent", creationSource: input.creationSource ?? "mcp", }) @@ -229,7 +240,9 @@ const make = Effect.gen(function* () { : result.delivery === "steered" ? "it was mid-turn; the message went straight into the running turn" : result.delivery === "queued" - ? "it was starting a turn; the message is queued right behind it" + ? queued && running + ? "it is mid-turn; the message waits until that turn ends, so nothing it runs is cut (pass interrupt to cut in)" + : "it was starting a turn; the message is queued right behind it" : "delivered"; return { messageId, delivery: result.delivery, how }; }); diff --git a/apps/server/src/t4/T4Jobs.ts b/apps/server/src/t4/T4Jobs.ts index ab0804b71935e..8b467716385f9 100644 --- a/apps/server/src/t4/T4Jobs.ts +++ b/apps/server/src/t4/T4Jobs.ts @@ -13,6 +13,7 @@ import * as FyiDigest from "./fyiDigest.ts"; import * as T4LegacyImport from "./T4LegacyImport.ts"; import * as T4AutoArchive from "./T4AutoArchive.ts"; import * as T4ReleaseGuard from "./T4ReleaseGuard.ts"; +import * as T4Releases from "./T4Releases.ts"; import * as T4Schedules from "./T4Schedules.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; import * as T4Settle from "./T4Settle.ts"; @@ -44,6 +45,7 @@ export const layer = Layer.effectDiscard( yield* scheduler.register("t4-workflow-runs", yield* throttled(30_000, runWatch.sweep)); yield* scheduler.register("t4-fyi-digests", yield* throttled(60_000, FyiDigest.sweep)); yield* scheduler.register("t4-release-guard", yield* throttled(120_000, T4ReleaseGuard.sweep)); + yield* scheduler.register("t4-release-stale", yield* throttled(600_000, T4Releases.sweepStale)); yield* scheduler.register("t4-auto-archive", yield* throttled(600_000, T4AutoArchive.sweep)); yield* scheduler.register( "t4-schedule-models", diff --git a/apps/server/src/t4/T4Migrations.ts b/apps/server/src/t4/T4Migrations.ts index db67cc4fe0489..f85b2963bc712 100644 --- a/apps/server/src/t4/T4Migrations.ts +++ b/apps/server/src/t4/T4Migrations.ts @@ -140,10 +140,40 @@ const Migration0003 = Effect.gen(function* () { `; }); +// Threads waiting on a PR they don't own hear its staging and shipped notices. +// Write tool calls are logged so a restart note can say which ones went through. +const Migration0004 = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE IF NOT EXISTS t4_release_waiters ( + project_id TEXT NOT NULL, + pr INTEGER NOT NULL, + thread_id TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (project_id, pr, thread_id) + ) WITHOUT ROWID + `; + yield* sql`CREATE INDEX IF NOT EXISTS t4_release_waiters_thread ON t4_release_waiters (thread_id)`; + yield* sql` + CREATE TABLE IF NOT EXISTS t4_tool_calls ( + id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + tool TEXT NOT NULL, + summary TEXT NOT NULL, + boot TEXT NOT NULL, + started_at TEXT NOT NULL, + finished_at TEXT, + result TEXT + ) WITHOUT ROWID + `; + yield* sql`CREATE INDEX IF NOT EXISTS t4_tool_calls_thread ON t4_tool_calls (thread_id)`; +}); + const t4MigrationEntries = [ [1, "T4SessionTooling", Migration0001], [2, "T4ThreadRoles", Migration0002], [3, "T4ReleaseQueue", Migration0003], + [4, "T4WaitersAndToolCalls", Migration0004], ] as const; const run = Migrator.make({}); diff --git a/apps/server/src/t4/T4Releases.ts b/apps/server/src/t4/T4Releases.ts new file mode 100644 index 0000000000000..6074d719c67ef --- /dev/null +++ b/apps/server/src/t4/T4Releases.ts @@ -0,0 +1,191 @@ +/** + * t4 fork: what release managers, owners and waiters are told about the release queue, so none + * of them polls it: a release manager's handoffs and wakes carry its queue and debts. + */ +import { ThreadId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as T4Delivery from "./T4Delivery.ts"; +import * as T4Ledger from "./T4Ledger.ts"; +import * as T4Store from "./T4Store.ts"; +import { ago, isRetired, shortId } from "./T4Threads.ts"; + +type Row = T4Store.T4ReleaseRow; + +const LISTED = 8; + +/** When the row reached its current state. */ +const stateSinceOf = (row: Row): string => { + switch (row.state) { + case "queued": + return row.queuedAt; + case "merged": + return row.mergedAt ?? row.updatedAt; + case "staging": + return row.stagedAt ?? row.updatedAt; + case "shipped": + return row.shippedAt ?? row.updatedAt; + default: + return row.updatedAt; + } +}; + +/** + * The one-paragraph header a release manager gets with every handoff and run-watch wake: what is + * open in its queue and how many threads it owes an answer, so it starts a turn without reading + * either. + */ +const releaseManagerBrief = ( + rows: ReadonlyArray, + owed: ReadonlyArray<{ readonly fromTitle: string }>, + nowMs: number, +): string => { + const open = rows.filter((row) => row.state !== "shipped"); + const listed = open + .slice(0, LISTED) + .map( + (row) => + `#${row.pr} ${row.state} ${ago(Date.parse(stateSinceOf(row)), nowMs)}${row.note ? ` (${row.note.slice(0, 60)})` : ""}`, + ); + const more = open.length > LISTED ? `, +${open.length - LISTED} more` : ""; + const queue = + open.length === 0 + ? "Your queue is empty." + : `Your queue: ${open.length} open - ${listed.join(", ")}${more}.`; + const owes = + owed.length === 0 + ? "You owe no thread an answer." + : `You owe ${owed.length} thread${owed.length === 1 ? "" : "s"} an answer: ${owed + .slice(0, LISTED) + .map((entry) => `"${entry.fromTitle.slice(0, 50)}"`) + .join(", ")}${owed.length > LISTED ? ", …" : ""}.`; + return `(t4: ${queue} ${owes} This is current - read \`release_queue\` or \`t3_owed\` only for detail.)\n\n`; +}; + +/** The release manager's brief, read fresh. Empty when the store can't be read. */ +export const releaseManagerBriefFor = Effect.fn("t4.releaseManagerBriefFor")(function* ( + rm: { readonly id: string; readonly projectId: string }, + world: T4Ledger.T4World, + /** The thread whose request this brief rides on, counted even before it is recorded. */ + asking?: { readonly id: string; readonly title: string }, +) { + const store = yield* T4Store.T4Store; + const now = yield* Clock.currentTimeMillis; + const rows = yield* store + .releaseQueue({ projectId: rm.projectId }) + .pipe(Effect.orElseSucceed(() => null)); + if (rows === null) return ""; + const owed: Array<{ readonly fromTitle: string }> = world.live.filter( + (entry) => entry.toThreadId === rm.id, + ); + if ( + asking !== undefined && + !world.live.some((entry) => entry.toThreadId === rm.id && entry.fromThreadId === asking.id) + ) { + owed.push({ fromTitle: asking.title }); + } + return releaseManagerBrief(rows, owed, now); +}); + +/** A queue row as release_queue returns it by default: ~200 bytes. */ +export const compactEntry = ( + row: Row, + world: T4Ledger.T4World, + nowMs: number, + lastReadAt: string | undefined, +) => { + const owner = row.ownerThreadId === null ? undefined : world.byId.get(row.ownerThreadId); + return { + pr: row.pr, + state: row.state, + since: ago(Date.parse(stateSinceOf(row)), nowMs), + title: row.title === null ? null : row.title.slice(0, 80), + issue: row.issue, + owner: + row.ownerThreadId === null + ? null + : `${(owner?.title ?? row.ownerTitle ?? row.ownerThreadId).slice(0, 60)} (${shortId(row.ownerThreadId)}${owner === undefined ? ", deleted" : ""})`, + note: row.note, + commit: row.commitSha === null ? null : row.commitSha.slice(0, 10), + changed: lastReadAt === undefined || row.updatedAt > lastReadAt, + }; +}; + +/** One release notice per owner and state (release_queue). */ +export const releaseNotice = ( + state: "staging" | "shipped" | "failed", + prs: ReadonlyArray, + note: string | null, +) => { + const list = prs.map((pr) => `#${pr}`).join(", "); + const plural = prs.length === 1 ? "PR" : "PRs"; + switch (state) { + case "staging": + // 45 settles were refused on `staging:` in a week (AI-93): the owner still owes verification. + return `staging: ${plural} ${list} ${prs.length === 1 ? "is" : "are"} on staging. Verify there. Don't settle yet: \`shipped:\` comes when ${prs.length === 1 ? "it is" : "they are"} live.${note ? ` ${note}` : ""}`; + case "shipped": + return `shipped: ${plural} ${list} live in production. Verify, close your Linear.${note ? ` ${note}` : ""}`; + case "failed": + return `release failed on your ${plural} ${list}: ${note ?? "see the release manager's thread"}`; + } +}; + +/** What a thread waiting on someone else's PR hears (AI-93). */ +export const waiterNotice = ( + state: "staging" | "shipped" | "failed", + row: Pick, + projectTitle: string, +) => { + const what = `PR #${row.pr}${row.title ? ` ("${row.title.slice(0, 80)}")` : ""} in ${projectTitle}`; + switch (state) { + case "staging": + return `release: ${what}, which you are waiting on, is on staging. You hear again when it is live.`; + case "shipped": + return `release: ${what}, which you were waiting on, is live in production. You are no longer waiting on it.`; + case "failed": + return `release: ${what}, which you are waiting on, failed to release${row.note ? ` (${row.note})` : ""}. Its owner is fixing it; you hear again when it ships.`; + } +}; + +const STALE_MS = 2 * 60 * 60_000; +const pingedKey = (row: Row) => `release-ping:${row.projectId}:${row.pr}`; + +/** The note an owner gets when its PR has sat in one state for over 2 hours. */ +const staleNotice = (row: Row, nowMs: number) => + `release: your PR #${row.pr} is still ${row.state} (for ${ago(Date.parse(stateSinceOf(row)), nowMs)})${row.note ? `: ${row.note}` : ""}. Nothing to do for it - the release manager sends \`shipped:\` when it is live; don't schedule a wake or read \`release_queue\` to check.`; + +/** + * Owners whose PR row has not changed for 2 hours hear where it is, once per change, so they + * stop setting wakes to check for `shipped:` (783 of 840 owner wakes in 98 h, AI-93). + */ +export const sweepStale = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const delivery = yield* T4Delivery.T4Delivery; + const threads = yield* ThreadManagementService.ThreadManagementService; + const now = yield* Clock.currentTimeMillis; + const rows = yield* store.releaseQueue(); + for (const row of rows) { + if (row.state === "shipped" || row.state === "failed" || row.ownerThreadId === null) continue; + if (now - Date.parse(row.updatedAt) < STALE_MS) continue; + const pinged = yield* store.meta(pingedKey(row)).pipe(Effect.orElseSucceed(() => undefined)); + if (pinged === row.updatedAt) continue; + yield* store.setMeta(pingedKey(row), row.updatedAt); + const owner = yield* threads + .getThreadShell(ThreadId.make(row.ownerThreadId)) + .pipe(Effect.orElseSucceed(() => null)); + if (owner === null || isRetired(owner)) continue; + yield* delivery + .deliver({ + target: owner, + text: staleNotice(row, now), + force: true, + patient: true, + notice: true, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.ignore); + } +}).pipe(Effect.ignoreCause({ log: true })); diff --git a/apps/server/src/t4/T4RunWatch.ts b/apps/server/src/t4/T4RunWatch.ts index a4c9ea4d7913c..84fe43b60c718 100644 --- a/apps/server/src/t4/T4RunWatch.ts +++ b/apps/server/src/t4/T4RunWatch.ts @@ -4,18 +4,21 @@ * Each watched run is checked every 30 s and one message posted when it completes. Watches live in * t4_meta (a handful at a time); one older than six hours is dropped with a note. */ -import { ThreadId } from "@t3tools/contracts"; +import { type OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as T4Delivery from "./T4Delivery.ts"; +import * as T4Ledger from "./T4Ledger.ts"; +import * as T4Releases from "./T4Releases.ts"; import * as T4Store from "./T4Store.ts"; const META_KEY = "workflow-run-watches"; @@ -496,6 +499,21 @@ const make = Effect.gen(function* () { return { run, watching: true }; }); + // t4 fork: a release manager's wake carries its queue and debts, so it starts the turn without + // reading them (AI-93); a finished run waits for a running turn instead of cutting its command. + const ledger = Option.getOrUndefined(yield* Effect.serviceOption(T4Ledger.T4Ledger)); + const briefFor = (target: OrchestrationV2ThreadShell) => + ledger === undefined + ? Effect.succeed("") + : ledger.world().pipe( + Effect.flatMap((world) => + ledger.isReleaseManager(world, target) + ? T4Releases.releaseManagerBriefFor(target, world) + : Effect.succeed(""), + ), + Effect.provideService(T4Store.T4Store, store), + Effect.orElseSucceed(() => ""), + ); const post = (threadId: string, text: string, options?: { readonly skipSettled?: boolean }) => threads.getThreadShell(ThreadId.make(threadId)).pipe( Effect.flatMap((target) => @@ -506,9 +524,19 @@ const make = Effect.gen(function* () { (options?.skipSettled === true && (target.settledOverride === "settled" || target.settledAt != null)) ? Effect.void - : delivery - .deliver({ target, text, force: true, createdBy: "system", creationSource: "server" }) - .pipe(Effect.asVoid), + : briefFor(target).pipe( + Effect.flatMap((brief) => + delivery.deliver({ + target, + text: brief + text, + force: true, + patient: true, + createdBy: "system", + creationSource: "server", + }), + ), + Effect.asVoid, + ), ), Effect.ignore, ); diff --git a/apps/server/src/t4/T4Store.test.ts b/apps/server/src/t4/T4Store.test.ts index 58ee238b518bf..e878d851ccff6 100644 --- a/apps/server/src/t4/T4Store.test.ts +++ b/apps/server/src/t4/T4Store.test.ts @@ -3,9 +3,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; import * as T4Sql from "./T4Sql.ts"; import * as T4Store from "./T4Store.ts"; +import { restartToolCallsNote } from "./toolCallLog.ts"; const layer = T4Store.layer.pipe( Layer.provideMerge(T4Sql.layerMemory), @@ -162,6 +164,57 @@ describe("T4Store", () => { }).pipe(Effect.provide(layer)), ); + it.effect("keeps release waiters per PR and per thread", () => + Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const waiter = { projectId: "theme", pr: 306, threadId: "usa-455" }; + assert.isTrue(yield* store.addReleaseWaiter(waiter)); + assert.isFalse(yield* store.addReleaseWaiter(waiter)); + yield* store.addReleaseWaiter({ ...waiter, threadId: "usa-756" }); + assert.deepEqual( + (yield* store.releaseWaiters({ projectId: "theme", pr: 306 })).map((w) => w.threadId), + ["usa-455", "usa-756"], + ); + assert.deepEqual(yield* store.releaseWaiters({ threadId: "usa-455" }), [waiter]); + assert.isTrue(yield* store.removeReleaseWaiter(waiter)); + assert.isFalse(yield* store.removeReleaseWaiter(waiter)); + assert.deepEqual(yield* store.releaseWaiters({ threadId: "usa-455" }), []); + }).pipe(Effect.provide(layer)), + ); + + it.effect("tells a thread once which tool calls a restart cut and which finished", () => + Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const sql = yield* SqlClient.SqlClient; + const at = "2026-11-13T22:00:00.000Z"; + // Rows an earlier server process left: one never finished, one finished unseen. + yield* sql` + INSERT INTO t4_tool_calls (id, thread_id, tool, summary, boot, started_at, finished_at, result) + VALUES + ('a', 'owner', 't3_thread_launch', 't3_thread_launch (title: USA-2086 fix)', 'old', ${at}, NULL, NULL), + ('b', 'owner', 'schedule_task', 'schedule_task (title: check CI)', 'old', ${at}, ${at}, 'done'), + ('c', 'other', 'schedule_task', 'schedule_task (title: theirs)', 'old', ${at}, NULL, NULL) + `; + // A call this process is running is not cut. + yield* store.startToolCall({ + id: "d", + threadId: "owner", + tool: "release_queue", + summary: "now", + }); + const note = yield* restartToolCallsNote("owner"); + assert.include(note, "still running when T3 restarted"); + assert.include(note, "- t3_thread_launch (title: USA-2086 fix)"); + assert.include(note, "finished before the restart"); + assert.include(note, "- schedule_task (title: check CI): done"); + assert.notInclude(note, "now"); + assert.notInclude(note, "theirs"); + assert.equal(yield* restartToolCallsNote("owner"), ""); + // Still found by its key afterwards (a retried handoff), marked cut. + assert.equal((yield* store.toolCall("a"))?.result, T4Store.CUT_RESULT); + }).pipe(Effect.provide(layer)), + ); + it("stamps no staging time on a hold", () => { const held = T4Store.applyReleaseUpdate( undefined, diff --git a/apps/server/src/t4/T4Store.ts b/apps/server/src/t4/T4Store.ts index 570de1f593e2a..a15bd49f9196b 100644 --- a/apps/server/src/t4/T4Store.ts +++ b/apps/server/src/t4/T4Store.ts @@ -150,6 +150,32 @@ export const applyReleaseUpdate = ( }; }; +export interface T4ReleaseWaiter { + readonly projectId: string; + readonly pr: number; + readonly threadId: string; +} + +export interface T4ToolCall { + readonly id: string; + readonly threadId: string; + readonly tool: string; + readonly summary: string; + readonly startedAt: string; + readonly finishedAt: string | null; + readonly result: string | null; + /** Started by this server process (not one a restart ended). */ + readonly current: boolean; +} + +/** This server process: a call left unfinished by an earlier one was cut by a restart. */ +const BOOT_ID = `${process.pid}-${process.hrtime.bigint().toString(36)}`; +let callSeq = 0; +/** A unique id for a logged tool call. */ +export const newToolCallId = () => `call:${BOOT_ID}:${(callSeq += 1)}`; +/** The result a call cut by a restart is left with. */ +export const CUT_RESULT = "cut by a restart"; + const MAX_NOTICES = 500; type StoreError = SqlError.SqlError; @@ -236,6 +262,33 @@ export interface T4StoreShape { */ readonly queueRelease: (update: T4ReleaseUpdate) => Effect.Effect; + /** Threads waiting on a PR they don't own (AI-93). */ + readonly addReleaseWaiter: (waiter: T4ReleaseWaiter) => Effect.Effect; + readonly removeReleaseWaiter: (waiter: T4ReleaseWaiter) => Effect.Effect; + /** Waiters on one PR (`threadId` unset), or the PRs one thread waits on. */ + readonly releaseWaiters: (filter: { + readonly projectId?: string; + readonly pr?: number; + readonly threadId?: string; + }) => Effect.Effect, StoreError>; + + /** A write tool call starting (AI-93): its row stays unfinished if a restart cuts it. */ + readonly startToolCall: (call: { + readonly id: string; + readonly threadId: string; + readonly tool: string; + readonly summary: string; + }) => Effect.Effect; + readonly finishToolCall: (id: string, result: string) => Effect.Effect; + readonly toolCall: (id: string) => Effect.Effect; + /** + * A thread's calls from before the last restart (30 min), oldest first: unfinished ones were + * cut. Each is returned once. + */ + readonly takeRestartToolCalls: ( + threadId: string, + ) => Effect.Effect, StoreError>; + readonly meta: (key: string) => Effect.Effect; readonly setMeta: (key: string, value: string) => Effect.Effect; } @@ -646,6 +699,113 @@ const make = Effect.gen(function* () { ), ); + const addReleaseWaiter: T4StoreShape["addReleaseWaiter"] = Effect.fn("T4Store.addReleaseWaiter")( + function* (waiter) { + const at = yield* nowIso; + const rows = yield* sql<{ readonly pr: number }>` + INSERT OR IGNORE INTO t4_release_waiters (project_id, pr, thread_id, created_at) + VALUES (${waiter.projectId}, ${waiter.pr}, ${waiter.threadId}, ${at}) + RETURNING pr + `; + return rows.length > 0; + }, + ); + + const removeReleaseWaiter: T4StoreShape["removeReleaseWaiter"] = (waiter) => + sql<{ readonly pr: number }>` + DELETE FROM t4_release_waiters + WHERE project_id = ${waiter.projectId} AND pr = ${waiter.pr} AND thread_id = ${waiter.threadId} + RETURNING pr + `.pipe(Effect.map((rows) => rows.length > 0)); + + const releaseWaiters: T4StoreShape["releaseWaiters"] = (filter) => + sql<{ readonly project_id: string; readonly pr: number; readonly thread_id: string }>` + SELECT project_id, pr, thread_id FROM t4_release_waiters + WHERE (${filter.projectId ?? null} IS NULL OR project_id = ${filter.projectId ?? null}) + AND (${filter.pr ?? null} IS NULL OR pr = ${filter.pr ?? null}) + AND (${filter.threadId ?? null} IS NULL OR thread_id = ${filter.threadId ?? null}) + ORDER BY created_at + `.pipe( + Effect.map((rows) => + rows.map((row) => ({ + projectId: row.project_id, + pr: Number(row.pr), + threadId: row.thread_id, + })), + ), + ); + + interface ToolCallRow { + readonly id: string; + readonly thread_id: string; + readonly tool: string; + readonly summary: string; + readonly started_at: string; + readonly finished_at: string | null; + readonly result: string | null; + readonly boot: string; + } + const toolCallOf = (row: ToolCallRow): T4ToolCall => ({ + id: row.id, + threadId: row.thread_id, + tool: row.tool, + summary: row.summary, + startedAt: row.started_at, + finishedAt: row.finished_at, + result: row.result, + current: row.boot === BOOT_ID, + }); + + const startToolCall: T4StoreShape["startToolCall"] = Effect.fn("T4Store.startToolCall")( + function* (call) { + const now = yield* DateTime.now; + const at = DateTime.formatIso(now); + yield* sql` + INSERT OR REPLACE INTO t4_tool_calls (id, thread_id, tool, summary, boot, started_at) + VALUES (${call.id}, ${call.threadId}, ${call.tool}, ${call.summary}, ${BOOT_ID}, ${at}) + `; + // Kept a day: long enough for a retry with the same clientRequestId. + const dayAgo = DateTime.formatIso(DateTime.subtract(now, { days: 1 })); + yield* sql`DELETE FROM t4_tool_calls WHERE started_at < ${dayAgo}`; + }, + ); + + const finishToolCall: T4StoreShape["finishToolCall"] = Effect.fn("T4Store.finishToolCall")( + function* (id, result) { + const at = yield* nowIso; + yield* sql`UPDATE t4_tool_calls SET finished_at = ${at}, result = ${result} WHERE id = ${id}`; + }, + ); + + const toolCall: T4StoreShape["toolCall"] = (id) => + sql`SELECT * FROM t4_tool_calls WHERE id = ${id}`.pipe( + Effect.map((rows) => (rows[0] === undefined ? undefined : toolCallOf(rows[0]))), + ); + + const takeRestartToolCalls: T4StoreShape["takeRestartToolCalls"] = (threadId) => + sql.withTransaction( + Effect.gen(function* () { + const now = yield* DateTime.now; + const at = DateTime.formatIso(now); + const since = DateTime.formatIso(DateTime.subtract(now, { minutes: 30 })); + const rows = yield* sql` + SELECT * FROM t4_tool_calls + WHERE thread_id = ${threadId} AND boot != ${BOOT_ID} + AND started_at >= ${since} + ORDER BY started_at + `; + // Re-owned by this process: told once, still found by a retry's key. + yield* sql` + UPDATE t4_tool_calls + SET finished_at = COALESCE(finished_at, ${at}), + result = COALESCE(result, ${CUT_RESULT}), + boot = ${BOOT_ID} + WHERE thread_id = ${threadId} AND boot != ${BOOT_ID} + `; + return rows.map(toolCallOf); + }), + ); + const setMeta: T4StoreShape["setMeta"] = (key, value) => sql` INSERT INTO t4_meta (key, value) VALUES (${key}, ${value}) @@ -682,6 +842,13 @@ const make = Effect.gen(function* () { releaseQueue, updateRelease, queueRelease, + addReleaseWaiter, + removeReleaseWaiter, + releaseWaiters, + startToolCall, + finishToolCall, + toolCall, + takeRestartToolCalls, meta, setMeta, }); diff --git a/apps/server/src/t4/declineSafetyChecks.test.ts b/apps/server/src/t4/declineSafetyChecks.test.ts new file mode 100644 index 0000000000000..4ca1a754699f4 --- /dev/null +++ b/apps/server/src/t4/declineSafetyChecks.test.ts @@ -0,0 +1,21 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { safetyCheckDeclinedNote } from "./declineSafetyChecks.ts"; + +describe("safetyCheckDeclinedNote", () => { + it("tells how to write a removal for rm commands, and to run a saved file otherwise", () => { + for (const command of [undefined, "rm -rf /tmp/x", "cd web && rm -f ../a/*", "ls; rmdir out"]) { + const note = safetyCheckDeclinedNote("Dangerous rm", command); + assert.include(note, "one rm per target"); + assert.notInclude(note, "Write tool"); + } + for (const command of [ + "python3 - <<'EOF'\nprint('confirm')\nEOF", + "bash -c 'npm run format'", + ]) { + const note = safetyCheckDeclinedNote("This shell -c script could not be checked", command); + assert.include(note, "save it with the Write tool to a file"); + assert.notInclude(note, "one rm per target"); + } + }); +}); diff --git a/apps/server/src/t4/declineSafetyChecks.ts b/apps/server/src/t4/declineSafetyChecks.ts index 2b4f5bf57aa26..e8b156f673a50 100644 --- a/apps/server/src/t4/declineSafetyChecks.ts +++ b/apps/server/src/t4/declineSafetyChecks.ts @@ -7,9 +7,16 @@ export const t4DeclineSafetyChecks = (env: NodeJS.ProcessEnv = process.env): boolean => env.T4_CLAUDE_DECLINE_SAFETY_CHECKS?.trim() === "1"; -export const safetyCheckDeclinedNote = (reason: string | undefined): string => +const RM_COMMAND = /(?:^|[\s;&|(`])rm(?:dir)?(?=\s|$)/m; + +/** Without the command, the note assumes a removal. */ +export const safetyCheckDeclinedNote = (reason: string | undefined, command?: string): string => `Claude Code's safety check stopped this command${reason ? ` (${reason})` : ""}, and no one ` + - "approves commands on this thread, so it was not run. Do it in a form the check can verify: " + - "for a removal, one rm per target with its literal absolute path - no `cd` before it in the " + - "same command, no relative glob, no glob across directories, no variable or command " + - "substitution in the path. Don't ask the user to approve it."; + "approves commands on this thread, so it was not run. " + + (command === undefined || RM_COMMAND.test(command) + ? "Do it in a form the check can verify: for a removal, one rm per target with its literal " + + "absolute path - no `cd` before it in the same command, no relative glob, no glob across " + + "directories, no variable or command substitution in the path." + : "Don't run a script inline through a heredoc or `-c`: save it with the Write tool to a " + + "file (outside the repository or in a gitignored folder) and run that file.") + + " Don't ask the user to approve it."; diff --git a/apps/server/src/t4/fyiDigest.ts b/apps/server/src/t4/fyiDigest.ts index 2308cb377ee56..ebfc7058a36b2 100644 --- a/apps/server/src/t4/fyiDigest.ts +++ b/apps/server/src/t4/fyiDigest.ts @@ -130,6 +130,7 @@ export const sweep = Effect.gen(function* () { text: digestText(pair.fromTitle, pair.from, items), senderThreadId: ThreadId.make(pair.from), notice: true, + patient: true, }) .pipe(Effect.ignore); yield* store.setMeta(lastKey(pair.from, pair.to), String(now)); diff --git a/apps/server/src/t4/toolCallLog.ts b/apps/server/src/t4/toolCallLog.ts new file mode 100644 index 0000000000000..1f713d1358b40 --- /dev/null +++ b/apps/server/src/t4/toolCallLog.ts @@ -0,0 +1,109 @@ +/** + * t4 fork: write tool calls a T3 restart can cut (AI-93). A restart cut 50 MCP calls in a week + * (ECONNRESET, "interrupted before a result") and the agent could not tell whether its handoff, + * launch or wake had happened. Each call is logged when it starts and when it ends; the restart + * continuation tells the agent which ones never finished and which did. + */ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as T4Store from "./T4Store.ts"; + +/** Tools whose effect an agent must not repeat blindly. `t3_handoff` logs itself (its retry key). */ +export const LOGGED_TOOLS: ReadonlySet = new Set([ + "t3_thread_launch", + "create_threads", + "delegate_task", + "t3_thread_send", + "schedule_task", + "delete_scheduled_task", + "t3_thread_organize", + "release_queue", + "link_issue", +]); + +const clip = (text: string, max: number) => { + const flat = text.replaceAll(/\s+/g, " ").trim(); + return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`; +}; + +/** A short, recognisable description of a call: the arguments that say what it did. */ +export const callSummary = (tool: string, args: unknown): string => { + const record = typeof args === "object" && args !== null ? (args as Record) : {}; + const parts: Array = []; + for (const key of [ + "action", + "to", + "threadId", + "title", + "pr", + "prs", + "identifier", + "scheduledTaskId", + ]) { + const value = record[key]; + if (value === undefined || value === null) continue; + parts.push(`${key}: ${clip(typeof value === "string" ? value : JSON.stringify(value), 80)}`); + } + for (const key of ["message", "prompt", "task"]) { + const value = record[key]; + if (typeof value === "string" && value.trim().length > 0) { + parts.push(`${key}: "${clip(value, 80)}"`); + break; + } + } + return `${tool}${parts.length === 0 ? "" : ` (${parts.join(", ")})`}`; +}; + +/** Runs a logged call: started before it runs, finished with its outcome after. */ +export const logged = Effect.fn("t4.loggedToolCall")(function* ( + store: T4Store.T4StoreShape, + input: { readonly threadId: string; readonly tool: string; readonly args: unknown }, + run: Effect.Effect, + outcome: (value: A) => string, +) { + const id = T4Store.newToolCallId(); + yield* store + .startToolCall({ + id, + threadId: input.threadId, + tool: input.tool, + summary: callSummary(input.tool, input.args), + }) + .pipe(Effect.ignoreCause({ log: true })); + return yield* run.pipe( + Effect.onExit((exit) => + store + .finishToolCall(id, exit._tag === "Success" ? outcome(exit.value) : "failed") + .pipe(Effect.ignoreCause({ log: true })), + ), + ); +}); + +/** The restart note's list of this thread's T3 tool calls from before the restart, or "". */ +export const restartToolCallsNote = Effect.fn("t4.restartToolCallsNote")(function* ( + threadId: string, +) { + const store = yield* Effect.serviceOption(T4Store.T4Store); + if (Option.isNone(store)) return ""; + const calls = yield* store.value + .takeRestartToolCalls(threadId) + .pipe(Effect.orElseSucceed(() => [])); + const cut = calls.filter((call) => call.finishedAt === null); + const done = calls.filter((call) => call.finishedAt !== null); + if (cut.length === 0 && done.length === 0) return ""; + const lines: Array = []; + if (cut.length > 0) { + lines.push( + "These T3 tool calls of yours were still running when T3 restarted, so they may have run only in part. Check their effect (`t3_owed`, `t3_thread_list`, `list_scheduled_tasks`, `release_queue`) before you repeat one; a `t3_handoff` repeated with the same message (or `clientRequestId`) is sent only once:", + ...cut.slice(0, 8).map((call) => `- ${call.summary}`), + ); + } + if (done.length > 0) { + lines.push( + "These finished before the restart, even if your side reported a connection error (ECONNRESET, interrupted) - don't repeat the ones that went through:", + ...done.slice(-8).map((call) => `- ${call.summary}: ${clip(call.result ?? "done", 160)}`), + ); + } + return lines.join("\n"); +}); diff --git a/apps/server/src/t4/worktreeNaming.test.ts b/apps/server/src/t4/worktreeNaming.test.ts index 36391279e7dfa..88d4f9c729d8c 100644 --- a/apps/server/src/t4/worktreeNaming.test.ts +++ b/apps/server/src/t4/worktreeNaming.test.ts @@ -1,7 +1,12 @@ import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as TestClock from "effect/testing/TestClock"; -import { uniqueWorktreePath, worktreeDirName } from "./worktreeNaming.ts"; +import { makeWorktreeCreationLock, uniqueWorktreePath, worktreeDirName } from "./worktreeNaming.ts"; describe("t4 worktree naming", () => { it("names a worktree by the issue id its branch carries, else a slug", () => { @@ -25,4 +30,69 @@ describe("t4 worktree naming", () => { assert.equal(path, "/t3/worktrees/usa-7-3"); }), ); + + it.effect("creates one worktree at a time per repository", () => + Effect.gen(function* () { + const withLock = makeWorktreeCreationLock(); + const never = () => Effect.succeed(false); + const release = yield* Deferred.make(); + const started = yield* Deferred.make(); + const log: Array = []; + const first = yield* withLock( + "/repo", + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen(Effect.sync(() => log.push("first done"))), + ), + never, + ).pipe(Effect.forkChild); + yield* Deferred.await(started); + const second = yield* withLock( + "/repo", + Effect.sync(() => log.push("second")), + never, + ).pipe(Effect.forkChild); + yield* withLock( + "/other", + Effect.sync(() => log.push("other repo")), + never, + ); + + const waited = yield* Fiber.join(second).pipe( + Effect.timeoutOption("1 second"), + Effect.forkChild, + ); + yield* TestClock.adjust("1 second"); + assert.isTrue(Option.isNone(yield* Fiber.join(waited))); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + assert.deepEqual(log, ["other repo", "first done", "second"]); + }), + ); + + it.effect("retries a failed creation once, and only when the failure allows it", () => + Effect.gen(function* () { + const withLock = makeWorktreeCreationLock(); + let attempts = 0; + const flaky = Effect.suspend(() => + ++attempts === 1 ? Effect.fail("locked" as const) : Effect.succeed("created"), + ); + assert.equal(yield* withLock("/repo", flaky, () => Effect.succeed(true)), "created"); + assert.equal(attempts, 2); + + attempts = 0; + const failing = Effect.failSync(() => `failed ${++attempts}`); + const retried = yield* withLock("/repo", failing, () => Effect.succeed(true)).pipe( + Effect.result, + ); + assert.deepEqual(retried, Result.fail("failed 2")); + + attempts = 0; + const lasting = yield* withLock("/repo", failing, () => Effect.succeed(false)).pipe( + Effect.result, + ); + assert.deepEqual(lasting, Result.fail("failed 1")); + }), + ); }); diff --git a/apps/server/src/t4/worktreeNaming.ts b/apps/server/src/t4/worktreeNaming.ts index 4bef45ae28f83..756e0999cd0a7 100644 --- a/apps/server/src/t4/worktreeNaming.ts +++ b/apps/server/src/t4/worktreeNaming.ts @@ -4,6 +4,7 @@ * contract: `create_worktree()` in t4's `t3agents.py`. */ import * as Effect from "effect/Effect"; +import * as Semaphore from "effect/Semaphore"; import { issueIdIn, slugOf } from "./T4Threads.ts"; @@ -28,3 +29,29 @@ export const uniqueWorktreePath = Effect.fn("t4.uniqueWorktreePath")(function* ( for (let n = 2; yield* exists(candidate); n++) candidate = join(parentDir, `${name}-${n}`); return candidate; }); + +/** + * Worktree creation, one at a time per repository: two launches into one repo picked the same free + * directory or collided on git's own locks. An attempt the `retryable` check clears runs once more. + */ +export const makeWorktreeCreationLock = () => { + const locks = new Map(); + return ( + repository: string, + attempt: Effect.Effect, + retryable: (error: E) => Effect.Effect, + ): Effect.Effect => { + let lock = locks.get(repository); + if (lock === undefined) { + lock = Semaphore.makeUnsafe(1); + locks.set(repository, lock); + } + return lock.withPermit( + attempt.pipe( + Effect.catch((error) => + retryable(error).pipe(Effect.flatMap((again) => (again ? attempt : Effect.fail(error)))), + ), + ), + ); + }; +}; diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 01ab4a8eddf0d..0a44490007818 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -46,7 +46,11 @@ import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts"; import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; -import { uniqueWorktreePath, worktreeNamingMode } from "../t4/worktreeNaming.ts"; +import { + makeWorktreeCreationLock, + uniqueWorktreePath, + worktreeNamingMode, +} from "../t4/worktreeNaming.ts"; import { parseRemoteNames, parseRemoteNamesInGitOrder, @@ -4248,129 +4252,154 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }, ); + const withWorktreeCreationLock = makeWorktreeCreationLock(); const createWorktree: GitVcsDriver.GitVcsDriver["Service"]["createWorktree"] = Effect.fn( "createWorktree", )(function* (input, options) { yield* refuseOptionLikeRefName("GitVcsDriver.createWorktree", input.cwd, input.refName); yield* refuseOptionLikeRefName("GitVcsDriver.createWorktree", input.cwd, input.newRefName); const targetBranch = input.newRefName ?? input.refName; - // Resolve sub/.. before taking the basename. - const repoName = path.basename(path.resolve(input.cwd)); - let worktreePath = input.path; - if (worktreePath == null) { - const parentDir = resolveWorktreesDirectory( - options?.worktreesDirectory ?? "", - worktreesDir, - path, - yield* HostProcess.HomeDirectory, - ); - if (parentDir === null) { - return yield* new GitCommandError({ - operation: "GitVcsDriver.createWorktree", - command: "git worktree add", - cwd: input.cwd, - detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.`, - }); - } - // t4 fork: short, flat worktree directories (T4_WORKTREE_NAMING=issueId). - if (worktreeNamingMode() === "issueId") { - worktreePath = yield* uniqueWorktreePath( - parentDir, - targetBranch, - (...parts) => path.join(...parts), - (candidate) => fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false)), + const progress = options?.progress; + // t4 fork: one worktree creation at a time per repository, retried once (t4/worktreeNaming.ts). + let attemptedPath: string | null = null; + const addWorktree = Effect.gen(function* () { + attemptedPath = null; + // Resolve sub/.. before taking the basename. + const repoName = path.basename(path.resolve(input.cwd)); + let worktreePath = input.path; + if (worktreePath == null) { + const parentDir = resolveWorktreesDirectory( + options?.worktreesDirectory ?? "", + worktreesDir, + path, + yield* HostProcess.HomeDirectory, ); - } else { - const identity = `${yield* readGitCommonDir(input.cwd)}\0${targetBranch}`; - const hash = yield* digest.digest(Digest.sha256, new TextEncoder().encode(identity)); - // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows. - let prefix = ""; - for (const character of targetBranch.replace(/\//g, "-")) { - if (Buffer.byteLength(prefix + character) > 23) break; - prefix += character; + if (parentDir === null) { + return yield* new GitCommandError({ + operation: "GitVcsDriver.createWorktree", + command: "git worktree add", + cwd: input.cwd, + detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.`, + }); + } + // t4 fork: short, flat worktree directories (T4_WORKTREE_NAMING=issueId). + if (worktreeNamingMode() === "issueId") { + worktreePath = yield* uniqueWorktreePath( + parentDir, + targetBranch, + (...parts) => path.join(...parts), + (candidate) => fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false)), + ); + } else { + const identity = `${yield* readGitCommonDir(input.cwd)}\0${targetBranch}`; + const hash = yield* digest.digest(Digest.sha256, new TextEncoder().encode(identity)); + // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows. + let prefix = ""; + for (const character of targetBranch.replace(/\//g, "-")) { + if (Buffer.byteLength(prefix + character) > 23) break; + prefix += character; + } + const directoryName = `${prefix}-${Hex.encode(hash).slice(0, 16)}`; + worktreePath = path.join(parentDir, repoName, directoryName); } - const directoryName = `${prefix}-${Hex.encode(hash).slice(0, 16)}`; - worktreePath = path.join(parentDir, repoName, directoryName); } - } - const newRefName = input.newRefName; - if (newRefName) { - // Kept apart from the checkout so the shared-config lock only covers the tracking write. - yield* createBranchAt( - "GitVcsDriver.createWorktree.createBranch", - { cwd: input.cwd, branch: newRefName, startPoint: input.refName }, - "git worktree add failed", - ); - } - const checkoutRef = newRefName ?? input.refName; - const progress = options?.progress; - const onCheckoutProgress = progress?.onCheckoutProgress; + const newRefName = input.newRefName; + if (newRefName) { + // Kept apart from the checkout so the shared-config lock only covers the tracking write. + yield* createBranchAt( + "GitVcsDriver.createWorktree.createBranch", + { cwd: input.cwd, branch: newRefName, startPoint: input.refName }, + "git worktree add failed", + ); + } + const checkoutRef = newRefName ?? input.refName; + const onCheckoutProgress = progress?.onCheckoutProgress; - // Both reads leave the repository alone, so they share one round trip before the checkout. - const [configuredCheckoutWorkers, base] = yield* Effect.all( - [ - readConfigValue(input.cwd, "checkout.workers"), - input.newRefName && input.baseRefName - ? resolveBranchBase(input.cwd, input.baseRefName) - : Effect.succeed(null), - ], - { concurrency: "unbounded" }, - ); - const checkoutWorkers = configuredCheckoutWorkers ?? "0"; - const fastCheckout = checkoutCache !== undefined && options?.fastCheckout === true; - const cacheGeneration = fastCheckout ? yield* checkoutCache.currentGeneration : 0; - const stockCheckout = executeGitWithStableDiagnostics( - "GitVcsDriver.createWorktree", - input.cwd, - [ - "-c", - `checkout.workers=${checkoutWorkers}`, - "worktree", - "add", - "--", - worktreePath, - checkoutRef, - ], - { - fallbackErrorDetail: "git worktree add failed", - // Large checkouts and post-checkout hooks can legitimately run for many - // minutes; a fixed deadline kills them and leaves an orphaned worktree. - timeoutMs: null, - ...(onCheckoutProgress - ? { - // Git only prints checkout progress when stderr is a tty or the - // delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe. - env: { GIT_PROGRESS_DELAY: "0" }, - progress: { - onStderrLine: (line) => { - const parsed = parseGitCheckoutProgressLine(line); - return parsed ? onCheckoutProgress(parsed) : Effect.void; + // Both reads leave the repository alone, so they share one round trip before the checkout. + const [configuredCheckoutWorkers, base] = yield* Effect.all( + [ + readConfigValue(input.cwd, "checkout.workers"), + input.newRefName && input.baseRefName + ? resolveBranchBase(input.cwd, input.baseRefName) + : Effect.succeed(null), + ], + { concurrency: "unbounded" }, + ); + const checkoutWorkers = configuredCheckoutWorkers ?? "0"; + const fastCheckout = checkoutCache !== undefined && options?.fastCheckout === true; + const cacheGeneration = fastCheckout ? yield* checkoutCache.currentGeneration : 0; + attemptedPath = worktreePath; + const stockCheckout = executeGitWithStableDiagnostics( + "GitVcsDriver.createWorktree", + input.cwd, + [ + "-c", + `checkout.workers=${checkoutWorkers}`, + "worktree", + "add", + "--", + worktreePath, + checkoutRef, + ], + { + fallbackErrorDetail: "git worktree add failed", + // Large checkouts and post-checkout hooks can legitimately run for many + // minutes; a fixed deadline kills them and leaves an orphaned worktree. + timeoutMs: null, + ...(onCheckoutProgress + ? { + // Git only prints checkout progress when stderr is a tty or the + // delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe. + env: { GIT_PROGRESS_DELAY: "0" }, + progress: { + onStderrLine: (line) => { + const parsed = parseGitCheckoutProgressLine(line); + return parsed ? onCheckoutProgress(parsed) : Effect.void; + }, }, - }, - } - : {}), - }, - ); - yield* ( - fastCheckout - ? checkoutCache - .create({ cwd: input.cwd, worktreePath, refName: checkoutRef, checkoutWorkers }) - .pipe(Effect.flatMap((cloned) => (cloned ? Effect.void : stockCheckout))) - : stockCheckout - ).pipe( - Effect.onError(() => - newRefName - ? deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }).pipe( - Effect.catch((cause) => - Effect.logWarning("could not remove the branch of a failed worktree", { cause }), + } + : {}), + }, + ); + yield* ( + fastCheckout + ? checkoutCache + .create({ cwd: input.cwd, worktreePath, refName: checkoutRef, checkoutWorkers }) + .pipe(Effect.flatMap((cloned) => (cloned ? Effect.void : stockCheckout))) + : stockCheckout + ).pipe( + Effect.onError(() => + newRefName + ? deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }).pipe( + Effect.catch((cause) => + Effect.logWarning("could not remove the branch of a failed worktree", { cause }), + ), + ) + : Effect.void, + ), + ); + if (fastCheckout) { + yield* checkoutCache.schedule(worktreePath, cacheGeneration); + } + + return { worktreePath, base }; + }); + const { worktreePath, base } = yield* withWorktreeCreationLock( + path.resolve(input.cwd), + addWorktree, + // Retry only a failure git did not explain as lasting (an existing branch or path) and that + // left no checkout behind, so no checkout hook ran. + (error) => + error.reason !== undefined && error.reason !== "config_locked" + ? Effect.succeed(false) + : attemptedPath === null + ? Effect.succeed(true) + : fileSystem.exists(attemptedPath).pipe( + Effect.map((exists) => !exists), + Effect.orElseSucceed(() => false), ), - ) - : Effect.void, - ), ); - if (fastCheckout) { - yield* checkoutCache.schedule(worktreePath, cacheGeneration); - } + const newRefName = input.newRefName; if (progress?.onWorktreeClaimed) { yield* progress.onWorktreeClaimed(worktreePath); diff --git a/docs/t4/DESIGN.md b/docs/t4/DESIGN.md index 6f3e5101e2c1e..49436fbc2d757 100644 --- a/docs/t4/DESIGN.md +++ b/docs/t4/DESIGN.md @@ -21,27 +21,27 @@ unchanged. ### Extended T3 tools -| Tool | From | Change | -| ----------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `t3_thread_send` | `cmd_msg`, `deliver` | Messages between threads carry the sender header `Message from thread "" (<short>):`. The two delivery notes are prepended when they apply: an unanswered ask-user question ("this message is NOT their answer … ask again"), and a Claude tool call cancelled by the steer ("this message cancelled it - not the user"). Archived targets are refused. Thread-to-thread messages steer a running turn by default; `restart` is t4's `--interrupt`. A message after a pending settle cancels it unless it is a notice (see `t3_thread_organize`). Release managers receive turns on the RM model. | -| `t3_thread_organize` (`settle`) | `cmd_settle`, `tick_settles`, `dev_footprint` | Refused for release managers ("release managers never settle") and while the thread owes anything (lists who, voiding closed askers). Retires the worktree's dev footprint with the repo's `scripts/*dev-retire` when there is one ("no dev environment to retire" otherwise; failure is left to the reaper). Notes pending wakes. Settles when the turn ends (existing `settlesWhenTurnEnds`); a later non-notice message cancels the request and tells the thread. `archive` on an asker voids debts owed to it. | -| `t3_thread_launch` | `cmd_spawn`, `create_worktree`, `new_thread` | `workspaceStrategy: worktree` names the directory by the worktree naming setting (§3): issue id from the branch, else a slug, `-2…` suffixes, full branch kept, started from `origin/<base>`, project setup scripts run. New: `anyway` (the live-thread guard: running or active <3 h in the project, excluding the caller and release managers, refuses unless set), `modelPreset` (named selections, e.g. the dashboard's Codex/Claude presets), full access by default. When the caller is a thread: a parent→child `spawn` ledger entry and the spawn footer (release-manager wording when the parent is one). | -| `create_threads` | — | Same parent→child ledger entries and footers as `t3_thread_launch` when called from a thread; same live-thread guard. | -| `delegate_task` | — | Unchanged behaviour. Its child threads are listed with their parent (lineage) in `t3_thread_list`; the instructions say when to delegate versus launch. | -| `schedule_task`, `list_scheduled_tasks`, `update_scheduled_task`, `delete_scheduled_task` | `cmd_wake`, `wake_list/cancel/adjust`, `tick_wakes` | New schedules: one-shot `{type:'at', at}` and `{type:'in', delayMs}`, and `{type:'cron', expression}` (5 fields) alongside `interval`, `fixed_time` and `webhook`. New `threadId` target (wake another thread). Thread-bound wakes: at most 8 pending per thread, one-shots at most 30 days out, intervals at least 5 minutes. A thread-bound run is delivered as `WAKE #<n> (you scheduled this <when>):` + note, with the recurring footer; archived or deleted targets drop the wake; a failed delivery retries next minute. List/update/delete give wake list/adjust/cancel. | -| `t3_thread_list` | `cmd_sessions` | Each thread also reports `isReleaseManager`, `owes` and `owedBy` counts, the caller marker, and the t4 state (running / waiting-you / settled / snoozed / idle / archived). New `allProjects` option. | -| `t3_thread_read` | `cmd_show` | Adds the ledger entries the thread owes and is owed, and the release-manager flag. | -| `t3_thread_update` | `cmd_title` | Unchanged (`rename` covers it). | -| `t3_worktree_handoff` | — | Uses the worktree naming setting. | -| `request_secret` | — | Returns `pending` at once; the card stays open until the user answers, through restarts. The answer reaches the agent as a message (`secret_request.record` `wake`): the file path (written first) or the one-use secretRef, or the decline. Only Stop or archiving the thread closes it; the same label asked again replaces an older open card. `timeoutMs` is ignored (upstream waited up to an hour, then closed the card). | +| Tool | From | Change | +| ----------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `t3_thread_send` | `cmd_msg`, `deliver` | Messages between threads carry the sender header `Message from thread "<title>" (<short>):`. The two delivery notes are prepended when they apply: an unanswered ask-user question ("this message is NOT their answer … ask again"), and a Claude tool call cancelled by the steer ("this message cancelled it - not the user"). Archived targets are refused. A plain (`auto`) message from another thread waits for a running turn to end instead of steering into it, so the command it runs is never cut; `steer` cuts in, `restart` is t4's `--interrupt`. A message after a pending settle cancels it unless it is a notice (see `t3_thread_organize`). Release managers receive turns on the RM model. | +| `t3_thread_organize` (`settle`) | `cmd_settle`, `tick_settles`, `dev_footprint` | Refused for release managers ("release managers never settle") and while the thread owes anything (lists who, voiding closed askers). Retires the worktree's dev footprint with the repo's `scripts/*dev-retire` when there is one ("no dev environment to retire" otherwise; failure is left to the reaper). Notes pending wakes. Settles when the turn ends (existing `settlesWhenTurnEnds`); a later non-notice message cancels the request and tells the thread. `archive` on an asker voids debts owed to it. | +| `t3_thread_launch` | `cmd_spawn`, `create_worktree`, `new_thread` | `workspaceStrategy: worktree` names the directory by the worktree naming setting (§3): issue id from the branch, else a slug, `-2…` suffixes, full branch kept, started from `origin/<base>`, project setup scripts run. New: `anyway` (the live-thread guard: running or active <3 h in the project, excluding the caller and release managers, refuses unless set), `modelPreset` (named selections, e.g. the dashboard's Codex/Claude presets), full access by default. When the caller is a thread: a parent→child `spawn` ledger entry and the spawn footer (release-manager wording when the parent is one). | +| `create_threads` | — | Same parent→child ledger entries and footers as `t3_thread_launch` when called from a thread; same live-thread guard. | +| `delegate_task` | — | Unchanged behaviour. Its child threads are listed with their parent (lineage) in `t3_thread_list`; the instructions say when to delegate versus launch. | +| `schedule_task`, `list_scheduled_tasks`, `update_scheduled_task`, `delete_scheduled_task` | `cmd_wake`, `wake_list/cancel/adjust`, `tick_wakes` | New schedules: one-shot `{type:'at', at}` and `{type:'in', delayMs}`, and `{type:'cron', expression}` (5 fields) alongside `interval`, `fixed_time` and `webhook`. New `threadId` target (wake another thread). Thread-bound wakes: at most 8 pending per thread, one-shots at most 30 days out, intervals at least 5 minutes. A thread-bound run is delivered as `WAKE #<n> (you scheduled this <when>):` + note, with the recurring footer; archived or deleted targets drop the wake; a failed delivery retries next minute. List/update/delete give wake list/adjust/cancel. | +| `t3_thread_list` | `cmd_sessions` | Each thread also reports `isReleaseManager`, `owes` and `owedBy` counts, the caller marker, and the t4 state (running / waiting-you / settled / snoozed / idle / archived). New `allProjects` option. | +| `t3_thread_read` | `cmd_show` | Adds the ledger entries the thread owes and is owed, and the release-manager flag. | +| `t3_thread_update` | `cmd_title` | Unchanged (`rename` covers it). | +| `t3_worktree_handoff` | — | Uses the worktree naming setting. | +| `request_secret` | — | Returns `pending` at once; the card stays open until the user answers, through restarts. The answer reaches the agent as a message (`secret_request.record` `wake`): the file path (written first) or the one-use secretRef, or the decline. Only Stop or archiving the thread closes it; the same label asked again replaces an older open card. `timeoutMs` is ignored (upstream waited up to an hour, then closed the card). | ### New T3 tools -| Tool | From | Behaviour | -| -------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `t3_handoff` | `cmd_handoff`, `settle_owed`, `record_handoff`, `find_rm` | Hand work over with an explicit ledger effect. Parameters: `message`, `threadId?`, `done?`, `ask?`, `fyi?`, `interrupt?`, `check?`, `includeRetired?`. Without `threadId`: to the project's release manager, always `ask` (the RM itself is refused; `fyi` refused); if none exists, create `Release manager — <project>` on the RM model, pin it, record it, and deliver intro + handoff as its first turn. With `threadId`: one of `done`/`ask`/`fyi` required, `fyi`+`ask` refused, self refused; an owner's handoff to a release manager is forced to `ask` (with the note). `done` settles every open entry from target→caller. Header `HANDOFF from "<title>" (<short>, <where>) — <labels>:`; reply footer when asking. Non-asking deliveries are recorded as notices. `ask` opens or updates the single (from, to) entry. Result: delivery mode, entries settled, "now owes you", and "you still owe them". `check` returns the release manager or none. | -| `t3_owed` | `cmd_owed`, `requester_closed` | What the caller owes (or, with `all`, the whole project), oldest first; debts to a settled, archived or deleted asker are void and omitted. | -| `t3_decisions` | `cmd_decisions` | The user's answers to ask-user questions over `days` (default 14), this project or `all`, newest first; an answer that isn't an offered option is reported as a note (a standing rule). | +| Tool | From | Behaviour | +| -------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `t3_handoff` | `cmd_handoff`, `settle_owed`, `record_handoff`, `find_rm` | Hand work over with an explicit ledger effect. Parameters: `message`, `threadId?`, `done?`, `ask?`, `fyi?`, `interrupt?`, `check?`, `includeRetired?`. Without `threadId`: to the project's release manager, always `ask` (the RM itself is refused; `fyi` refused); if none exists, create `Release manager — <project>` on the RM model, pin it, record it, and deliver intro + handoff as its first turn. With `threadId`: one of `done`/`ask`/`fyi` required, `fyi`+`ask` refused, self refused; an owner's handoff to a release manager is forced to `ask` (with the note). `done` settles every open entry from target→caller. Header `HANDOFF from "<title>" (<short>, <where>) — <labels>:`; reply footer when asking (not to a release manager, whose handoffs and run-watch wakes open with its queue and the threads it owes instead). Non-asking deliveries are recorded as notices; a pure `fyi` waits for a running turn to end, `done`/`ask` steer in. A repeat with the same `clientRequestId`, or the same message within an hour, returns the first result. `ask` opens or updates the single (from, to) entry. Result: delivery mode, entries settled, "now owes you", and "you still owe them". `check` returns the release manager or none. | +| `t3_owed` | `cmd_owed`, `requester_closed` | What the caller owes (or, with `all`, the whole project), oldest first; debts to a settled, archived or deleted asker are void and omitted. | +| `t3_decisions` | `cmd_decisions` | The user's answers to ask-user questions over `days` (default 14), this project or `all`, newest first; an answer that isn't an offered option is reported as a note (a standing rule). | ### Linked issues (Linear) @@ -147,6 +147,8 @@ planner statistics, and rolling back means ignoring one file. Tables: is unused - `t4_settle_requests` (thread_id, requested_at) - `t4_stalls` +- `t4_release_queue`; `t4_release_waiters` (threads that asked for a PR's staging and shipped notices) +- `t4_tool_calls`: write tool calls as they start and end, a day; after a restart the continuation lists the ones that never finished and the ones that did One-time import on first start from `~/.config/t3-agents/state/*.json` (handoffs, notices, release-managers, wakes, settle-requests); the files stay diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 6199117dbc22a..ab78759ef65b1 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -357,6 +357,13 @@ export const OrchestratorMcpThreadListInput = Schema.Struct({ includeSubagents: Schema.optional(Schema.Boolean), cursor: Schema.optional(NonNegativeInt), limit: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(100))), + /** t4 fork (AI-93): rows are compact unless this is set. */ + detail: Schema.optional( + Schema.Boolean.annotate({ + description: + "true: full rows (model, modes, creator, run, timestamps). Default: compact rows.", + }), + ), }); export type OrchestratorMcpThreadListInput = typeof OrchestratorMcpThreadListInput.Type; @@ -388,31 +395,32 @@ export const OrchestratorMcpThreadPullRequest = Schema.Struct({ }); export type OrchestratorMcpThreadPullRequest = typeof OrchestratorMcpThreadPullRequest.Type; +/** t4 fork (AI-93): a compact row by default; `detail: true` fills every optional field. */ export const OrchestratorMcpThreadListItem = Schema.Struct({ threadId: ThreadId, - projectId: ProjectId, /** t4 fork. */ t4: Schema.optional(OrchestratorMcpThreadT4Facts), title: Schema.String, link: Schema.optional(Schema.String), - createdBy: OrchestrationV2Actor, - creationSource: OrchestrationV2CreationSource, status: OrchestratorMcpThreadStatus, - latestRunId: Schema.NullOr(RunId), - providerInstanceId: ProviderInstanceId, - model: Schema.String, - runtimeMode: RuntimeMode, - interactionMode: ProviderInteractionMode, - linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest), - settled: Schema.Boolean, - settledAt: Schema.NullOr(IsoDateTime), - snoozed: Schema.Boolean, - snoozedUntil: Schema.NullOr(IsoDateTime), - parentThreadId: Schema.NullOr(ThreadId), - relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), - itemCount: NonNegativeInt, - createdAt: IsoDateTime, updatedAt: IsoDateTime, + linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + settled: Schema.optional(Schema.Boolean), + snoozed: Schema.optional(Schema.Boolean), + parentThreadId: Schema.optional(Schema.NullOr(ThreadId)), + projectId: Schema.optional(ProjectId), + createdBy: Schema.optional(OrchestrationV2Actor), + creationSource: Schema.optional(OrchestrationV2CreationSource), + latestRunId: Schema.optional(Schema.NullOr(RunId)), + providerInstanceId: Schema.optional(ProviderInstanceId), + model: Schema.optional(Schema.String), + runtimeMode: Schema.optional(RuntimeMode), + interactionMode: Schema.optional(ProviderInteractionMode), + settledAt: Schema.optional(Schema.NullOr(IsoDateTime)), + snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)), + relationshipToParent: Schema.optional(Schema.NullOr(Schema.Literals(["fork", "subagent"]))), + itemCount: Schema.optional(NonNegativeInt), + createdAt: Schema.optional(IsoDateTime), }); export type OrchestratorMcpThreadListItem = typeof OrchestratorMcpThreadListItem.Type; @@ -423,6 +431,8 @@ export const OrchestratorMcpThreadListResult = Schema.Struct({ threads: Schema.Array(OrchestratorMcpThreadListItem), nextCursor: Schema.NullOr(NonNegativeInt), total: NonNegativeInt, + /** t4 fork (AI-93): how to see what a compact row leaves out. */ + more: Schema.optional(Schema.String), }); export type OrchestratorMcpThreadListResult = typeof OrchestratorMcpThreadListResult.Type; @@ -527,6 +537,8 @@ export const OrchestratorMcpThreadTimelineItem = Schema.Struct({ text: Schema.NullOr(Schema.String), textTruncated: Schema.Boolean, nextTextOffset: Schema.optional(Schema.NullOr(NonNegativeInt)), + /** t4 fork (AI-93): characters left after this page of a cut item's text. */ + remainingChars: Schema.optional(NonNegativeInt), updatedAt: IsoDateTime, }); export type OrchestratorMcpThreadTimelineItem = typeof OrchestratorMcpThreadTimelineItem.Type; @@ -775,12 +787,39 @@ export const OrchestratorMcpListScheduledTasksInput = Schema.Struct({ "true: every task in the project, finished ones too. Default: your thread's pending tasks.", }), ), + /** t4 fork (AI-93): one task in full; list rows are compact. */ + scheduledTaskId: Schema.optional( + ScheduledTaskId.annotate({ + description: "Read this one task in full (whole prompt, webhook URL) as `task`.", + }), + ), }); export type OrchestratorMcpListScheduledTasksInput = typeof OrchestratorMcpListScheduledTasksInput.Type; +/** t4 fork (AI-93): a list row; the prompt is cut to a preview. */ +export const OrchestratorMcpScheduledTaskRow = Schema.Struct({ + scheduledTaskId: ScheduledTaskId, + title: Schema.String, + enabled: Schema.Boolean, + boundThreadId: Schema.NullOr(ThreadId), + schedule: ScheduledTaskSchedule, + nextRunAt: Schema.NullOr(IsoDateTime), + lastRunStatus: ScheduledTaskRunStatus, + promptPreview: Schema.String, + promptLength: NonNegativeInt, + blockedByPolicy: Schema.optional(Schema.String), +}); +export type OrchestratorMcpScheduledTaskRow = typeof OrchestratorMcpScheduledTaskRow.Type; + export const OrchestratorMcpListScheduledTasksResult = Schema.Struct({ - tasks: Schema.Array(OrchestratorMcpScheduledTask), + // Full rows still decode: a linked environment on an older version sends them. + tasks: Schema.Array( + Schema.Union([OrchestratorMcpScheduledTaskRow, OrchestratorMcpScheduledTask]), + ), + /** With `scheduledTaskId`. */ + task: Schema.optional(OrchestratorMcpScheduledTask), + more: Schema.optional(Schema.String), }); export type OrchestratorMcpListScheduledTasksResult = typeof OrchestratorMcpListScheduledTasksResult.Type; diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 50e3a8a0ac296..af7a4f947d5a3 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -14,7 +14,7 @@ The \`t3-code\` MCP server is how your thread works with other threads. Its tool - \`t3_handoff\` moves work between threads with an explicit effect on the ledger of who owes whom an answer. The ledger moves only on its flags, never on wording: \`done\` answers what you owe that thread, \`ask\` makes it owe you a reply, \`fyi\` does neither; \`done\` combines with \`ask\` or \`fyi\`. One of them is required when you name \`to\`. - Each project has one persistent release manager. When your work is finished (your PR is green and has the merge word), \`t3_handoff\` without \`to\` hands it the release; it answers with \`t3_handoff\` \`done\`. A handoff to the release manager is always a request. Release managers never settle. - \`t3_owed\` lists what you still owe. Answer each before you settle. -- \`t3_thread_send\` sends a plain message: it steers a running turn, and \`restart\` interrupts it. A message never moves the ledger; use \`t3_handoff\` for anything owed or asked. +- \`t3_thread_send\` sends a plain message: a running turn gets it when that turn ends, \`steer\` cuts in now, and \`restart\` interrupts it. A message never moves the ledger; use \`t3_handoff\` for anything owed or asked. - When your work is fully closed - nothing owed, nothing awaiting the user - settle your thread as the last act of the turn (\`t3_thread_organize\` with \`settle\`). A later message, other than a handoff that asks nothing, cancels it and you are told. - \`t3_decisions\` lists the user's earlier answers to ask-user questions; an answer that isn't one of the offered options is a standing rule. Check it before asking something the user may already have decided.`, `### Subagents