From 743698e700638cddc4d3fc4c0ad89e6c132fab40 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:11:22 -0500 Subject: [PATCH 1/4] fix(runner): preserve OpenCode bash process exit codes (#18076) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native Runner stores structured tool events so people can inspect actual work. > - OpenCode puts a completed bash command's process exit in `state.metadata.exit`. > - The canonical event mapper only read `state.exit`, so a real nonzero exit became unknown. > - This pull request preserves the documented builtin bash exit and rejects conflicting evidence. > - The benefit is an accurate process exit without changing tool completion or native run status. ## Linked Issues or Issue Description **What happened?** A completed OpenCode bash part with `state.metadata.exit: 37` produced `exitCode: null`. The process result was present, but the canonical tool event lost it. The pinned upstream [shell result](https://github.com/anomalyco/opencode/blob/v1.18.34/packages/opencode/src/tool/shell.ts#L544-L552) and [completed part](https://github.com/anomalyco/opencode/blob/v1.18.34/packages/opencode/src/session/processor.ts#L160-L170) establish the field path. **Expected behavior** The canonical event retains the numeric process exit from a completed builtin bash part. A completed tool call can have a nonzero command exit. Missing or invalid evidence must not become a successful command. **Steps to reproduce** 1. Pass a `type: "tool"`, `tool: "bash"` part with completed state and numeric `metadata.exit` to `canonicalProviderEventsFromOpenCodePart`. 2. Inspect `tool.execution.completed.payload.exitCode`. 3. Before this fix, the value is null. After this fix, it matches the process exit. **Paperclip version or commit** Reproduced on master `f4f02880cae4f5fa54d47d39565ca99b6b72446d`. Duplicate searches found no matching fix. Related PR #15715 concerns OpenCode V2 transport and version support; it does not change this mapper. ## What Changed - Read numeric metadata exits only from completed builtin bash parts. - Keep legacy numeric top-level exits. Return unknown when supplied legacy evidence conflicts. - Cover zero and nonzero exits, invalid values, foreign tools, incomplete calls and conflicting receipts. - Document the run-log field and the distinction between tool completion and command success. ## Verification - The regression suite first failed five assertions on the unchanged mapper. All 53 provider-event tests now pass. - A focused no-emit TypeScript check covers the changed mapper, its tests and imported protocol validators. - Tests use synthetic structured parts and real protocol validation. No local database, provider, SDK build or live scenario was run. - All 48 jobs in the normal PR workflow passed, including the required `ci / verify` and `ci / e2e` gates. CI also executed all 53 provider-event tests. - Greptile reviewed this exact head at 5/5 with no actionable findings. The separate hosted quality-gate review also completed successfully. ## Risks - Conflicting legacy and metadata exits now remain unknown for completed builtin bash calls. This avoids selecting one inconsistent value as proof. - Other tools retain their existing legacy behavior. Output prose never supplies an exit code. - The change adds no schema field and changes no provider version, budget, accounting, fixture or native run outcome. ## Model Used OpenAI `gpt-6.1-sol` through Codex, with reasoning and terminal tools. The session does not expose the context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- doc/run-log-events.md | 8 ++++ .../src/provider-events.test.ts | 47 +++++++++++++++++++ .../paperclip-runner/src/provider-events.ts | 15 +++++- 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index b449def19f6..5672c6a693c 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -92,6 +92,14 @@ They also become native Observability spans only with an operator OTLP endpoint. ## Native PRP Run-Log Events +Completed OpenCode builtin `bash` parts preserve the numeric process exit from +`state.metadata.exit` in `tool.execution.completed.payload.exitCode`. The tool +status stays `completed` even when the command exits with a nonzero code. This +status describes completion of the tool call, not success of the command or the +native run. Metadata adds an exit only when it is an integer. Conflicting supplied +legacy exits stay unknown. Existing numeric `state.exit` values remain supported; +metadata on other tools cannot add process-exit proof. + `auth.credentials.updated` is a runner-produced PRP event for a change to a supported credential store, including account identity changes and later token refreshes on the new account. The bundled transport awaits a host commit callback diff --git a/packages/paperclip-runner/src/provider-events.test.ts b/packages/paperclip-runner/src/provider-events.test.ts index a35c21179fd..ea9469238d2 100644 --- a/packages/paperclip-runner/src/provider-events.test.ts +++ b/packages/paperclip-runner/src/provider-events.test.ts @@ -484,6 +484,53 @@ describe("provider-neutral events", () => { ).toEqual([]); }); + it.each([0, 37, -1])("preserves OpenCode bash metadata exit %i without changing tool completion", (exit) => { + const event = canonicalProviderEventsFromOpenCodePart({ + id: "bash-part", type: "tool", tool: "bash", callID: "bash-call", + state: { status: "completed", input: { command: "node verify.mjs" }, + output: "Work validation finished", metadata: { exit, truncated: false }, time: { start: 1, end: 2 } }, + })[0]!; + expect(event).toMatchObject({ eventType: "tool.execution.completed", itemId: "bash-part", + payload: { executionId: "bash-part", name: "bash", status: "completed", exitCode: exit } }); + expect(validatePrpEvent(envelope(event)).ok).toBe(true); + }); + + it.each([undefined, null, "37", 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])("does not infer a bash exit from invalid metadata %s", (exit) => { + const event = canonicalProviderEventsFromOpenCodePart({ id: "bash-invalid", type: "tool", tool: "bash", + state: { status: "completed", output: "exitCode=37", metadata: { exit } } })[0]!; + expect(event.payload.exitCode).toBeNull(); + }); + + it.each([ + { type: "tool", tool: "read", state: { status: "completed" } }, + { type: "tool", tool: "mcp_bash", state: { status: "completed" } }, + { type: "tool", tool: "unknown", callID: "functions.bash:0", state: { status: "completed" } }, + { type: "bash", state: { status: "completed" } }, + { type: "tool", tool: "bash", state: { status: "running" } }, + { type: "tool", tool: "bash", state: { status: "error", error: "Tool execution aborted" } }, + ])("rejects metadata exits outside a completed builtin bash part %#", (part) => { + const event = canonicalProviderEventsFromOpenCodePart({ id: "not-bash-complete", ...part, + state: { ...part.state, metadata: { exit: 37 } } })[0]!; + expect(event.payload.exitCode).toBeNull(); + }); + + it.each([0, 37, "37", 1.5])("rejects conflicting legacy and metadata exits %s", (exit) => { + const event = canonicalProviderEventsFromOpenCodePart({ id: "bash-conflict", type: "tool", tool: "bash", + state: { status: "completed", exit, metadata: { exit: 1 } } })[0]!; + expect(event.payload.exitCode).toBeNull(); + }); + + it.each([ + { tool: "bash", exit: 37, metadata: undefined }, + { tool: "bash", exit: 37, metadata: { exit: 37 } }, + { tool: "bash", exit: 37, metadata: { exit: "37" } }, + { tool: "read", exit: 37, metadata: { exit: 1 } }, + ])("preserves an existing legacy numeric exit %#", ({ tool, exit, metadata }) => { + const event = canonicalProviderEventsFromOpenCodePart({ id: "legacy-exit", type: "tool", tool, + state: { status: "completed", exit, metadata } })[0]!; + expect(event.payload.exitCode).toBe(exit); + }); + it("maps OpenCode pending dynamic tools to a valid builtin execution start", () => { const event = canonicalProviderEventsFromOpenCodePart({ id: "prt_02c35c313001X42cqyvQrpXOFv", diff --git a/packages/paperclip-runner/src/provider-events.ts b/packages/paperclip-runner/src/provider-events.ts index a20ac855af1..dac4af58b80 100644 --- a/packages/paperclip-runner/src/provider-events.ts +++ b/packages/paperclip-runner/src/provider-events.ts @@ -1002,6 +1002,19 @@ export function canonicalProviderEventsFromCodex( return []; } +function openCodeToolExitCode( + part: Record, + state: Record, +): number | null { + const legacy = integer(state.exit); + if (part.type !== "tool" || part.tool !== "bash" || state.status !== "completed") { + return legacy; + } + const exit = integer(record(state.metadata).exit); + if (exit === null) return legacy; + return state.exit != null && legacy !== exit ? null : exit; +} + /** Maps documented OpenCode structured message parts. Unrecognized parts are deliberately unsupported. */ export function canonicalProviderEventsFromOpenCodePart( partValue: unknown, @@ -1051,7 +1064,7 @@ export function canonicalProviderEventsFromOpenCodePart( readOnly: /read|search|grep|find|list|glob/i.test(tool), status, durationMs: integer(state.time), - exitCode: integer(state.exit), + exitCode: openCodeToolExitCode(part, state), progress: status === "running" ? text(state.title).slice(0, 4000) || null : null, ...boundedOutput( From c74171d62060b61cf3aad28176ab9f9c9468f2ec Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:15:19 -0500 Subject: [PATCH 2/4] fix(recovery): retire superseded native workspace retries (#18077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip coordinates agents while retaining their work and execution authority. > - A failed native run can schedule an exact-session retry and retain a sandbox. > - An explicit task Retry can already have completed successfully on a successor. > - Recovery correctly refuses the old run after its task execution lock changes. > - It nevertheless leaves that old retry scheduled and its workspace without a preservation owner. > - This change retires that proven superseded retry and registers exact-source preservation together. > - Existing stop receipts and saved-file verification still control workspace switching. ## Linked Issues or Issue Description **What happened?** A native sandbox run failed before starting a provider turn. An explicit Retry completed on a linked successor. The original coordinator remained in `retryable_failure` with an active sandbox lease. Restart recovery returned `issue_execution_lock_changed`, while the ordinary sweep kept delaying it. A pending workspace selection then made every new task run fail during setup. **Expected behavior** Stop replaying a failed retry after its linked explicit successor has completed. Preserve the original files through the existing system worker. Keep the current task, ownership, pending choice, and unresolved action outcomes intact. **Steps to reproduce** 1. Persist a failed, unowned native run with a prepared remote workspace and `retryable_failure` coordinator. 2. Complete a same-company/task/agent explicit Retry linked to that run. 3. Release the task's old execution lock and schedule a workspace selection. 4. Run startup or ordinary retry recovery. Observe the old retry remain scheduled and the selection fail with an unfinished-recovery conflict. **Paperclip version or commit** Regression reproduced against `644937c931`. The current repair is based on refreshed master `60b8089a44`. **Deployment mode** Native Runner with remote sandbox workspaces. The reported runtime used ACPX Claude with per-turn lifecycle. The original provider session-resume rejection is not independently reproduced or claimed fixed here; this PR addresses the subsequent stranded recovery. Related: #17839 records preservation when restart classification becomes terminal. This change handles the earlier lock-mismatch return and ordinary retry admission after a completed explicit successor. It uses the same preservation service and does not require that PR. ## What Changed - Share a narrow superseded-retry settlement between startup recovery and the ordinary retry sweep. - Require a failed source with no coordinator owner or process, its exact prepared source lease, and a completed linked successor under the same company, task and agent. - Atomically retire replay and register preservation. Do not alter task state or create another provider run. - Add PostgreSQL lifecycle/safety regressions, a real-file preservation and workspace-selection regression, and execution/map documentation. ## Verification - Red: both startup and ordinary admission regressions left the old coordinator in `retryable_failure` with no preservation obligation. - Green: the same two cases retire the retry and retain the exact lease without another run or task mutation. - The assembled PostgreSQL/filesystem regression passes: workspace selection remains blocked before preservation, the existing service saves `saved.txt` and preserves newer local work, then the normal selection guard applies the pending shared workspace. - All 90 native retention/resumption cases pass. Three neighboring startup-recovery cases pass, including the blocked-owner inventory. Full recursive typecheck and full build pass at runtime head `23ddb213b4`; final `19d7738ae3` only moves the function comment into execution documentation. Map, module-boundary and diff checks pass. The duplicate full local Vitest run was stopped after 20 minutes in its first long general shard once the complete current-head hosted test gates passed; no complete local-suite pass is claimed. - Current-head CI has 53 passing checks and two intended Storybook skips, including full typecheck, all test shards, build, Runner verification, browser shards and both aggregate gates. The separate `commitperclip PR Review` job is still queued on `ubuntu-latest` with no assigned runner; its outcome remains pending. Greptile reviewed exact head `19d7738ae3` at 5/5, with zero unresolved threads. - Live acceptance passes on exact final source `19d7738ae3`: a disposable Daytona Linux sandbox, the current immutable staging fleet snapshot, SDK 0.203.0, a Darwin arm64 source host and Node 26.4.0. The real native workspace preparation/export and provider stop/start paths preserve an unpredictable report and newer host files. The ordinary workspace-selection guard stays blocked until preservation commits, then applies the pending shared workspace. - The old workload's start count and side-effect marker each remain one. Recovery creates no new run or native result. The sandbox finishes stopped and is then deleted by the probe; a final provider read confirms it is absent. - A second live acceptance also passes on the original runtime's older immutable snapshot with the source explicitly archived before recovery. It verifies cold source reopening, the same report/newer-file checks, one workload start and side effect, pending workspace application, and confirmed deletion. Its initial probe attempt used immediate archive/deletion reads and failed during asynchronous cleanup observation; bounded provider-state polling fixed the probe without a product change. The abandoned probe allocation is independently confirmed absent. - Scope: database fixtures represent the already-failed run and completed explicit successor. The old workload is a persistent shell process with observable file/side-effect markers, not a paid Claude turn. This qualifies the repaired recovery handoff and real provider preservation; it does not reproduce the initial ACPX session-resume rejection. - The original hosted task has only been inspected read-only. No rollout or original-task recovery is claimed. ## Risks - Incorrect successor classification could retire legitimate work. Matching requires the server-persisted explicit Retry link, same company/task/agent, later successful committed execution, no current source execution lock, no recorded process, no coordinator owner, and no workspace finalization owner. - Retirement is not a stop receipt. The exact source remains retained, unknown effects remain unknown, and workspace switching still waits for the existing worker's stop and file-persistence proof. - A failed preservation transaction rolls back retirement. No new scan, retry budget, schema or public API is introduced. ## Model Used OpenAI GPT-6 through Codex, with reasoning, tool use and code execution. The host does not expose a more specific model ID or the context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass — focused suites and live acceptance; full-suite status above - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green — separate template-review job still queued as noted above - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups — exact head `19d7738ae3` - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/execution-semantics.md | 10 +++ maps/agent-access-map/recovery.md | 3 + maps/feature-map/recovery.md | 3 + .../native-failed-workspace-recovery.test.ts | 78 +++++++++++++++++++ .../native-finalization-reconciler.ts | 7 +- .../native-runtime/native-restart-recovery.ts | 4 + .../native-runtime/native-superseded-retry.ts | 56 +++++++++++++ .../src/services/workspace-recovery.test.ts | 38 +++++++++ 8 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 server/src/services/native-runtime/native-superseded-retry.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 3546241c639..fb4754c95e4 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1369,6 +1369,16 @@ recording the proof and successor lineage. Retained provider files are not edite Bootstrap retries, exact-checkpoint resumes, and fresh replacement sessions share three total provider attempts, including the original attempt. Linked run IDs, controller restarts, and duplicate wakes do not reset this budget. Automatic attempts retain the 30-second delay. Replacement scheduling and predecessor lineage commit together, with one successor per predecessor and admission through the normal task locks, authorization, pause, approval, and budget gates. +A failed, unowned native sandbox retry can outlive an explicit Retry that already +completed successfully. Startup recovery and ordinary retry admission retire that +old retry only with the same company, task and agent, a linked completed successor, +and the exact prepared source lease. They atomically register file preservation +without replaying provider work or changing the current task. A live owner, +recorded process or mismatched source remains held. Retirement does not prove +termination or saved files; the existing stop-and-save worker must establish both +before workspace selection can proceed. Both callers hold the task, coordinator +and source-run locks throughout retirement and preservation registration. + When a same-run retry acquires a replacement plugin task lease, the executor reloads the prior task's durable Runner checkpoint before checking local lifecycle evidence. This includes retries after a provider turn omitted its diff --git a/maps/agent-access-map/recovery.md b/maps/agent-access-map/recovery.md index 48329cb29db..3456b5c5793 100644 --- a/maps/agent-access-map/recovery.md +++ b/maps/agent-access-map/recovery.md @@ -7,6 +7,9 @@ Feature ID: `recovery`. Native finalization deadline reconciliation records unfinished workspace preservation through the existing server-owned recovery path. It grants no additional agent API, provider-stop authority or permission to replay work. +The server also retires an unowned failed sandbox retry after its linked explicit +Retry completes. This only registers exact-source preservation; it neither changes +the current task nor supplies stop or saved-file proof. Remote process probes remain server-owned. Confirmed exit requires `ESRCH` or a zombie with the saved generation. Unknown adopted-process ownership rejects the diff --git a/maps/feature-map/recovery.md b/maps/feature-map/recovery.md index 6969e047fce..90126dacd6c 100644 --- a/maps/feature-map/recovery.md +++ b/maps/feature-map/recovery.md @@ -46,6 +46,9 @@ Agent access: [companion](../agent-access-map/recovery.md). New messages and orphan cleanup can register missing preservation automatically and wake the existing worker. Saved input still waits for verified stop and file persistence, then enters ordinary admission once. + A completed explicit Retry also retires its failed, unowned sandbox predecessor's + stale retry and registers preservation atomically. Current task state and live or + mismatched owners remain protected; workspace switching still waits for cleanup. - `unknown-outcome`: `recovery/unknown-outcome` — uncertain external side effects require inspection and an explicit decision, not automatic replay. - `user-continuation`: `recovery/user-continuation` — saved user messages after a stop are reconsidered once diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts index 37492f913c7..eb9425f715e 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts @@ -10,6 +10,8 @@ import { preserveCancelledNativeWorkspaces, preserveNativeFailedWorkspace, prese import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js"; import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js"; +import { claimNativeRestartRecoveries } from "./native-restart-recovery.js"; +import { claimNativeSessionResumptions } from "./native-finalization-reconciler.js"; const externalUrl = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim(); const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -51,6 +53,82 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]!; const actions = async (issueId: string) => db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)); + async function supersededRetry() { + const f = await seed(); + await db.update(heartbeatRuns).set({ nativePhase: "retryable_failure", startedAt: new Date(1), finishedAt: new Date(2) }) + .where(eq(heartbeatRuns.id, f.runId)); + await db.update(nativeRunFinalizations).set({ phase: "retryable_failure", attempt: 1, + recoveryState: "resuming_session", nextAttemptAt: new Date(0) }).where(eq(nativeRunFinalizations.runId, f.runId)); + const [successor] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, + issueId: f.issueId, nativeIssueId: f.issueId, runtimeMode: "native", status: "succeeded", nativePhase: "committed", + startedAt: new Date(3), finishedAt: new Date(4), contextSnapshot: { issueId: f.issueId, + previousRunId: f.runId, taskRetryRequestId: randomUUID() } }).returning(); + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.issueId)); + return { ...f, successor }; + } + + it.each(["restart", "resume"])("retires a superseded failed retry and preserves its files during %s recovery", async path => { + const f = await supersededRetry(); + const beforeTask = (await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]; + const recover = () => path === "restart" ? claimNativeRestartRecoveries({ db, runIds: [f.runId], restartKind: "hard" }) + : claimNativeSessionResumptions({ db, runIds: [f.runId], runnerInstanceId: "recovery" }); + await recover(); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]) + .toMatchObject({ phase: "terminal_failure", attempt: 1, leaseOwner: null, nextAttemptAt: null, + failureCode: "native_retry_superseded", failureDetail: { successorRunId: f.successor.id } }); + expect(await readRun(f.runId)).toMatchObject({ status: "failed", nativePhase: "terminal_failure", + resultJson: { originalDiagnostic: true, workspaceRestoreRecovery: { leaseIds: [f.lease.id] } } }); + expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" }); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(beforeTask); + const retainedActions = await actions(f.issueId); + expect(retainedActions).toHaveLength(1); + await recover(); + expect(await actions(f.issueId)).toEqual(retainedActions); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2); + }); + + it.each(["live_owner", "process", "current_execution", "unfinished_successor", "unlinked_successor", "foreign_successor", "mismatched_source"])( + "keeps an unverified superseded retry held: %s", async scenario => { + const f = await supersededRetry(); + if (scenario === "live_owner") await db.update(nativeRunFinalizations).set({ leaseOwner: "live-controller", + leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, f.runId)); + if (scenario === "process") await db.update(heartbeatRuns).set({ processPid: process.pid }).where(eq(heartbeatRuns.id, f.runId)); + if (scenario === "current_execution") await db.update(issues).set({ executionRunId: f.runId }).where(eq(issues.id, f.issueId)); + if (scenario === "unfinished_successor") await db.update(heartbeatRuns).set({ status: "running", nativePhase: "observed", finishedAt: null }) + .where(eq(heartbeatRuns.id, f.successor.id)); + if (scenario === "unlinked_successor") await db.update(heartbeatRuns).set({ contextSnapshot: { previousRunId: randomUUID(), taskRetryRequestId: randomUUID() } }) + .where(eq(heartbeatRuns.id, f.successor.id)); + if (scenario === "foreign_successor") { + const foreign = await seed(); + await db.update(heartbeatRuns).set({ contextSnapshot: {} }).where(eq(heartbeatRuns.id, f.successor.id)); + await db.insert(heartbeatRuns).values({ companyId: foreign.companyId, agentId: foreign.agentId, + issueId: foreign.issueId, nativeIssueId: foreign.issueId, runtimeMode: "native", status: "succeeded", nativePhase: "committed", + startedAt: new Date(3), finishedAt: new Date(4), contextSnapshot: { previousRunId: f.runId, taskRetryRequestId: randomUUID() } }); + } + if (scenario === "mismatched_source") await db.update(environmentLeases).set({ providerLeaseId: randomUUID() }) + .where(eq(environmentLeases.id, f.lease.id)); + const beforeRun = await readRun(f.runId), beforeLease = await readLease(f.lease.id); + await claimNativeSessionResumptions({ db, runIds: [f.runId], runnerInstanceId: "recovery" }); + expect(await readRun(f.runId)).toEqual(beforeRun); + expect(await readLease(f.lease.id)).toEqual(beforeLease); + expect(await actions(f.issueId)).toEqual([]); + }); + + it("rolls back retry retirement together with file preservation", async () => { + const f = await supersededRetry(); + const beforeRun = await readRun(f.runId), beforeLease = await readLease(f.lease.id); + const beforeCoordinator = (await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]; + await expect(db.transaction(async tx => { + await claimNativeSessionResumptions({ db: tx as unknown as typeof db, runIds: [f.runId], runnerInstanceId: "recovery" }); + expect((await tx.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0].phase).toBe("terminal_failure"); + throw new Error("rollback retry retirement"); + })).rejects.toThrow("rollback retry retirement"); + expect(await readRun(f.runId)).toEqual(beforeRun); + expect(await readLease(f.lease.id)).toEqual(beforeLease); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(beforeCoordinator); + expect(await actions(f.issueId)).toEqual([]); + }); + it("keeps another orphan recoverable while a task lock delays preservation", async () => { const busy = await seed(), free = await seed(); let unlock!: () => void, ready!: () => void; diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts index 283aac76b2d..fda887b8eb8 100644 --- a/server/src/services/native-runtime/native-finalization-reconciler.ts +++ b/server/src/services/native-runtime/native-finalization-reconciler.ts @@ -63,6 +63,7 @@ import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js"; import { isAutomaticRecoverySuppressedByPauseHold } from "../recovery/pause-hold-guard.js"; import { readRunCancellation } from "../run-cancellation.js"; import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; +import { retireSupersededNativeRetry } from "./native-superseded-retry.js"; export type NativeReconciliationFacts = { equivalentAttentionFamily?: boolean; @@ -392,7 +393,7 @@ export async function claimNativeSessionResumptions(input: { const [issue] = await tx.select().from(issues).where(and( eq(issues.companyId, candidate.companyId), eq(issues.id, candidate.issueId), )).for("update").limit(1); - if (!issue || !["todo", "in_progress", "in_review"].includes(issue.status)) return false; + if (!issue) return false; const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, candidate.companyId), eq(nativeRunFinalizations.runId, candidate.runId), eq(nativeRunFinalizations.issueId, issue.id), @@ -402,6 +403,10 @@ export async function claimNativeSessionResumptions(input: { eq(heartbeatRuns.nativeIssueId, issue.id), )).for("update").limit(1); if (!run || !coordinator) return false; + if (await retireSupersededNativeRetry(tx as unknown as Db, { + run, coordinator, issueExecutionRunId: issue.executionRunId, now, + })) return false; + if (!["todo", "in_progress", "in_review"].includes(issue.status)) return false; const row = { run, coordinator }; if ( row.run.runtimeMode !== "native" || diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 0c854b7fe13..a906c14c56e 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -26,6 +26,7 @@ import { issueRecoveryActionService } from "../issue-recovery-actions.js"; import { isNewTerminalRunFailure, reportRunFailure } from "../run-failure-report.js"; import { isNativeRunnerOwnershipHeld } from "./native-runner-ownership.js"; import { nativeRestartInterruptedTurnId, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js"; +import { retireSupersededNativeRetry } from "./native-superseded-retry.js"; export type NativeControllerIdentity = { bootId: string; @@ -588,6 +589,9 @@ export async function claimNativeRestartRecoveries(input: { reason: "result_already_persisted", } as const; } + if (!input.liveRunExecutions?.has(row.run.id) && await retireSupersededNativeRetry(tx as unknown as Db, { + run: row.run, coordinator: row.coordinator, issueExecutionRunId: row.issueExecutionRunId, now, + })) return { kind: "blocked", runId: row.run.id, reason: "native_retry_superseded" } as const; if (row.issueExecutionRunId !== row.run.id) { return { kind: "blocked", diff --git a/server/src/services/native-runtime/native-superseded-retry.ts b/server/src/services/native-runtime/native-superseded-retry.ts new file mode 100644 index 00000000000..e98672826b0 --- /dev/null +++ b/server/src/services/native-runtime/native-superseded-retry.ts @@ -0,0 +1,56 @@ +import { and, desc, eq, gt, isNotNull, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; +import { notifyExecutionRunWork } from "../execution-control-notifications.js"; +import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; +import { preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js"; +import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js"; + +export async function retireSupersededNativeRetry(db: Db, input: { + run: typeof heartbeatRuns.$inferSelect; + coordinator: typeof nativeRunFinalizations.$inferSelect; + issueExecutionRunId: string | null; + now: Date; +}): Promise { + const { run, coordinator, now } = input; + if (run.runtimeMode !== "native" || run.status !== "failed" || !run.startedAt || !run.finishedAt + || run.processPid !== null || run.processGroupId !== null + || coordinator.phase !== "retryable_failure" || coordinator.resultId || coordinator.leaseOwner + || coordinator.companyId !== run.companyId || coordinator.issueId !== run.nativeIssueId + || coordinator.runId !== run.id || input.issueExecutionRunId === run.id + || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner || nativeRunHasNoWorkspaceAccess(run)) return false; + const reference = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync); + if (reference?.state !== "prepared") return false; + + const [successor] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.nativeIssueId, coordinator.issueId), + eq(heartbeatRuns.agentId, run.agentId), eq(heartbeatRuns.runtimeMode, "native"), + eq(heartbeatRuns.status, "succeeded"), eq(heartbeatRuns.nativePhase, "committed"), + gt(heartbeatRuns.startedAt, run.finishedAt), isNotNull(heartbeatRuns.finishedAt), + sql`${heartbeatRuns.contextSnapshot}->>'previousRunId' = ${run.id}`, + sql`nullif(${heartbeatRuns.contextSnapshot}->>'taskRetryRequestId', '') is not null`, + )).orderBy(desc(heartbeatRuns.startedAt)).limit(1); + if (!successor) return false; + const [source] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + eq(environmentLeases.id, reference.leaseId), eq(environmentLeases.companyId, run.companyId), + eq(environmentLeases.heartbeatRunId, run.id), eq(environmentLeases.issueId, coordinator.issueId), + eq(environmentLeases.providerLeaseId, reference.providerLeaseId), + sql`${environmentLeases.metadata}->>'remoteCwd' = ${reference.remoteCwd}`, + sql`(${environmentLeases.executionWorkspaceId} is null or ${environmentLeases.executionWorkspaceId}::text = ${reference.workspaceId})`, + )).limit(1); + if (!source) return false; + + await notifyExecutionRunWork(db); + await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", nextAttemptAt: null, + leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: "blocked", + failureCode: "native_retry_superseded", failureDetail: { ...coordinator.failureDetail, + reason: "completed_explicit_retry", successorRunId: successor.id }, updatedAt: now, + }).where(eq(nativeRunFinalizations.runId, run.id)); + const [retired] = await db.update(heartbeatRuns).set({ nativePhase: "terminal_failure", + nativePhaseUpdatedAt: now, updatedAt: now, + }).where(eq(heartbeatRuns.id, run.id)).returning(); + const preserved = await preserveNativeFailedWorkspace(db, retired!); + if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) { + throw new Error("superseded_native_retry_preservation_not_recorded"); + } + return true; +} diff --git a/server/src/services/workspace-recovery.test.ts b/server/src/services/workspace-recovery.test.ts index a0a462e6056..3cb3089b196 100644 --- a/server/src/services/workspace-recovery.test.ts +++ b/server/src/services/workspace-recovery.test.ts @@ -40,6 +40,8 @@ import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { registerWorkspaceRecoveryWork } from "./workspace-recovery-work.js"; import { heartbeatService } from "./heartbeat.js"; import { hasVerifiedWorkspaceRepair, readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; +import { claimNativeSessionResumptions } from "./native-runtime/native-finalization-reconciler.js"; +import { executionWorkspaces } from "@paperclipai/db"; import { getExecutionBlocker } from "./execution-blocker.js"; import { issueRoutes } from "../routes/issues.js"; import { errorHandler } from "../middleware/index.js"; @@ -137,6 +139,42 @@ describe("automatic retained workspace recovery", () => { const action = async (id: string) => (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, id)))[0]!; const run = async (id: string) => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0]!; + it("unblocks a pending workspace selection only after a superseded retry's real files are preserved", async () => { + const f = await seed(); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)); + const source = await run(f.runId); + await db.update(heartbeatRuns).set({ resultJson: null, nativePhase: "retryable_failure", + startedAt: new Date(1), finishedAt: new Date(2) }).where(eq(heartbeatRuns.id, f.runId)); + await db.update(nativeRunFinalizations).set({ phase: "retryable_failure", attempt: 1, + recoveryState: "resuming_session", nextAttemptAt: new Date(0) }).where(eq(nativeRunFinalizations.runId, f.runId)); + await db.update(environmentLeases).set({ status: "active", leasePolicy: "ephemeral", + releasedAt: null, cleanupStatus: null, metadata: f.lease.metadata }).where(eq(environmentLeases.id, f.lease.id)); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: source.agentId, + issueId: f.issueId, nativeIssueId: f.issueId, runtimeMode: "native", status: "succeeded", nativePhase: "committed", + startedAt: new Date(3), finishedAt: new Date(4), contextSnapshot: { previousRunId: f.runId, taskRetryRequestId: randomUUID() } }); + await db.insert(executionWorkspaces).values({ id: f.issueId, companyId: f.companyId, sourceIssueId: f.issueId, + name: "Shared files", mode: "shared_workspace", strategyType: "project_primary", cwd: f.host }); + const actor = { type: "board" as const, source: "local_implicit" as const, isInstanceAdmin: true }; + const workspaces = executionWorkspaceService(db); + await workspaces.selectTaskWorkspace({ companyId: f.companyId, issueId: f.issueId, actor, + selection: { kind: "existing", workspaceId: f.issueId }, expectedBindingRevision: 0, requestKey: randomUUID() }); + const admission = { companyId: f.companyId, issueId: f.issueId, actor, runId: randomUUID() }; + await expect(workspaces.applyPendingTaskWorkspaceSelection(admission)).rejects.toThrow("Previous task run still owns workspace recovery"); + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "recovery", runIds: [f.runId] })).toEqual([]); + await expect(workspaces.applyPendingTaskWorkspaceSelection(admission)).rejects.toThrow("Previous task run still owns workspace recovery"); + const [preservation] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + await recoverRetainedWorkspace({ ...f.input, actionId: preservation.id }); + expect(readSystemRecovery((await action(preservation.id)).evidence)?.state).toBe("complete"); + expect(await readFile(path.join(f.host, "saved.txt"), "utf8")).toBe("finished work\n"); + expect(await readFile(path.join(f.host, "newer.txt"), "utf8")).toBe("newer local work\n"); + expect(await workspaces.applyPendingTaskWorkspaceSelection(admission)).toBe(true); + const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(task).toMatchObject({ status: "blocked", assigneeAgentId: source.agentId, executionWorkspaceId: f.issueId, + workspacePendingSelection: null, executionWorkspaceSettings: { mode: "shared_workspace" } }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.companyId, f.companyId))).toHaveLength(0); + }, 30_000); + it.each(["HTTP Retry", "new comment", "automatic cleanup"] as const)("repairs an unregistered historical deadline failure through %s without admitting work before verified stop", async entry => { const f = await seed("native", true, "keep_running"); const source = await run(f.runId); From 287b04d72f1b9fca1412e05435c75b8302ba0710 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:30:58 -0500 Subject: [PATCH 3/4] fix(evals): keep report dependency proof with lockfile refresh (#18063) https://entire.com/gh/paperclipai/-/trails/192/changes/paperclip/192 ## Thinking Path > - Paperclip manages AI agents and runs paid Product E2E evaluations. > - Paid work needs a report that can install its trusted dependencies. > - The report uses a reviewed offline lock correction. > - New UI dependencies can make that correction stale while its lock hash still matches. > - The lockfile bot must refresh the correction with its lock changes. > - This PR also checks manifest consistency offline before model admission. ## Linked Issues or Issue Description **What happened?** Current master declares new CodeMirror and YAML UI dependencies. Its committed lock omits those UI importer entries. The existing report correction accepts that lock, but a frozen install then fails with `ERR_PNPM_OUTDATED_LOCKFILE`. This can waste completed paid work before the report fails. Refs #18059. That bot PR supplies the matching lock. This PR keeps the root lock bot-owned and supplies its exact offline report correction. The correction changes 21 importer lines and leaves all package records unchanged. **Expected behavior** The existing bot includes matching report proof in its dependency PR. Paid authorization rejects stale manifests before model work. Report installation still accepts only reviewed hashes and applies no registry resolution. **Steps to reproduce** 1. Run a frozen pnpm 9.15.4 install on master at `7f10cc058568e3c1ac133cf24f3b4000cbdfca0e`. 2. Observe the missing UI importer entries. 3. Apply the reviewed correction in this PR. The frozen install passes. ## What Changed - Add an explicit refresh mode that derives the offline patch and hashes from a known committed lock and the bot's resolved lock. - Keep the existing unknown-lock, patch hash and output hash guards. - Include the proof files in the existing lockfile bot PR. New bot PRs use complete descriptions; existing descriptions stay intact. - Validate the frozen lock against current manifests offline before paid admission, using the existing pinned pnpm version. - Refresh the current correction and document this process. The root lockfile is not committed here. ## Verification - 24 focused report-lock and workflow-security tests pass. They cover offline replay, tampered input/patch/output rejection, real Git refresh, unknown-base refusal and unchanged proof. - A full frozen install passes after the reviewed correction, with lifecycle scripts disabled. - A fresh source archive validates offline with an empty package store. - A deliberate manifest change fails that same offline check with `ERR_PNPM_OUTDATED_LOCKFILE`. - Both workflow files parse as YAML. All 95 shell steps pass Bash syntax checks. - `git diff --check` passes. These checks make no model requests. - Full repository checks and fresh reviews must pass on the final PR head before merge. ## Risks - Dependency changes must still pass review. Refresh refuses an unknown committed baseline. - The bot now commits two additional proof files. Its write permissions and target branch stay unchanged. Existing PR descriptions are preserved. - The paid authorization job adds an offline manifest check. It runs no package lifecycle scripts. - No budget, provider credential, environment permission, schedule or paid enable gate changes. ## Model Used - OpenAI Codex, GPT-6, with reasoning and code execution tools. The exact serving variant and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .github/workflows/refresh-lockfile.yml | 59 +- .github/workflows/runner-full-stack-e2e.yml | 12 + tests/runner-e2e/OPERATIONS.md | 12 +- tests/runner-e2e/prepare-report-lock.d.mts | 1 + tests/runner-e2e/prepare-report-lock.mjs | 25 +- tests/runner-e2e/prepare-report-lock.test.ts | 66 +- tests/runner-e2e/report-lock.json | 8 +- tests/runner-e2e/report-lock.patch | 655 ++----------------- tests/runner-e2e/workflow-security.test.ts | 12 +- 9 files changed, 217 insertions(+), 633 deletions(-) diff --git a/.github/workflows/refresh-lockfile.yml b/.github/workflows/refresh-lockfile.yml index ecc0c73ebee..59f47b01531 100644 --- a/.github/workflows/refresh-lockfile.yml +++ b/.github/workflows/refresh-lockfile.yml @@ -39,6 +39,9 @@ jobs: - name: Refresh pnpm lockfile run: pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile + - name: Refresh reviewed eval report dependency proof + run: node tests/runner-e2e/prepare-report-lock.mjs --refresh + - name: Fail on unexpected file changes run: | changed="$(git status --porcelain)" @@ -46,7 +49,8 @@ jobs: echo "Lockfile is already up to date." exit 0 fi - if printf '%s\n' "$changed" | grep -Fvq ' pnpm-lock.yaml'; then + unexpected="$(printf '%s\n' "$changed" | awk '$2 != "pnpm-lock.yaml" && $2 != "tests/runner-e2e/report-lock.json" && $2 != "tests/runner-e2e/report-lock.patch" { print }')" + if [ -n "$unexpected" ]; then echo "Unexpected files changed during lockfile refresh:" echo "$changed" exit 1 @@ -69,7 +73,7 @@ jobs: git config user.email "lockfile-bot@users.noreply.github.com" git checkout -B "$BRANCH" - git add pnpm-lock.yaml + git add pnpm-lock.yaml tests/runner-e2e/report-lock.json tests/runner-e2e/report-lock.patch git commit -m "chore(lockfile): refresh pnpm-lock.yaml" git push --force origin "$BRANCH" @@ -80,10 +84,59 @@ jobs: head -n 1 )" if [ -z "$pr_url" ]; then + pr_body_file="$RUNNER_TEMP/lockfile-pr-body.md" + cat > "$pr_body_file" <<'PR_BODY' + ## Thinking Path + + > - Paperclip uses a dependency lock for reproducible builds. + > - Dependency changes on master need matching lock entries. + > - Paid eval reports also pin a reviewed offline correction. + > - Reports must install before paid model work starts. + > - This automated PR keeps the lock and report proof together. + + ## Linked Issues or Issue Description + + **What happened?** + + Dependency manifests on master changed after the last committed lock refresh. + + **Expected behavior** + + Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. + + **Steps to reproduce** + + Run a frozen install before and after this lock refresh. + + ## What Changed + + - Refresh the dependency lock from the manifests on master. + - Include the matching offline report correction and hashes. + + ## Verification + + - Pinned pnpm resolution completed with lifecycle scripts disabled. + - The report proof refresh accepted the reviewed committed baseline. + - Required PR checks and reviews must pass before merge. + + ## Risks + + Dependency changes require review. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. + + ## Model Used + + None — generated by pnpm and the deterministic report-lock updater. + + ## Checklist + + - [x] Thinking path and problem description included + - [x] Generated lock and matching report proof included + - [ ] Required CI checks and reviews pass + PR_BODY pr_url="$(gh pr create \ --head "$BRANCH" \ --title "chore(lockfile): refresh pnpm-lock.yaml" \ - --body "Auto-generated lockfile refresh after dependencies changed on master. This PR only updates pnpm-lock.yaml.")" + --body-file "$pr_body_file")" echo "Created new PR: $pr_url" else echo "PR already exists: $pr_url" diff --git a/.github/workflows/runner-full-stack-e2e.yml b/.github/workflows/runner-full-stack-e2e.yml index c1a402d1a4c..fcac6ebf260 100644 --- a/.github/workflows/runner-full-stack-e2e.yml +++ b/.github/workflows/runner-full-stack-e2e.yml @@ -196,9 +196,21 @@ jobs: with: node-version: 24 + - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + env: + NPM_CONFIG_AUDIT: "false" + NPM_CONFIG_FUND: "false" + NPM_CONFIG_UPDATE_NOTIFIER: "false" + with: + version: 9.15.4 + run_install: false + - name: Preflight reviewed report dependencies before paid admission run: node tests/runner-e2e/prepare-report-lock.mjs + - name: Validate report dependency manifests offline + run: pnpm install --lockfile-only --frozen-lockfile --ignore-scripts --offline + target_lock: name: Resolve target pnpm lockfile needs: authorize diff --git a/tests/runner-e2e/OPERATIONS.md b/tests/runner-e2e/OPERATIONS.md index e193652ba13..732ef2ca680 100644 --- a/tests/runner-e2e/OPERATIONS.md +++ b/tests/runner-e2e/OPERATIONS.md @@ -976,11 +976,17 @@ install. `report-lock.json` pins the input lock, patch and resulting lock hashes This updates existing patch identities and the already declared yaml dependency without registry resolution. The worker target and its lock artifact never control report dependencies. An already-reviewed output lock is used unchanged. An unknown committed lock fails before install; -update and review this correction when dependency inputs change. The original +review the correction with dependency changes. The existing lockfile-refresh bot runs +`prepare-report-lock.mjs --refresh` and includes the correction and hashes in its +lockfile PR. The PR includes the root lock, which is owned by CODEOWNERS; +the bot requests normal auto-merge and cannot bypass required code-owner review +or checks. It refuses to bless an unrecognized committed lock. Paid authorization +and report jobs still apply only the reviewed offline correction. The original failed run remains failed when retained evidence gets a new presentation. -The trusted authorization job checks this correction before catalog/build and -paid work. Unknown dependency locks fail before model admission. Manual history +The trusted authorization job checks this correction and validates the frozen +lock against current dependency manifests offline before catalog/build and paid +work. This check resolves no packages and runs no lifecycle scripts. Unknown dependency locks fail before model admission. Manual history publication applies the same correction before its frozen install. Qualification image builds apply it only when target and workflow revisions match; a different target keeps its own lock and does not require these reporting helper files. diff --git a/tests/runner-e2e/prepare-report-lock.d.mts b/tests/runner-e2e/prepare-report-lock.d.mts index a6314304c3f..c69a6f0e43a 100644 --- a/tests/runner-e2e/prepare-report-lock.d.mts +++ b/tests/runner-e2e/prepare-report-lock.d.mts @@ -1 +1,2 @@ export function prepareReportLock(root?: string): Promise<'already-reviewed' | 'reviewed-correction'>; +export function refreshReportLock(root?: string): Promise<'unchanged' | 'refreshed'>; diff --git a/tests/runner-e2e/prepare-report-lock.mjs b/tests/runner-e2e/prepare-report-lock.mjs index 587a1428592..2916e1d4b52 100644 --- a/tests/runner-e2e/prepare-report-lock.mjs +++ b/tests/runner-e2e/prepare-report-lock.mjs @@ -26,6 +26,29 @@ export async function prepareReportLock(root = path.resolve(import.meta.dirname, return 'reviewed-correction'; } finally { await rm(temporary, { recursive: true, force: true }); } } +export async function refreshReportLock(root = path.resolve(import.meta.dirname, '../..')) { + const directory = path.join(root, 'tests/runner-e2e'); + const policyPath = path.join(directory, 'report-lock.json'); + const policy = JSON.parse(await readFile(policyPath, 'utf8')); + const committed = execFileSync('git', ['show', 'HEAD:pnpm-lock.yaml'], { cwd: root }); + const inputSha256 = sha256(committed); + if (![policy.inputSha256, policy.outputSha256].includes(inputSha256)) { + throw new Error('Committed report lock is not reviewed; refusing to refresh its proof'); + } + const resolved = await readFile(path.join(root, 'pnpm-lock.yaml')); + if (resolved.equals(committed)) return 'unchanged'; + const patch = execFileSync('git', ['diff', '--no-ext-diff', '--no-textconv', '--no-color', 'HEAD', '--', 'pnpm-lock.yaml'], { cwd: root }); + const changed = execFileSync('git', ['apply', '--numstat', '-'], { cwd: root, input: patch, encoding: 'utf8' }); + if (!/^\d+\s+\d+\s+pnpm-lock\.yaml\n$/.test(changed)) throw new Error('Report correction must change only the lockfile'); + await writeFile(path.join(directory, 'report-lock.patch'), patch); + await writeFile(policyPath, JSON.stringify({ inputSha256, outputSha256: sha256(resolved), patchSha256: sha256(patch), + basis: 'Generated with the trusted master lockfile refresh. Review this offline correction and its hashes with the dependency changes.' }, null, 2) + '\n'); + return 'refreshed'; +} + if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { - console.log(await prepareReportLock()); + const args = process.argv.slice(2); + if (args.length === 0) console.log(await prepareReportLock()); + else if (args.length === 1 && args[0] === '--refresh') console.log(await refreshReportLock()); + else throw new Error('Usage: prepare-report-lock.mjs [--refresh]'); } diff --git a/tests/runner-e2e/prepare-report-lock.test.ts b/tests/runner-e2e/prepare-report-lock.test.ts index a13b064ec48..463a841bf26 100644 --- a/tests/runner-e2e/prepare-report-lock.test.ts +++ b/tests/runner-e2e/prepare-report-lock.test.ts @@ -1,11 +1,11 @@ -import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from 'node:fs/promises'; +import { mkdtemp, mkdir, readFile, writeFile, copyFile, realpath, rm } from 'node:fs/promises'; import { createHash } from 'node:crypto'; import { execFileSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { expect, it } from 'vitest'; import { parse } from 'yaml'; -import { prepareReportLock } from './prepare-report-lock.mjs'; +import { prepareReportLock, refreshReportLock } from './prepare-report-lock.mjs'; it.each(['valid', 'unknown-lock', 'changed-patch', 'wrong-output'])( 'installs only the reviewed dependency correction: %s', async variant => { @@ -37,12 +37,15 @@ it.each(['valid', 'unknown-lock', 'changed-patch', 'wrong-output'])( expect(await prepareReportLock(root)).toBe('reviewed-correction'); expect(createHash('sha256').update(await readFile(lock)).digest('hex')).toBe(policy.outputSha256); expect(await prepareReportLock(root)).toBe('already-reviewed'); - const before = parse(input.toString()).packages; - const after = parse(await readFile(lock, 'utf8')).packages; - expect(Object.keys(after).filter(key => !Object.hasOwn(before, key))).toEqual(['yaml@2.9.1']); - for (const [key, value] of Object.entries(before)) expect(after[key]).toEqual(value); - expect(after['yaml@2.9.1'].resolution.integrity).toBe('sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=='); - + const reviewed = parse(await readFile(lock, 'utf8')); + const ui = JSON.parse(await readFile(path.resolve(here, '../../ui/package.json'), 'utf8')); + for (const [name, specifier] of Object.entries(ui.dependencies)) { + const entry = reviewed.importers.ui.dependencies[name]; + expect(entry.specifier).toBe(specifier); + if (entry.version.startsWith('link:')) continue; + expect(reviewed.packages, name).toHaveProperty(`${name}@${entry.version.split('(')[0]}`); + expect(reviewed.snapshots, name).toHaveProperty(`${name}@${entry.version}`); + } } else { await expect(prepareReportLock(root)).rejects.toThrow(); expect(await readFile(lock)).toEqual(variant === 'unknown-lock' ? Buffer.from('unknown\n') : input); @@ -50,3 +53,50 @@ it.each(['valid', 'unknown-lock', 'changed-patch', 'wrong-output'])( } finally { await rm(root, { recursive: true, force: true }); } }, ); + + +it.each(['input', 'output', 'unknown'])('refreshes dependency proof only from a %s committed lock', async variant => { + const root = await realpath(await mkdtemp(path.join(tmpdir(), 'eval-report-lock-refresh-'))); + const relative = path.join(root, 'tests/runner-e2e'); + const original = "lockfileVersion: '9.0'\nimporters: {}\npackages:\n old@1.0.0: {resolution: {integrity: fixture-old}}\n"; + const resolved = "lockfileVersion: '9.0'\nimporters:\n ui: {}\npackages:\n added@2.0.0: {resolution: {integrity: fixture-new}}\n"; + const hash = (value: string) => createHash('sha256').update(value).digest('hex'); + try { + await mkdir(relative, { recursive: true }); + await writeFile(path.join(root, 'pnpm-lock.yaml'), original); + const initial = { inputSha256: variant === 'input' ? hash(original) : '0'.repeat(64), + outputSha256: variant === 'output' ? hash(original) : '1'.repeat(64), patchSha256: hash('historical') }; + await writeFile(path.join(relative, 'report-lock.json'), JSON.stringify(initial)); + await writeFile(path.join(relative, 'report-lock.patch'), 'historical'); + execFileSync('git', ['init', '-q'], { cwd: root }); + execFileSync('git', ['add', '.'], { cwd: root }); + execFileSync('git', ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture'], { cwd: root }); + await writeFile(path.join(root, 'pnpm-lock.yaml'), resolved); + if (variant === 'unknown') { + await expect(refreshReportLock(root)).rejects.toThrow('not reviewed'); + expect(await readFile(path.join(relative, 'report-lock.patch'), 'utf8')).toBe('historical'); + expect(JSON.parse(await readFile(path.join(relative, 'report-lock.json'), 'utf8'))).toEqual(initial); + expect(await readFile(path.join(root, 'pnpm-lock.yaml'), 'utf8')).toBe(resolved); + return; + } + if (variant === 'output') { + const cli = path.join(relative, 'prepare-report-lock.mjs'); + await copyFile(path.join(import.meta.dirname, 'prepare-report-lock.mjs'), cli); + expect(execFileSync(process.execPath, [cli, '--refresh'], { cwd: root, encoding: 'utf8' }).trim()).toBe('refreshed'); + } else { + expect(await refreshReportLock(root)).toBe('refreshed'); + } + const policy = JSON.parse(await readFile(path.join(relative, 'report-lock.json'), 'utf8')); + const patch = await readFile(path.join(relative, 'report-lock.patch'), 'utf8'); + expect(policy).toMatchObject({ inputSha256: hash(original), outputSha256: hash(resolved), patchSha256: hash(patch) }); + await writeFile(path.join(root, 'pnpm-lock.yaml'), original); + expect(await prepareReportLock(root)).toBe('reviewed-correction'); + expect(await readFile(path.join(root, 'pnpm-lock.yaml'), 'utf8')).toBe(resolved); + expect(parse(await readFile(path.join(root, 'pnpm-lock.yaml'), 'utf8')).packages).toEqual(parse(resolved).packages); + expect(await prepareReportLock(root)).toBe('already-reviewed'); + execFileSync('git', ['add', '.'], { cwd: root }); + execFileSync('git', ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'refresh'], { cwd: root }); + expect(await refreshReportLock(root)).toBe('unchanged'); + expect(await readFile(path.join(relative, 'report-lock.patch'), 'utf8')).toBe(patch); + } finally { await rm(root, { recursive: true, force: true }); } +}); diff --git a/tests/runner-e2e/report-lock.json b/tests/runner-e2e/report-lock.json index 4dd5d2bdeff..0872fa1593a 100644 --- a/tests/runner-e2e/report-lock.json +++ b/tests/runner-e2e/report-lock.json @@ -1,6 +1,6 @@ { - "inputSha256": "893496dddc21c31bd812ea106ac30d1515dda305eb1dd183007d89cf5b1bab4d", - "outputSha256": "c7f23021335b60da0cff1dd4c75cf8b948333ef3165d7d1703eb79a589edb798", - "patchSha256": "c7c11e899c12e6a030fe1554a8ceee5f21689a3a4f19956746e852050049cc49", - "basis": "Reviewed corrections to existing patch hashes and the already declared yaml workspace dependency. Existing package tarball integrity entries are unchanged. The only added package is yaml@2.9.1 with its exact integrity pinned by this reviewed correction." + "inputSha256": "c7f23021335b60da0cff1dd4c75cf8b948333ef3165d7d1703eb79a589edb798", + "outputSha256": "a2606a8218799ac96e841d1f3008053df4f4fca24d5db2941ad10b3d62c0e14a", + "patchSha256": "ee382a42cb5738d85068a4cd1ab5ba42db05f6477936d0c0efa65f182ea70f17", + "basis": "Generated with the trusted master lockfile refresh. Review this offline correction and its hashes with the dependency changes." } diff --git a/tests/runner-e2e/report-lock.patch b/tests/runner-e2e/report-lock.patch index 84a0bcac131..9367b5d3ced 100644 --- a/tests/runner-e2e/report-lock.patch +++ b/tests/runner-e2e/report-lock.patch @@ -1,612 +1,53 @@ +diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml +index 7f3361f73c..b074b7f305 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml -@@ -16,7 +16,7 @@ - - patchedDependencies: - '@agentclientprotocol/claude-agent-acp@0.73.0': -- hash: riqgguivxjxydoydnzpedjy5au -+ hash: xjlrz3rllh2ztafbdiywpfh2rq - path: patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch - '@agentclientprotocol/codex-acp@1.6.2': - hash: 2iynuypg76nxmydiylgtffhr7e -@@ -49,7 +49,7 @@ - hash: 55uhvnotpqyiy37rn3pqpukhei - path: patches/embedded-postgres@18.1.0-beta.16.patch - postgres@3.4.9: -- hash: sryle6qd5qfmnxvoebal4gashi -+ hash: 6q4cic6qawywsyeo2spgnjamda - path: patches/postgres@3.4.9.patch - - importers: -@@ -73,7 +73,10 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) +@@ -1183,6 +1183,18 @@ importers: + '@base-ui/react': + specifier: ^1.7.0 + version: 1.7.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) ++ '@codemirror/lang-yaml': ++ specifier: ^6.1.3 ++ version: 6.1.3 ++ '@codemirror/language': ++ specifier: ^6.12.4 ++ version: 6.12.4 ++ '@codemirror/state': ++ specifier: ^6.7.2 ++ version: 6.7.6 ++ '@codemirror/view': ++ specifier: ^6.43.11 ++ version: 6.43.11 + '@dnd-kit/core': + specifier: ^6.3.1 + version: 6.3.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) +@@ -1195,6 +1207,9 @@ importers: + '@lexical/link': + specifier: 0.48.0 + version: 0.48.0(typescript@7.0.2) ++ '@lezer/highlight': ++ specifier: ^1.2.3 ++ version: 1.2.3 + '@mdxeditor/editor': + specifier: ^4.2.3 + version: 4.2.3(@codemirror/language@6.12.4)(@lezer/highlight@1.2.3)(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(typescript@7.0.2)(yjs@13.6.32) +@@ -1264,6 +1279,9 @@ importers: + cmdk: + specifier: ^1.1.1 + version: 1.1.1(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) ++ codemirror: ++ specifier: ^6.0.2 ++ version: 6.0.2 + i18next: + specifier: ^26.4.2 + version: 26.4.2(typescript@7.0.2) +@@ -1306,6 +1324,9 @@ importers: + tailwind-merge: + specifier: ^3.6.0 + version: 3.6.0 + yaml: + specifier: ^2.8.1 + version: 2.9.1 - - cli: - dependencies: -@@ -133,7 +136,7 @@ - version: 17.4.2 - drizzle-orm: - specifier: 0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -180,7 +183,7 @@ - dependencies: - '@agentclientprotocol/claude-agent-acp': - specifier: ^0.73.0 -- version: 0.73.0(patch_hash=riqgguivxjxydoydnzpedjy5au)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5)) -+ version: 0.73.0(patch_hash=xjlrz3rllh2ztafbdiywpfh2rq)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5)) - '@anthropic-ai/sdk': - specifier: 0.129.0 - version: 0.129.0(zod@4.6.5) -@@ -310,7 +313,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/adapters/hermes-gateway: - dependencies: -@@ -326,7 +329,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/adapters/kimi-local: - dependencies: -@@ -405,13 +408,13 @@ - version: link:../shared - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) - postgres: - specifier: ^3.4.9 -- version: 3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi) -+ version: 3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda) - devDependencies: - '@types/node': - specifier: ^24.0.0 -@@ -427,7 +430,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/google-sheets-mcp-server: - dependencies: -@@ -449,7 +452,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/kv-demo-mcp-server: - dependencies: -@@ -468,7 +471,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/mcp-server: - dependencies: -@@ -490,7 +493,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/paperclip-eval-kernel: - devDependencies: -@@ -505,7 +508,7 @@ - dependencies: - '@agentclientprotocol/claude-agent-acp': - specifier: 0.73.0 -- version: 0.73.0(patch_hash=riqgguivxjxydoydnzpedjy5au)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5)) -+ version: 0.73.0(patch_hash=xjlrz3rllh2ztafbdiywpfh2rq)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5)) - '@agentclientprotocol/codex-acp': - specifier: 1.6.2 - version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) -@@ -561,7 +564,7 @@ - version: 19.2.5(@types/react@19.2.18) - '@vitejs/plugin-react': - specifier: ^4.7.0 -- version: 4.7.0(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)) -+ version: 4.7.0(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1)) - axe-core: - specifier: ^4.12.1 - version: 4.13.0 -@@ -579,10 +582,10 @@ - version: 7.0.2 - vite: - specifier: ^6.1.0 -- version: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15) -+ version: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1) - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/plugins/create-paperclip-plugin: - dependencies: -@@ -629,7 +632,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/plugins/examples/plugin-file-browser-example: - dependencies: -@@ -747,7 +750,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/plugins/plugin-llm-wiki: - devDependencies: -@@ -786,7 +789,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/plugins/plugin-workspace-diff: - dependencies: -@@ -820,7 +823,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/plugins/sdk: - dependencies: -@@ -880,7 +883,7 @@ - version: 7.0.2 - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages/teams-catalog: - devDependencies: -@@ -895,7 +898,7 @@ - version: 0.5.0 - '@agentclientprotocol/claude-agent-acp': - specifier: 0.73.0 -- version: 0.73.0(patch_hash=riqgguivxjxydoydnzpedjy5au)(@anthropic-ai/sdk@0.129.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3)) -+ version: 0.73.0(patch_hash=xjlrz3rllh2ztafbdiywpfh2rq)(@anthropic-ai/sdk@0.129.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3)) - '@agentclientprotocol/codex-acp': - specifier: 1.6.2 - version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) -@@ -1006,7 +1009,7 @@ - version: 2.1.0(@grpc/grpc-js@1.14.5)(nice-grpc-common@2.0.4)(nice-grpc@2.1.17) - '@vercel/connect': - specifier: 2.3.3 -- version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=226jj24akljccsfbw7bcxujz4u)(ai@7.0.130(zod@4.4.3))(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))(ai@7.0.130(zod@4.4.3))(better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)))) -+ version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=226jj24akljccsfbw7bcxujz4u)(ai@7.0.130(zod@4.4.3))(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))(ai@7.0.130(zod@4.4.3))(better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) - acorn: - specifier: 8.18.0 - version: 8.18.0 -@@ -1024,7 +1027,7 @@ - version: 3.0.1(ajv@8.20.0) - better-auth: - specifier: 1.7.2 -- version: 1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))) -+ version: 1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - chat: - specifier: 4.39.0 - version: 4.39.0(ai@7.0.130(zod@4.4.3))(zod@4.4.3) -@@ -1045,7 +1048,7 @@ - version: 17.4.2 - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -1167,10 +1170,10 @@ - version: 7.0.2 - vite: - specifier: ^8.2.2 -- version: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ version: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - ui: - dependencies: -@@ -1321,10 +1324,10 @@ - version: 10.6.0(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8)) - '@storybook/react-vite': - specifier: 10.5.10 -- version: 10.5.10(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(esbuild@0.28.2)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 10.5.10(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(esbuild@0.28.2)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - '@tailwindcss/vite': - specifier: ^4.3.3 -- version: 4.3.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 4.3.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - '@types/node': - specifier: ^24.0.0 - version: 24.13.3 -@@ -1336,7 +1339,7 @@ - version: 19.2.5(@types/react@19.2.18) - '@vitejs/plugin-react': - specifier: ^6.1.1 -- version: 6.1.1(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 6.1.1(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - storybook: - specifier: 10.6.0 - version: 10.6.0(@types/react@19.2.18)(react@19.2.8) -@@ -1348,10 +1351,10 @@ - version: 7.0.2 - vite: - specifier: ^8.2.2 -- version: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ version: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - vitest: - specifier: ^5.0.3 -- version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ version: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - - packages: - -@@ -9256,6 +9259,11 @@ - yallist@4.0.0: - resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} - -+ yaml@2.9.1: -+ resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} -+ engines: {node: '>= 14.6'} -+ hasBin: true -+ - yargs-parser@21.1.1: - resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} - engines: {node: '>=12'} -@@ -9316,7 +9324,7 @@ - - '@adobe/css-tools@4.5.0': {} - -- '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=riqgguivxjxydoydnzpedjy5au)(@anthropic-ai/sdk@0.129.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))': -+ '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=xjlrz3rllh2ztafbdiywpfh2rq)(@anthropic-ai/sdk@0.129.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))': - dependencies: - '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) - '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))(zod@4.4.3) -@@ -9325,7 +9333,7 @@ - - '@anthropic-ai/sdk' - - '@modelcontextprotocol/sdk' - -- '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=riqgguivxjxydoydnzpedjy5au)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5))': -+ '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=xjlrz3rllh2ztafbdiywpfh2rq)(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5))': - dependencies: - '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) - '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.5))(zod@4.4.3) -@@ -9907,12 +9915,12 @@ - optionalDependencies: - '@opentelemetry/api': 1.9.1 - -- '@better-auth/drizzle-adapter@1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))': -+ '@better-auth/drizzle-adapter@1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))': - dependencies: - '@better-auth/core': 1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3) - '@better-auth/utils': 0.4.2 - optionalDependencies: -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)) - - '@better-auth/kysely-adapter@1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(kysely@0.29.5)': - dependencies: -@@ -10974,11 +10982,11 @@ - '@img/sharp-win32-x64@0.35.4': - optional: true - -- '@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -+ '@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - glob: 13.0.6 - react-docgen-typescript: 2.4.0(typescript@7.0.2) -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - optionalDependencies: - typescript: 7.0.2 - -@@ -13184,25 +13192,25 @@ - transitivePeerDependencies: - - '@types/react-dom' - -- '@storybook/builder-vite@10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -- dependencies: -- '@storybook/csf-plugin': 10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ '@storybook/builder-vite@10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': -+ dependencies: -+ '@storybook/csf-plugin': 10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - storybook: 10.6.0(@types/react@19.2.18)(react@19.2.8) - ts-dedent: 2.3.0 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - transitivePeerDependencies: - - esbuild - - rollup - - webpack - -- '@storybook/csf-plugin@10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -+ '@storybook/csf-plugin@10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - storybook: 10.6.0(@types/react@19.2.18)(react@19.2.8) - unplugin: 2.3.11 - optionalDependencies: - esbuild: 0.28.2 - rollup: 4.63.1 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - - '@storybook/global@5.0.0': {} - -@@ -13228,11 +13236,11 @@ - '@types/react': 19.2.18 - '@types/react-dom': 19.2.5(@types/react@19.2.18) - -- '@storybook/react-vite@10.5.10(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(esbuild@0.28.2)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -- dependencies: -- '@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ '@storybook/react-vite@10.5.10(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(esbuild@0.28.2)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': -+ dependencies: -+ '@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@7.0.2)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - '@rollup/pluginutils': 5.4.0(rollup@4.63.1) -- '@storybook/builder-vite': 10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ '@storybook/builder-vite': 10.5.10(esbuild@0.28.2)(rollup@4.63.1)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - '@storybook/react': 10.5.10(@types/react-dom@19.2.5(@types/react@19.2.18))(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(storybook@10.6.0(@types/react@19.2.18)(react@19.2.8))(typescript@7.0.2) - empathic: 2.0.1 - magic-string: 0.30.21 -@@ -13242,7 +13250,7 @@ - resolve: 1.22.12 - storybook: 10.6.0(@types/react@19.2.18)(react@19.2.8) - tsconfig-paths: 4.2.0 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - optionalDependencies: - typescript: 7.0.2 - transitivePeerDependencies: -@@ -13335,12 +13343,12 @@ - postcss-selector-parser: 6.0.10 - tailwindcss: 4.3.3 - -- '@tailwindcss/vite@4.3.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -+ '@tailwindcss/vite@4.3.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - '@tailwindcss/node': 4.3.3 - '@tailwindcss/oxide': 4.3.3 - tailwindcss: 4.3.3 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - - '@tanstack/query-core@5.102.8': {} - -@@ -13758,14 +13766,14 @@ - dependencies: - execa: 5.1.1 - -- '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=226jj24akljccsfbw7bcxujz4u)(ai@7.0.130(zod@4.4.3))(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))(ai@7.0.130(zod@4.4.3))(better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))))': -+ '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=226jj24akljccsfbw7bcxujz4u)(ai@7.0.130(zod@4.4.3))(zod@4.4.3))(@modelcontextprotocol/sdk@1.31.0(zod@4.4.3))(ai@7.0.130(zod@4.4.3))(better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': - dependencies: - '@vercel/oidc': 3.8.9 - optionalDependencies: - '@chat-adapter/slack': 4.39.0(patch_hash=226jj24akljccsfbw7bcxujz4u)(ai@7.0.130(zod@4.4.3))(zod@4.4.3) - '@modelcontextprotocol/sdk': 1.31.0(zod@4.4.3) - ai: 7.0.130(zod@4.4.3) -- better-auth: 1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))) -+ better-auth: 1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - - '@vercel/oidc@3.2.0': {} - -@@ -13775,7 +13783,7 @@ - '@vercel/cli-exec': 1.0.1 - jose: 5.10.0 - -- '@vitejs/plugin-react@4.7.0(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15))': -+ '@vitejs/plugin-react@4.7.0(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) -@@ -13783,14 +13791,14 @@ - '@rolldown/pluginutils': 1.0.0-beta.27 - '@types/babel__core': 7.20.5 - react-refresh: 0.17.0 -- vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15) -+ vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1) - transitivePeerDependencies: - - supports-color - -- '@vitejs/plugin-react@6.1.1(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -+ '@vitejs/plugin-react@6.1.1(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - '@rolldown/pluginutils': 1.0.1 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - - '@vitest/expect@3.2.4': - dependencies: -@@ -13800,23 +13808,23 @@ - chai: 5.3.3 - tinyrainbow: 2.0.0 - -- '@vitest/mocker@5.0.3(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15))': -+ '@vitest/mocker@5.0.3(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.0.3 - estree-walker: 3.0.3 - magic-string: 1.4.3 - optionalDependencies: -- vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15) -- -- '@vitest/mocker@5.0.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))': -+ vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1) -+ -+ '@vitest/mocker@5.0.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.0.3 - estree-walker: 3.0.3 - magic-string: 1.4.3 - optionalDependencies: -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - - '@vitest/pretty-format@3.2.4': - dependencies: -@@ -14042,10 +14050,10 @@ - - before-after-hook@4.0.0: {} - -- better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15))): -+ better-auth@1.7.2(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): - dependencies: - '@better-auth/core': 1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3) -- '@better-auth/drizzle-adapter': 1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi))) -+ '@better-auth/drizzle-adapter': 1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda))) - '@better-auth/kysely-adapter': 1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2)(kysely@0.29.5) - '@better-auth/memory-adapter': 1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2) - '@better-auth/mongo-adapter': 1.7.2(@better-auth/core@1.7.2(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(@opentelemetry/api@1.9.1)(better-call@1.4.0(zod@4.4.3))(jose@6.2.10)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.4.2) -@@ -14063,11 +14071,11 @@ - zod: 4.4.3 - optionalDependencies: - drizzle-kit: 0.31.10 -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)) - pg: 8.18.0 - react: 19.2.8 - react-dom: 19.2.8(react@19.2.8) -- vitest: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ vitest: 5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - transitivePeerDependencies: - - '@cloudflare/workers-types' - - '@opentelemetry/api' -@@ -14654,12 +14662,12 @@ - esbuild: 0.25.12 - tsx: 4.23.15 - -- drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi)): -+ drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda)): - optionalDependencies: - '@opentelemetry/api': 1.9.1 - kysely: 0.29.5 - pg: 8.18.0 -- postgres: 3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi) -+ postgres: 3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda) - - dunder-proto@1.0.1: - dependencies: -@@ -16542,7 +16550,7 @@ - dependencies: - xtend: 4.0.2 - -- postgres@3.4.9(patch_hash=sryle6qd5qfmnxvoebal4gashi): {} -+ postgres@3.4.9(patch_hash=6q4cic6qawywsyeo2spgnjamda): {} - - powershell-utils@0.1.0: {} - -@@ -17587,7 +17595,7 @@ - '@types/unist': 3.0.3 - vfile-message: 4.0.3 - -- vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15): -+ vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1): - dependencies: - esbuild: 0.25.12 - fdir: 6.5.0(picomatch@4.0.7) -@@ -17601,8 +17609,9 @@ - jiti: 2.7.0 - lightningcss: 1.33.0 - tsx: 4.23.15 -- -- vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15): -+ yaml: 2.9.1 -+ -+ vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 -@@ -17615,11 +17624,12 @@ - fsevents: 2.3.3 - jiti: 2.7.0 - tsx: 4.23.15 -- -- vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)): -+ yaml: 2.9.1 -+ -+ vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1)): - dependencies: - '@types/chai': 5.2.3 -- '@vitest/mocker': 5.0.3(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)) -+ '@vitest/mocker': 5.0.3(vite@6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1)) - chai: 6.3.0 - es-module-lexer: 2.3.2 - expect-type: 1.4.0 -@@ -17630,7 +17640,7 @@ - tinybench: 6.2.0 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 -- vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15) -+ vite: 6.4.3(@types/node@24.13.3)(jiti@2.7.0)(lightningcss@1.33.0)(tsx@4.23.15)(yaml@2.9.1) - why-is-node-running: 3.2.1 - optionalDependencies: - '@opentelemetry/api': 1.9.1 -@@ -17639,10 +17649,10 @@ - transitivePeerDependencies: - - msw - -- vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)): -+ vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)): - dependencies: - '@types/chai': 5.2.3 -- '@vitest/mocker': 5.0.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)) -+ '@vitest/mocker': 5.0.3(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) - chai: 6.3.0 - es-module-lexer: 2.3.2 - expect-type: 1.4.0 -@@ -17653,7 +17663,7 @@ - tinybench: 6.2.0 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 -- vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15) -+ vite: 8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) - why-is-node-running: 3.2.1 - optionalDependencies: - '@opentelemetry/api': 1.9.1 -@@ -17748,6 +17758,8 @@ - yallist@3.1.1: {} - - yallist@4.0.0: {} -+ -+ yaml@2.9.1: {} - - yargs-parser@21.1.1: {} - + yjs: + specifier: 13.6.32 + version: 13.6.32 diff --git a/tests/runner-e2e/workflow-security.test.ts b/tests/runner-e2e/workflow-security.test.ts index 698f7e71575..d4a577b9f2c 100644 --- a/tests/runner-e2e/workflow-security.test.ts +++ b/tests/runner-e2e/workflow-security.test.ts @@ -95,9 +95,7 @@ describe("public repository paid workflow security", () => { .split(/\n(?= {6}- )/u) .filter((step) => step.includes("uses: pnpm/action-setup@")); - expect(pnpmSetupSteps, workflowName).toHaveLength( - workflowName === "pr-trusted.yml" ? 8 : 7, - ); + expect(pnpmSetupSteps, workflowName).toHaveLength(8); for (const step of pnpmSetupSteps) { expect(step, workflowName).toContain('NPM_CONFIG_AUDIT: "false"'); expect(step, workflowName).toContain('NPM_CONFIG_FUND: "false"'); @@ -141,9 +139,7 @@ describe("public repository paid workflow security", () => { step.includes("uses: pnpm/action-setup@") ? [index] : [], ); - expect(pnpmSetupStepIndexes, name).toHaveLength( - name === "pr-trusted.yml" ? 8 : 7, - ); + expect(pnpmSetupStepIndexes, name).toHaveLength(8); for (const pnpmSetupStepIndex of pnpmSetupStepIndexes) { const pnpmSetupStep = steps[pnpmSetupStepIndex]!; const nodeBootstrapStep = steps[pnpmSetupStepIndex - 1]!; @@ -282,7 +278,9 @@ describe("public repository paid workflow security", () => { expect(authorizeJob.match(/actions\/checkout@/gu)).toHaveLength(1); expect(authorizeJob).toContain("ref: ${{ github.sha }}"); expect(authorizeJob).not.toContain("ref: ${{ needs.authorize.outputs.target_sha }}"); - expect(authorizeJob).not.toContain("pnpm install"); + expect(authorizeJob.match(/run: pnpm install.*$/gmu)).toEqual([ + "run: pnpm install --lockfile-only --frozen-lockfile --ignore-scripts --offline", + ]); expect(targetLockJob).toContain("name: Resolve target pnpm lockfile"); expect(targetLockJob).toContain("needs: authorize"); expect(targetLockJob).toContain( From 063cfd43813cabf18417605fb9eefb9aacf95c8d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:45:18 -0500 Subject: [PATCH 4/4] fix(server): wake interaction continuations from committed responses (#17653) https://entire.com/gh/paperclipai/-/trails/204/changes/paperclip/204 ## Thinking Path > - Paperclip coordinates agent work and human approvals. > - Human decisions already persist the continuation action that resumes an agent. > - A response can commit before its callback or publication finishes. > - Periodic maintenance repeatedly discovers those rows, including when idle. > - Committed writes should wake the existing owner; saved retries and claims supply real deadlines. > - Startup reconstructs durable work, and settled history becomes quiet. ## Linked Issues or Issue Description Refs #17651, which is merged. This existing continuation slice targets master and removes its duty from periodic chat maintenance. **Problem:** A saved `interaction_wakeup` action can survive a committed human response whose callback crashes. Without producer coverage, removing maintenance strands the continuation. Repeated empty maintenance also keeps the database active. **Expected behavior:** The outer transaction's settlement wakes the continuation owner. It handles ready conversation publications, dispatches under existing authority, preserves interrupted/retry work, and becomes quiet after settlement. ## What Changed - Register continuation recovery with the shared scoped deadline coordinator. Reconstruct existing issued/processing actions and retain the existing retry and stale-claim deadlines. - Notify from both enqueue producers and owner-local claim/settlement writes. Preserve outer commit/rollback and avoid moving provider or heartbeat calls into database transactions. - Give the existing publication queue an optional company/endpoint/conversation scope. The continuation owner gives ready cards in that conversation a bounded delivery opportunity before claiming the action; FIFO, capacity, ambiguity and provider authority remain with the queue. - Carry admission/cancellation through publication preparation and check before every new send. Join in-flight requests and retain pending actions/publications through drain, standby, shutdown and resume. - Remove only recurring continuation recovery; keep the manual API. Add no table. A concurrent partial index on existing pending continuation actions and matching company/id keyset paging prevent retained history from being scanned. Parent #17651's indexed confirmation discovery and current master are retained. ## Verification Published head: `a1d16f84b3fae361d5d648670a5964486370c3a3`, on actual landed terminal-confirmation parent `ee67d2ece9bda157dfad9bdf25175b1d004ed341`. - **75 distinct current cases pass:** 32 selected real PostgreSQL chat cases (14 continuation lifecycle/producer/stop cases, one new continuation query-cost case, and 17 parent confirmation/query-cost cases; 1,671 skipped), and all 43 cases in complete interaction-publication and app/startup suites. Database build, server typecheck/build, module boundaries and fresh migrations through 0399 pass. The original landed-parent matrix passed 74 cases before the additional query-cost repair; those are not added again. - The new real-SQL regression seeds 20,000 completed/unrelated actions and one pending processing claim. Before repair it examines 20,345 rows and hits 20,421 buffers. The final startup and company-scoped queries must examine at most two action rows and fewer than 20 action buffers; empty scoped recovery must also stay below 20 buffers. Planner settings are unchanged. Migration `0399_ambitious_onslaught.sql` is concurrent/idempotent and uses the existing top-level migration runner; prior SQL/journal entries and the five newest snapshots are preserved. - The matrix covers callback recovery, concurrent responses, malformed prefixes, more than one page, saved retries/stale claims, outer rollback/commit, deferred/future/paused publication states, restart, drain and stop before each new provider request. Quiet assertions inspect real selects/transactions across virtual idle time. - Normal integration `db5a84c0f8b73a0ce863f4d2fbaee0a115cf044f` preserves the complete 12-path owned binary patch and all 12 unrelated current-master paths, including managed Cloud sandbox changes. A verified semantic base resolves squash-ancestry conflicts; both normal parents and the exact tree are checked. The subsequent index/keyset repair is a deliberate additional change, tested separately; the final patch is not claimed identical to the original 12-file implementation. No force push or rebase occurs. - The same 74 pre-index cases passed on the earlier prepared and actual landed parents. The new query-cost regression failed before its repair, then passes on the repaired source. Earlier 57-case and broad acceptance retain their original revision scopes; repeated cases are not added to the current count. The audit-only follow-up leaves all owned server source/test hashes unchanged. - [The owner audit](https://github.com/paperclipai/paperclip/blob/a1d16f84b3fae361d5d648670a5964486370c3a3/doc/plans/2026-10-25-interaction-continuation-sleep-audit.md#acceptance-on-the-actual-landed-terminal-confirmation-parent) retains the original missing-signal regression, the skipped standalone publication suite, and the review's stop-before-send failures with their corrections. Skips and earlier failing revisions are not relabelled as current passes. - **Fresh exact-head CI and Greptile 5/5 without unresolved actionable findings remain required.** The former remote head's reviews are stale. No full local repository suite, live provider or deployed sleep result is claimed. ## Risks - Process-local transaction hints cover supported application writers and shared pools. Independent SQL writers and other replicas do not gain a new wake guarantee. - The publication queue's existing FIFO, capacity, retry/ambiguity and authorization contracts still govern effects. In-flight provider requests can settle after Stop; the fence prevents a subsequent request from starting. - Missing a supported producer can defer recovery until another change or startup. Producer and rollback tests cover this slice's supported paths. - Worker quiet is separate from host/database suspension. External alarm coverage and Cloud sleep gates are unchanged. ## Model Used OpenAI Codex, using repository inspection, code execution and real PostgreSQL tests. The exact model identifier and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- ...2026-10-24-recurring-server-sleep-stack.md | 30 ++ ...25-interaction-continuation-sleep-audit.md | 255 +++++++++++++ packages/db/src/client.ts | 1 + .../migrations/0399_ambitious_onslaught.sql | 1 + ...{0394_snapshot.json => 0399_snapshot.json} | 132 ++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/chat_channels.ts | 3 + .../app-private-hostname-gate.test.ts | 1 + .../chat-channels.integration.test.ts | 343 ++++++++++++++++++ server/src/app.ts | 1 + server/src/services/chat-channels.ts | 5 +- .../interactions/confirmation-actions.ts | 2 + .../interactions/continuations.ts | 95 ++++- .../chat-channels/publications/queue.ts | 26 +- .../chat-continuation-notifications.ts | 8 + .../services/chat-interaction-publications.ts | 94 ++--- .../services/delivery-work-notifications.ts | 1 + 17 files changed, 936 insertions(+), 69 deletions(-) create mode 100644 doc/plans/2026-10-25-interaction-continuation-sleep-audit.md create mode 100644 packages/db/src/migrations/0399_ambitious_onslaught.sql rename packages/db/src/migrations/meta/{0394_snapshot.json => 0399_snapshot.json} (99%) create mode 100644 server/src/services/chat-continuation-notifications.ts diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index 286442d4b15..940f9cac89d 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -2296,3 +2296,33 @@ owed cron occurrence; fixing that fixture clock passes all 28 plugin tests. Thirteen selected chat lifecycle cases pass after the retry-notice wait fix. Initial Greptile is 5/5 without findings. Fresh full acceptance and corrected-head remote gates remain required; see the slice-32 audit for all retained failures. + +## Slice 32 accepted-head verification and slice 33 start + +At `8b43e6222706491f2d8044af3bf86358085069af`, #17651 passes all +53 remote checks and fresh Greptile 5/5, with no review threads. The corrected +full chat/startup run passed all 1,512 tests on a fresh database in 463.63 seconds; +final server typecheck also passed. Prior failed runs remain documented above. +The PR remains unmerged. Latest fetched master is `67aa87a93b`; final stack +reconciliation and older unresolved gates/reviews remain outstanding. + +Slice 33 starts from that accepted head and owns interaction continuation +recovery only. The owner audit is in +`2026-10-25-interaction-continuation-sleep-audit.md`. GitHub history maintenance +and host-sleep eligibility remain separate work. + +Slice 33 now implements interaction continuation recovery with committed action +signals, saved retry/claim deadlines, and a scoped call into the existing +publication dispatcher before claiming continuation work. It preserves paused +and future-retry publication behavior. Eleven new real-database cases pass, +including outer rollback/commit, historical prefixes, and concurrent response +commit. Existing Telegram acceptance also passes. Broad acceptance and fresh +PR gates remain pending; no merge or full-stack completion is claimed. + +Slice 33 is [#17653](https://github.com/paperclipai/paperclip/pull/17653), draft +and unmerged. Initial broad acceptance passed 1,523 tests with 14 skipped; +workspace types/build passed. Review found that publication preparation could +start another send after drain/standby/shutdown. Three regressions reproduced +it. Per-send admission/abort checks now pass all 14 new lifecycle cases, and the +previously skipped publication suite plus startup guards pass 27 cases with the +external test database. Fresh corrected-head verification remains required. diff --git a/doc/plans/2026-10-25-interaction-continuation-sleep-audit.md b/doc/plans/2026-10-25-interaction-continuation-sleep-audit.md new file mode 100644 index 00000000000..439ff4a347d --- /dev/null +++ b/doc/plans/2026-10-25-interaction-continuation-sleep-audit.md @@ -0,0 +1,255 @@ +# Interaction continuation delivery migration + +Date: 2026-10-25. Inspected parent implementation at aeaaed7b3e17e1377433165a38fef558acacb631 (#17651). This is an owner audit, not an implemented migration. + +## Obligation + +`chat-channels/interactions/continuations.ts` owns durable `chat_actions.kind = interaction_wakeup` delivery. The existing row already stores issue, interaction, assignee, actor provenance, source comment/run, and optional plan-review context. No table is needed. + +Current selector: issued with null result is due now; issued with result is due at updatedAt + CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS (currently 30,000ms); processing is reclaimable at updatedAt + 30,000ms. Claim repeats the predicate. A valid result marks processed; invalid payload marks failed; invalid current issue/interaction/assignee marks processed with an explicit no-longer-applicable code. A refused wake returns issued/deferred. Exceptions return issued/failed with an incremented attemptCount. Existing acceptance deliberately retries beyond five failures; do not silently cap/discard it. + +The owner coalesces against an existing non-failed/non-cancelled/non-skipped `agent_wakeup_requests` row with interaction-specific idempotency. A different current durable agent recipient is accounted for as reassignment coalescing. It retains actor provenance, inbound comment lineage, forced fresh-session plan context, and source run/comment. These are not scheduler responsibilities. + +## Actual producers + +1. `enqueueTerminalIssueInteractionChatPublications` in `chat-interaction-publications.ts` creates issued actions. It is used inside interaction resolution transactions, native review retirement transactions, and callback race handling. The helper inserts continuation state before it iterates terminal publication inserts. Audit every caller's transaction ownership; do not emit a root post-write hint and assume those writes are atomic. +2. `createTelegramConfirmationActions(...).settleTerminalConfirmationAction` inserts the same issued action in its settlement transaction. Its interaction-resolution publication insert is in that transaction too. It can lose insert ownership to the generic producer; onConflictDoNothing is intentional. +3. The continuation worker's claims, deferrals, failures and completion mutate scheduling state. Explicit/manual recovery may run beside the registered worker. Preserve CAS and stale-claim deadlines across those paths and transaction failure. + +Search found no other non-test insertion of interaction_wakeup. Native question answers have a separate question-delivery owner and the generic producer explicitly excludes answered ask_user_questions. + +## Existing invocation and ordering + +`processPublicationMaintenance` still calls `processPendingInteractionWakeups` after scheduling GitHub maintenance. The explicit publication queue calls it only when maintenance=true, after awaiting all publication tasks owned by that invocation. Production publication scheduling uses maintenance=false. Remove only the periodic continuation call; preserve the explicit/manual contract. + +Do not merely start an independent action worker on insert: a continuation can become visible in the same commit as a still-pending resolution card. Existing Telegram acceptance asserts the provider card edit happens before the continuation wake. The current periodic path is not itself proof that this ordering is robust. Establish an explicit owner predicate/receipt for owed publication delivery, together with its terminal, cancelled, ambiguous, retry, removed-binding and no-publication cases. Waiting on publication completion must use its committed changes rather than repeatedly poll it. The owner must allow continuation when the prompt was never externally visible and no resolution publication is owed. Avoid turning permanent publication failure into indefinite loss of the user's accepted decision. + +The shared `notifyChatPublicationWork(tx, optionalIssueScope)` already signals delivery changes, and terminal publication transitions often supply the issue scope. Audit all release/resolution writers before depending on that fanout. `onPublicationsSettled` currently stores only one callback used by publication refill; do not overwrite it with another consumer. + +## Mechanism and verification still to choose + +Reuse the shared coordinator/scheduler. Keep action eligibility, publication sequencing and dispatch in the continuation owner; app startup only registers it. Scope committed hints by issue/company (or exact action when useful), restore existing issued/processing debt at startup, retain work during drain and changes during a sweep, and register actual existing claim/retry deadlines. Do not scan completed history periodically. + +Tests should use the real accept/reject/board producers and preserve existing provider edit-before-wake, duplicate durable request, reassignment coalescing, deferred delivery, repeated failures and plan/source provenance assertions. Add idle first-write, no recurring SQL after settlement, rollback/outer commit, restart, failed attempt retry, paused/drain resume, bounded progress, and changed publication state wake coverage. Inspect current code again before implementation. + +## Independent scopes + +GitHub history maintenance remains another PR. Host sleep proof currently fails closed on any retained chat action/publication/delivery rows; this worker migration does not relax that gate or claim external Cloud alarm coverage. All earlier stack findings and final-master checks remain required. + +## Ordering refinement from the current queue + +The explicit publication queue only attempts eligible, due work, then wakes continuations. A retry with a future deadline, paused/attention endpoint, explicit-publication endpoint, or unrelated FIFO blocker can be skipped. Therefore requiring every resolution publication to become `published` would strengthen the old behavior into an indefinite agent-wake dependency and could lose useful functionality. Preserve the opportunity for ready resolution publication before the wake while leaving provider retry and ambiguous-delivery recovery with the publication owner. + +A concrete option to evaluate is a narrowly scoped queue drain for the continuation's issue/interaction before claiming its action. Reuse the queue's eligibility, FIFO, endpoint slots and waitForCompletion contract; do not call provider transport directly or start a second dispatcher. Keep the drain bounded and scoped so an unrelated failing provider cannot block all interaction wakes. Do it before the 30-second action claim so a slow provider attempt does not expire a newly acquired action claim. The generic and Telegram continuation producers must signal before their writes inside existing transactions. Inspect all caller transaction ownership and prove the real callback path before removing maintenance. + +## Slice 33 implementation + +Implemented on parent `8b43e6222706491f2d8044af3bf86358085069af`. +The owner now registers a scoped deadline worker. It restores issued/processing +rows in 100-row UUID pages, attempts up to 25 entries per sweep with company +rotation, and schedules existing retry and stale-claim deadlines. Completed +history has no recurring deadline. Total startup inventory and memory still grow +with unfinished actions; page size bounds individual reads, not total inventory. + +Both enqueue producers register intent before inserting. The generic producer +uses a nested transaction around its action insert, preserving caller-owned +outer commit and also supporting its existing root-client contract. All 20 +production call sites of the generic helper pass a transaction. Telegram +settlement already owns a transaction. The continuation owner uses one local +transaction helper for claim, failure, deferral, and settlement writes, with an +exact action hint. Provider publication and heartbeat dispatch stay outside +these transactions. Signals add opted-in transaction/XID work; they are not free +or a cross-process notification mechanism. + +The publication queue gained an optional company/endpoint/conversation scope. +Its existing eligibility, FIFO, credential fencing, endpoint concurrency and +ambiguity quarantine remain authoritative. Registered continuation recovery +attempts up to 25 ready publications in the originating conversation before +claiming the action. It waits for that endpoint's existing task when necessary, +without joining unrelated endpoint work merely because the scoped queue is +empty. Shared endpoint capacity can still require waiting for a slot. This is +not a guarantee that every card in an arbitrary backlog becomes published before +wake. Paused/attention, future retry, explicit mode, and FIFO-blocked publications +retain the old queue semantics and do not indefinitely block continuation. +The explicit/manual publication-maintenance contract remains unchanged. Only +the recurring continuation invocation was removed. + +The continuation worker rechecks drain/cancellation after publication preparation +before taking a new action claim. Interrupted dispatch and provider ambiguity +remain governed by existing claims, idempotency, and publication recovery. No +new table, expiry policy, attempt cap, or host-sleep exemption was added. + +## Verification evidence + +- `/tmp/sleep33-missing-signal.log`: the real callback commits its response and + then hits the existing injected settlement crash. Before enqueue notifications + are added, the durable continuation remains issued instead of processed. +- `/tmp/sleep33-signaled.log`: the new regression plus existing comprehensive + Telegram acceptance pass (2 cases). Existing acceptance includes card edit + before continuation, duplicate callbacks, board attribution, durable wake + coalescing, deferral, and more than five failures. +- `/tmp/sleep33-lifecycle.log`: 65 selected integration cases pass, including + seven new lifecycle modes. The two other named suites were filtered out by + the test-name selection and are not claimed as run. +- `/tmp/sleep33-transactions.log`: 10 new cases pass: accept/reject, drain, + restart, dispatch deferral/failure, paused endpoint, future publication retry, + stale processing claim, and outer transaction rollback/commit. Idle assertions + advance 120 seconds with no root selects or transactions. Server typecheck + passed before this command. +- `/tmp/sleep33-concurrent.log`: 101 malformed issued actions are explicitly + failed; valid continuation work progresses. A second real callback commits + while the first dispatch is blocked; both continuations settle and become + quiet. This is one additional case. + +Full acceptance, workspace typecheck/build, and remote review/checks are still +required. These local results do not prove actual hosting or database suspension. + +## Review correction: stop before each publication + +At implementation head `6d01f4c730`, workspace typecheck/build passed. Full chat +and startup acceptance passed 1,523 tests in 465.91 seconds, but the 14 standalone +publication tests skipped because their suite supported only embedded PostgreSQL. +This is not evidence those 14 tests passed. The suite now accepts an explicitly +named disposable `_test` external database and closes its own client afterward. + +Greptile review was 4/5 and found a valid stop-boundary gap: the continuation +checked cancellation/admission after preparing publications, but that preparation +could start another send after drain, standby, or shutdown began. The three new +real-queue regressions each reproduced the second publication becoming published +when it should remain pending (`/tmp/sleep33-stop-before.log`). They hold the +first provider edit in flight, change the lifecycle state, and release the edit. + +The existing queue now accepts an optional `canContinue` callback. The +continuation owner passes its current admission/abort check through preparation. +The queue checks before entry, each batch, each reservation, and each newly +started send. Already-started work is joined and settled. Deferred actions and +publications survive resume/restart. Default callers retain their current +behavior, with shutdown also checked before invoking a reserved send. + +All 14 new continuation cases pass after this correction +(`/tmp/sleep33-stop-fixed.log`). The previously skipped publication suite and +startup guards pass separately, 27 cases total +(`/tmp/sleep33-publication-startup.log`). Fresh broad acceptance and remote gates +on the corrected head remain required. No failed run has been relabelled passing. + + +## Current prepared integration — October 28 + +The existing 12-path slice is normally merged onto prepared confirmation parent +`9e9fff2be989d8447eb34a7fcba78076a26bdd27` at +`22530681c6a4a3d11ea14356d751cecf45035ba8`. The complete original edits and context +are identical after excluding only blob index hashes/hunk offsets. The proof is +`/tmp/sleep33-current-parent-composition-proof.json`. No new implementation is +added during this preparation; its predecessors carry current master and the +notice discovery/restoration repairs. + +**57 distinct cases pass:** all 14 selected real continuation lifecycle, +concurrent-response, outer-commit and stop-before-publication cases (1,687 other +chat cases skipped), plus 43 across the complete interaction-publication and +app/startup suites. These run after server typechecking/build and module boundary +checks, which also pass. Two isolated PostgreSQL fixtures keep the chat lifecycle +and publication consumers independent; the publication owner applies its own +migrations. Commands, fixtures and tested revision are in +`/tmp/sleep33-current-acceptance-command.json`; logs/exit receipts are +`/tmp/sleep33-current-{types,build,boundaries,continuations,consumers}.*`. + +The older 14-case publication count and broad acceptance above retain their +original revisions. The current complete publication/startup group has 43 cases; +none are skipped. This preparation is local and unpublished, with both preceding +PRs still required to land before final integration and fresh exact-head checks. +No full local repository, live-provider or physical sleep claim is made. + + +### Local acceptance on the indexed terminal-confirmation parent + +Normal merge `71ec3c00d15cd8081514f0d2eb99d5a1728425b1` adopts published terminal +confirmation parent `a35e78d076c1b618bc643391b7520fa6952fc996`, including its +concurrent partial index, company/id keyset discovery and current master +`644937c93150c423f12674992c7ea1e8b5dbc98c`. Both complete sets of added/removed +patch edits are preserved, excluding only blob hashes and hunk line metadata. +The two shared files (chat integration tests and confirmation actions) merge +normally; every unrelated parent blob is retained. Proof: +`/tmp/sleep33-indexed-parent-composition-proof.json`. + +**74 distinct cases pass on this combined source:** 31 selected chat cases +(14 continuation lifecycle/stop/retry/outer-commit cases plus 17 parent +confirmation lifecycle/query-cost cases; 1,671 skipped), and all 43 cases across +complete interaction-publication and app/startup suites. Server typechecking, +build and module boundaries pass. Fresh isolated PostgreSQL databases use the +parent's complete migration history through 0398. Its five newest snapshots +remain 0394–0398, with no schema changes from this slice. + +Commands, actual fixtures and tested revision: +`/tmp/sleep33-indexed-parent-acceptance-command.json`. Logs/exit receipts: +`/tmp/sleep33-indexed-parent-{types,build,boundaries,migrate,lifecycle,consumers}.*`. +The previous 57-case matrix retains its original revision scope; repeated cases +are not added to the current total. The following audit-only commit leaves all +owned product/test sources unchanged. + +This is local preparation. Terminal confirmations #17651 must actually merge +before this slice is reconciled with its landed squash parent and published. +The existing remote head's review is not a review of this integration. Fresh +exact-head CI and Greptile 5/5 without actionable findings remain required. +No full local repository suite, live provider or physical suspension result is +inferred from this acceptance. + + +### Acceptance on the actual landed terminal-confirmation parent + +Terminal confirmations #17651 landed at +`ee67d2ece9bda157dfad9bdf25175b1d004ed341`. Normal integration +`db5a84c0f8b73a0ce863f4d2fbaee0a115cf044f` preserves the complete original +12-path continuation patch and all 12 unrelated master paths, including managed +Cloud sandbox selection changes. Historical squash-ancestry conflicts are +resolved against the verified semantic parent `a35e78d076c1b618bc643391b7520fa6952fc996`; +both normal merge parents and the exact composition tree are checked. Proof: +`/tmp/sleep33-landed-parent-publication-proof.json`. All 74 original selected +cases pass again on that actual-parent integration, with fresh PostgreSQL, +database build, server typechecking/build and module boundaries. + +Before publication, inspection found the same retained-history scan that the +parent's review exposed in confirmation recovery. This owner also filtered +`chat_actions` without a matching work index. The new actual-SQL regression +fails at **20,345 examined rows and 20,421 shared buffers** for one pending claim, +with 20,000 completed/unrelated actions present. This red result is retained in +`/tmp/sleep33-cost-red.log` and its nonzero exit receipt. + +Repair `a4a207ff23116c3fb739ad614c4c254992b1cdac` adds the generated +`0399_ambitious_onslaught.sql` partial index on `(company_id, id)` for +`interaction_wakeup` actions in `issued`/`processing` state. It is concurrent +and idempotent, using the existing top-level migration runner. Keyset ordering +and its composite cursor match that index; fixed predicates remain SQL literals +for prepared-plan eligibility. This changes neither claim/retry deadlines nor +continuation/publication authority. It adds no table, timer or scheduler. +This is a deliberate additional repair after the original 12-path preservation +proof, not a claim that the final patch is unchanged from the old implementation. + +The regression captures the owner's real startup and company-scoped SQL, replays +it unchanged under `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`, and requires the +correct pending ID with at most two action rows examined and fewer than 20 action +buffers. Empty scoped recovery must also touch fewer than 20 buffers. No planner +setting forces the index. A future processing claim prevents the test from +consuming the pending row; the coordinator is stopped before checking empty +recovery. The test vacuums/analyzes its owned table so dead tuples from previous +cases do not masquerade as retained-history cost. The narrow green result is +`/tmp/sleep33-cost-green.log`. + +**75 distinct final cases pass:** 32 chat cases (14 continuation lifecycle, +concurrency, malformed backlog, outer commit and stop cases; the new cost case; +and 17 parent confirmation/query-cost cases), with 1,671 skipped; plus all 43 +cases across complete publication and startup suites. Database build, server +typecheck/build, module boundaries and fresh migration through 0399 pass. The +398-to-399 upgrade and target-branch migration-order gate also pass. All prior +SQL/journal entries and retained snapshot bytes are preserved. Generation prunes +0394 and retains the five newest snapshots, 0395–0399. + +Actual commands and fixtures: +`/tmp/sleep33-cost-final-acceptance-command.json`. Logs/receipts: +`/tmp/sleep33-cost-final-{db-build,types,build,boundaries,migrate,lifecycle,consumers}.*`, +`/tmp/sleep33-cost-upgrade.*`, and `/tmp/sleep33-cost-migration-order.*`. +Earlier 57/74-case runs retain their revision scopes; repeated cases are not +added to 75. Original missing-signal, skipped-publication and stop-before-send +failures above remain recorded. The audit-only follow-up leaves the final owned +source/test/migration hashes unchanged. Fresh exact-head CI and Greptile 5/5 +with no actionable findings remain required before merge. These tests establish +owner recovery/quiet and bounded reads, not deployed physical suspension. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 318c9f09317..22b07ed7279 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -550,6 +550,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0396_tan_paladin.sql", "0397_known_madrox.sql", "0398_yielding_random.sql", + "0399_ambitious_onslaught.sql", "0384_funny_adam_warlock.sql", diff --git a/packages/db/src/migrations/0399_ambitious_onslaught.sql b/packages/db/src/migrations/0399_ambitious_onslaught.sql new file mode 100644 index 00000000000..21bcfb687ad --- /dev/null +++ b/packages/db/src/migrations/0399_ambitious_onslaught.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_continuation_work_idx" ON "chat_actions" USING btree ("company_id","id") WHERE "chat_actions"."kind" = 'interaction_wakeup' AND "chat_actions"."status" IN ('issued', 'processing'); diff --git a/packages/db/src/migrations/meta/0394_snapshot.json b/packages/db/src/migrations/meta/0399_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0394_snapshot.json rename to packages/db/src/migrations/meta/0399_snapshot.json index 2f97a908044..05df360fe1f 100644 --- a/packages/db/src/migrations/meta/0394_snapshot.json +++ b/packages/db/src/migrations/meta/0399_snapshot.json @@ -1,6 +1,6 @@ { - "id": "633afb6b-4b89-44ea-81d5-a477a3696eb5", - "prevId": "e1ddc6f7-6335-4b3d-aeec-a5df27793874", + "id": "9ca01952-f1fa-4c54-a189-3f5a3a3a3761", + "prevId": "7f056258-4b1a-4828-b950-33f070fc0c47", "version": "7", "dialect": "postgresql", "tables": { @@ -1350,6 +1350,34 @@ "concurrently": false, "method": "btree", "with": {} + }, + "activity_log_company_user_issue_actor_idx": { + "name": "activity_log_company_user_issue_actor_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"activity_log\".\"actor_type\" = 'user' AND \"activity_log\".\"entity_type\" = 'issue'", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -9596,6 +9624,50 @@ } }, "indexes": { + "chat_actions_continuation_work_idx": { + "name": "chat_actions_continuation_work_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"kind\" = 'interaction_wakeup' AND \"chat_actions\".\"status\" IN ('issued', 'processing')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_actions_confirmation_recovery_idx": { + "name": "chat_actions_confirmation_recovery_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"kind\" = 'confirmation_response' AND \"chat_actions\".\"status\" = 'processing'", + "concurrently": false, + "method": "btree", + "with": {} + }, "chat_actions_provider_action_uq": { "name": "chat_actions_provider_action_uq", "columns": [ @@ -14160,6 +14232,24 @@ "primaryKey": false, "notNull": false }, + "provider_account_id": { + "name": "provider_account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cleanup_confirmed_at": { + "name": "cleanup_confirmed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cleanup_next_attempt_at": { + "name": "cleanup_next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "expires_at": { "name": "expires_at", "type": "timestamp with time zone", @@ -14182,6 +14272,22 @@ } }, "indexes": { + "chat_voice_inbound_cleanup_idx": { + "name": "chat_voice_inbound_cleanup_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_voice_inbound_calls\".\"cleanup_confirmed_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + }, "chat_voice_inbound_expiry_idx": { "name": "chat_voice_inbound_expiry_idx", "columns": [ @@ -14934,6 +15040,28 @@ "concurrently": false, "method": "btree", "with": {} + }, + "chat_voice_sessions_report_window_idx": { + "name": "chat_voice_sessions_report_window_idx", + "columns": [ + { + "expression": "ended_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_voice_sessions\".\"state\" in ('ended', 'failed', 'expired') and \"chat_voice_sessions\".\"provider_session_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} } }, "foreignKeys": { diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index b9355079da4..62fad4474c4 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2780,6 +2780,13 @@ "when": 1793216165150, "tag": "0398_yielding_random", "breakpoints": true + }, + { + "idx": 399, + "version": "7", + "when": 1793218102114, + "tag": "0399_ambitious_onslaught", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/chat_channels.ts b/packages/db/src/schema/chat_channels.ts index b6aeb4c9efd..1bb91f2603c 100644 --- a/packages/db/src/schema/chat_channels.ts +++ b/packages/db/src/schema/chat_channels.ts @@ -673,6 +673,9 @@ export const chatActions = pgTable( .defaultNow(), }, (table) => [ + index("chat_actions_continuation_work_idx") + .on(table.companyId, table.id) + .where(sql`${table.kind} = 'interaction_wakeup' AND ${table.status} IN ('issued', 'processing')`), index("chat_actions_confirmation_recovery_idx") .on(table.companyId, table.id) .where(sql`${table.kind} = 'confirmation_response' AND ${table.status} = 'processing'`), diff --git a/server/src/__tests__/app-private-hostname-gate.test.ts b/server/src/__tests__/app-private-hostname-gate.test.ts index 629bd1139f6..7123ae6c78e 100644 --- a/server/src/__tests__/app-private-hostname-gate.test.ts +++ b/server/src/__tests__/app-private-hostname-gate.test.ts @@ -93,6 +93,7 @@ describe("createChatReconciliationCoordinator", () => { expect(publicationMaintenance).not.toContain("await enqueueInboundWakeupPublications("); expect(publicationMaintenance).not.toContain("await enqueueFailedChatRetryPublications("); expect(publicationMaintenance).not.toContain("reconcileTerminalConfirmationActions("); + expect(source).toContain("chatChannels.registerInteractionContinuationWork(deliveryWork,"); expect(source).toContain("chatChannels.registerTerminalConfirmationWork(deliveryWork,"); expect(source).toContain("chatFailedRetryNoticeWork(chatChannels).register(deliveryWork,"); }); diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index c0f6c6494fb..b84bda2b3b5 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -45693,6 +45693,349 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { return { fixture, callbacks, onAction: callbacks.onAction, endpoint, service, wakeup, settlementBarrier, dm, conversation, linkedUserId, principal, interaction, publication, acceptAction, actionEvent }; } + it("bounds interaction continuation recovery reads with completed history", async () => { + const context = await telegramConfirmationRecoveryFixture(); + await expect(context.onAction(context.actionEvent)) + .rejects.toThrow("injected post-interaction confirmation settlement crash"); + const [action] = await db.select().from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + )); + expect(action).toBeDefined(); + await db.update(chatActions).set({ status: "processing", updatedAt: new Date() }).where(eq(chatActions.id, action.id)); + const prefix = `continuation-plan:${randomUUID()}:`; + await db.execute(sql` + INSERT INTO chat_actions (company_id, endpoint_id, kind, provider_action_id, status) + SELECT ${context.fixture.companyId}::uuid, ${context.endpoint.id}::uuid, + CASE WHEN n <= 10000 THEN 'interaction_wakeup' ELSE 'unrelated_action' END, + ${prefix} || n, + CASE WHEN n <= 10000 THEN 'processed' ELSE 'processing' END + FROM generate_series(1, 20000) AS n + `); + await db.execute(sql`VACUUM (ANALYZE) chat_actions`); + const statements: { sql: string; params: unknown[] }[] = []; + const select = db.select.bind(db); + const reads = vi.spyOn(db, "select").mockImplementation((...args) => { + const selection = select(...args), from = selection.from.bind(selection); + vi.spyOn(selection, "from").mockImplementation(table => { + const query = from(table); + if (table === chatActions) { + const execute = query.execute.bind(query); + vi.spyOn(query, "execute").mockImplementation(async () => { + const statement = query.toSQL(); + if (statement.params.includes("interaction_wakeup") || statement.sql.includes("'interaction_wakeup'")) { + statements.push(statement); + } + return execute(); + }); + } + return query; + }); + return selection; + }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + canReconcile: () => true, onError: error => errors.push(error) }); + try { + await context.service.registerInteractionContinuationWork(coordinator, () => true).ready; + expect(statements.length).toBeGreaterThan(0); + const startup = statements[0], beforeHint = statements.length; + await db.transaction(async tx => { + await signalDatabaseWork(tx, DELIVERY_QUEUES.chatInteractionContinuations, + JSON.stringify({ companyId: context.fixture.companyId })); + }); + await vi.waitFor(() => expect(statements.length).toBeGreaterThan(beforeHint), { timeout: 5_000 }); + const scoped = statements.at(-1)!; + expect(scoped.params).toContain(context.fixture.companyId); + await coordinator.stop(); reads.mockRestore(); + for (const statement of [startup, scoped]) { + expect(await db.$client.unsafe(statement.sql, statement.params as Parameters[1])) + .toMatchObject([{ id: action.id }]); + const result = await db.$client.unsafe( + `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${statement.sql}`, + statement.params as Parameters[1], + ); + type PlanNode = { Plans?: PlanNode[]; [key: string]: unknown }; + const nodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(nodes)]; + const actionReads = nodes(result[0]["QUERY PLAN"][0].Plan) + .filter(node => node["Relation Name"] === "chat_actions"); + expect(actionReads).toHaveLength(1); + expect(Number(actionReads[0]["Actual Rows"]) + Number(actionReads[0]["Rows Removed by Filter"] ?? 0), + JSON.stringify({ params: statement.params, actionReads })).toBeLessThanOrEqual(2); + expect(Number(actionReads[0]["Shared Hit Blocks"]) + Number(actionReads[0]["Shared Read Blocks"])) + .toBeLessThan(20); + } + await db.update(chatActions).set({ status: "processed" }).where(eq(chatActions.id, action.id)); + await db.execute(sql`ANALYZE chat_actions`); + expect(await db.$client.unsafe(scoped.sql, scoped.params as Parameters[1])).toHaveLength(0); + const empty = await db.$client.unsafe( + `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${scoped.sql}`, scoped.params as Parameters[1], + ); + expect(empty[0]["QUERY PLAN"][0].Plan["Shared Hit Blocks"] + + empty[0]["QUERY PLAN"][0].Plan["Shared Read Blocks"]).toBeLessThan(20); + expect(errors).toEqual([]); + } finally { + await coordinator.stop(); reads.mockRestore(); + await db.delete(chatActions).where(sql`${chatActions.providerActionId} LIKE ${`${prefix}%`}`); + } + }); + + it.each(["accept", "reject", "drain", "restart", "deferred", "failure", "paused endpoint", "future publication", "stale claim"] as const)("wakes interaction continuations from a committed response through %s", async mode => { + const context = await telegramConfirmationRecoveryFixture(mode === "reject" ? "reject" : "accept"); + const errors: unknown[] = []; + let canRun = true; + let coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => canRun, + canReconcile: () => true, onError: error => errors.push(error) }); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const settle = async () => vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(idleWorkSnapshot().active).toBe(0); expect(coordinator.nextWakeAt()).toBeNull(); + }, { timeout: 10_000 }); + const quiet = async () => { + const select = vi.spyOn(db, "select"), transaction = vi.spyOn(db, "transaction"); + try { + await vi.advanceTimersByTimeAsync(120_000); + expect(select).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); + } finally { select.mockRestore(); transaction.mockRestore(); } + }; + const originalWake = context.wakeup.getMockImplementation()!; + context.wakeup.mockImplementation(async (...args) => { + expect((context.service.runtime as unknown as FakeChatSdkRuntime).endpoints.get(context.endpoint.id)?.edits).toHaveLength(["paused endpoint", "future publication"].includes(mode) ? 0 : 1); + return originalWake(...args); + }); + if (mode === "deferred") context.wakeup.mockResolvedValueOnce(null); + if (mode === "failure") context.wakeup.mockRejectedValueOnce(new Error("temporary continuation admission failure")); + try { + await context.service.registerInteractionContinuationWork(coordinator, () => canRun).ready; + await settle(); await quiet(); + if (["drain", "paused endpoint", "future publication"].includes(mode)) canRun = false; + if (mode === "restart" || mode === "stale claim") await coordinator.stop(); + await expect(context.onAction(context.actionEvent)).rejects.toThrow("injected post-interaction confirmation settlement crash"); + if (["drain", "paused endpoint", "future publication"].includes(mode) || mode === "restart" || mode === "stale claim") { + await vi.advanceTimersByTimeAsync(1000); + await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0)); + expect(context.wakeup).not.toHaveBeenCalled(); + await quiet(); + if (mode === "paused endpoint") await db.update(chatEndpoints).set({ status: "paused" }).where(eq(chatEndpoints.id, context.endpoint.id)); + if (mode === "future publication") await db.update(chatPublications).set({ state: "retry", nextAttemptAt: new Date(Date.now() + 60_000) }) + .where(eq(chatPublications.idempotencyKey, `interaction-resolution:${context.interaction.id}:${context.endpoint.id}`)); + if (mode === "stale claim") await db.update(chatActions).set({ status: "processing", updatedAt: new Date() }).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + )); + canRun = true; + if (mode === "restart" || mode === "stale claim") { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => canRun, + canReconcile: () => true, onError: error => errors.push(error) }); + await context.service.registerInteractionContinuationWork(coordinator, () => canRun).ready; + } else if (coordinator.nextWakeAt() !== null) { + await vi.advanceTimersByTimeAsync(Math.max(0, coordinator.nextWakeAt()! - Date.now())); + } + } + if (mode === "stale claim") { + const [action] = await db.select().from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + )); + expect(coordinator.nextWakeAt()).toBe(action.updatedAt.getTime() + 30_000); + await vi.advanceTimersByTimeAsync(Math.max(0, coordinator.nextWakeAt()! - Date.now() - 1)); + expect(context.wakeup).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + } + if (mode === "deferred" || mode === "failure") { + let retryAt = 0; + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + const [action] = await db.select().from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + )); + expect(action).toMatchObject({ status: "issued", result: { code: mode === "deferred" ? "interaction_wakeup_deferred" : "interaction_wakeup_failed" } }); + retryAt = action.updatedAt.getTime() + 30_000; + expect(idleWorkSnapshot().active).toBe(0); + expect(coordinator.nextWakeAt()).toBe(retryAt); + }, { timeout: 10_000 }); + expect(context.wakeup).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(Math.max(0, retryAt - Date.now() - 1)); + expect(context.wakeup).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + } + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(await db.select({ status: chatActions.status }).from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + ))).toEqual([{ status: "processed" }]); + }, { timeout: 10_000 }); + expect(context.wakeup).toHaveBeenCalledTimes(mode === "deferred" || mode === "failure" ? 2 : 1); + expect(context.wakeup).toHaveBeenCalledWith(context.fixture.assignedAgentId, expect.objectContaining({ + idempotencyKey: `interaction:${context.interaction.id}:${mode === "reject" ? "rejected" : "accepted"}`, allowRunCoalescing: false, + })); + await settle(); await quiet(); + expect(errors).toEqual([]); + } finally { await coordinator.stop(); vi.useRealTimers(); await context.service.shutdown(); } + }); + + it("passes historical continuation prefixes and retains a response committed during dispatch", async () => { + const first = await telegramConfirmationRecoveryFixture(); + const second = await telegramConfirmationRecoveryFixture(); + await expect(first.onAction(first.actionEvent)).rejects.toThrow("injected post-interaction confirmation settlement crash"); + const invalidIds = Array.from({ length: 101 }, (_, index) => `00000000-0000-4000-8002-${String(index + 1).padStart(12, "0")}`); + await db.insert(chatActions).values(invalidIds.map(id => ({ + id, companyId: first.fixture.companyId, endpointId: first.endpoint.id, + kind: "interaction_wakeup", providerActionId: `invalid-continuation:${id}`, status: "issued", payload: {}, + }))); + let release!: () => void; + const barrier = new Promise(resolve => { release = resolve; }); + const originalWake = first.wakeup.getMockImplementation()!; + first.wakeup.mockImplementationOnce(async (...args) => { await barrier; return originalWake(...args); }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + canReconcile: () => true, onError: error => errors.push(error) }); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const ready = first.service.registerInteractionContinuationWork(coordinator, () => true).ready; + try { + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(first.wakeup).toHaveBeenCalledTimes(1); + }, { timeout: 15_000 }); + await expect(second.onAction(second.actionEvent)).rejects.toThrow("injected post-interaction confirmation settlement crash"); + expect(await db.select({ status: chatActions.status }).from(chatActions).where(and( + eq(chatActions.companyId, second.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + ))).toEqual([{ status: "issued" }]); + release(); await ready; + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(first.wakeup).toHaveBeenCalledTimes(2); + expect(idleWorkSnapshot().active).toBe(0); expect(coordinator.nextWakeAt()).toBeNull(); + }, { timeout: 15_000 }); + expect(await db.select({ id: chatActions.id }).from(chatActions).where(and( + inArray(chatActions.id, invalidIds), eq(chatActions.status, "failed"), + eq(sql`${chatActions.result}->>'code'`, "interaction_wakeup_payload_invalid"), + ))).toHaveLength(101); + expect(await db.select({ id: chatActions.id }).from(chatActions).where(and( + inArray(chatActions.companyId, [first.fixture.companyId, second.fixture.companyId]), + eq(chatActions.kind, "interaction_wakeup"), eq(chatActions.status, "processed"), + ))).toHaveLength(2); + const select = vi.spyOn(db, "select"), transaction = vi.spyOn(db, "transaction"); + try { + await vi.advanceTimersByTimeAsync(120_000); + expect(select).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); + } finally { select.mockRestore(); transaction.mockRestore(); } + expect(errors).toEqual([]); + } finally { + release(); await ready; await coordinator.stop(); vi.useRealTimers(); + await db.delete(chatActions).where(inArray(chatActions.id, invalidIds)); + await first.service.shutdown(); await second.service.shutdown(); + } + }); + + it.each(["drain", "standby", "shutdown"] as const)("stops starting continuation publications during %s", async mode => { + const context = await telegramConfirmationRecoveryFixture(); + await expect(context.onAction(context.actionEvent)).rejects.toThrow("injected post-interaction confirmation settlement crash"); + const next = await issueThreadInteractionService(db).create( + { id: context.conversation.issueId, companyId: context.fixture.companyId }, + { kind: "request_confirmation", continuationPolicy: "wake_assignee", title: "Next decision", + payload: { version: 1, prompt: "A second decision after the accepted response?" } }, + { agentId: context.fixture.assignedAgentId }, + ); + const nextPublication = () => db.select({ state: chatPublications.state }).from(chatPublications).where( + eq(chatPublications.idempotencyKey, `interaction:${next.id}:${context.endpoint.id}`)); + expect(await nextPublication()).toEqual([{ state: "pending" }]); + const provider = (context.service.runtime as unknown as FakeChatSdkRuntime).endpoints.get(context.endpoint.id)!; + const originalThread = provider.thread.bind(provider); + let entered = false; + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const threadSpy = vi.spyOn(provider, "thread").mockImplementation(threadId => { + const thread = originalThread(threadId), edit = thread.adapter.editMessage.bind(thread.adapter); + thread.adapter.editMessage = async (...args) => { entered = true; await gate; return edit(...args); }; + return thread; + }); + let canRun = true; + const errors: unknown[] = []; + let coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => canRun, + canReconcile: () => true, onError: error => errors.push(error) }); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const ready = context.service.registerInteractionContinuationWork(coordinator, () => canRun).ready; + let stopping: Promise | undefined; + try { + await vi.waitFor(() => expect(entered).toBe(true), { timeout: 10_000 }); + if (mode === "shutdown") stopping = coordinator.stop(); else canRun = false; + release(); await ready; await stopping; + await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0)); + expect(provider.edits).toHaveLength(1); + expect(await nextPublication()).toEqual([{ state: "pending" }]); + expect(context.wakeup).not.toHaveBeenCalled(); + if (mode === "shutdown") { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => canRun, + canReconcile: () => true, onError: error => errors.push(error) }); + await context.service.registerInteractionContinuationWork(coordinator, () => canRun).ready; + } else { + canRun = true; + await vi.advanceTimersByTimeAsync(Math.max(0, coordinator.nextWakeAt()! - Date.now())); + } + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(context.wakeup).toHaveBeenCalledTimes(1); + expect(await nextPublication()).toEqual([{ state: "published" }]); + expect(idleWorkSnapshot().active).toBe(0); expect(coordinator.nextWakeAt()).toBeNull(); + }, { timeout: 10_000 }); + expect(errors).toEqual([]); + } finally { + release(); await ready; await stopping; await coordinator.stop(); vi.useRealTimers(); + threadSpy.mockRestore(); await context.service.shutdown(); + } + }); + + it("defers continuation dispatch until the outer response transaction commits", async () => { + const context = await telegramConfirmationRecoveryFixture(); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + canReconcile: () => true, onError: error => errors.push(error) }); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const settle = async () => vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(idleWorkSnapshot().active).toBe(0); expect(coordinator.nextWakeAt()).toBeNull(); + }, { timeout: 10_000 }); + const originalWake = context.wakeup.getMockImplementation()!; + context.wakeup.mockImplementation(async (...args) => { + expect((context.service.runtime as unknown as FakeChatSdkRuntime).endpoints.get(context.endpoint.id)?.edits).toHaveLength(1); + return originalWake(...args); + }); + try { + await context.service.registerInteractionContinuationWork(coordinator, () => true).ready; + await settle(); + const [issue] = await db.select().from(issues).where(eq(issues.id, context.conversation.issueId)); + const accept = async (tx: Parameters[0]>[0]) => { + await issueThreadInteractionService(tx as unknown as Db).acceptInteraction(issue, context.interaction.id, {}, { userId: context.linkedUserId }); + await vi.advanceTimersByTimeAsync(100); + expect(context.wakeup).not.toHaveBeenCalled(); + expect(await db.select({ status: issueThreadInteractions.status }).from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, context.interaction.id))).toEqual([{ status: "pending" }]); + expect(await db.select({ id: chatActions.id }).from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + ))).toEqual([]); + }; + await expect(db.transaction(async tx => { + await accept(tx); + throw new Error("rollback outer continuation decision"); + })).rejects.toThrow("rollback outer continuation decision"); + await settle(); + expect(context.wakeup).not.toHaveBeenCalled(); + const select = vi.spyOn(db, "select"), transaction = vi.spyOn(db, "transaction"); + try { + await vi.advanceTimersByTimeAsync(120_000); + expect(select).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); + } finally { select.mockRestore(); transaction.mockRestore(); } + await db.transaction(accept); + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(10); + expect(context.wakeup).toHaveBeenCalledTimes(1); + }); + await settle(); + expect(await db.select({ status: chatActions.status }).from(chatActions).where(and( + eq(chatActions.companyId, context.fixture.companyId), eq(chatActions.kind, "interaction_wakeup"), + ))).toEqual([{ status: "processed" }]); + expect(errors).toEqual([]); + } finally { await coordinator.stop(); vi.useRealTimers(); await context.service.shutdown(); } + }); + it.each(["accept", "reject", "drain", "restart", "failed selection"] as const)("recovers committed terminal confirmations without polling through %s", async mode => { const context = await telegramConfirmationRecoveryFixture(mode === "reject" ? "reject" : "accept"); let canRun = true; diff --git a/server/src/app.ts b/server/src/app.ts index 2805f00b2a0..865424a5c3e 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -1288,6 +1288,7 @@ export async function createApp( chatChannels.registerReceiverWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); chatChannels.registerTeamsConsentExpiryWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); chatChannels.registerTeamsAttemptRecoveryWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); + chatChannels.registerInteractionContinuationWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); chatChannels.registerTerminalConfirmationWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); chatChannels.registerCommandWork(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); nativeChatProgressWork(db).register(deliveryWork, () => !isWarmStandby() && !isIdleTaskDrainActive()); diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 4e504e2b8f7..2ac5ed4eed0 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -3350,7 +3350,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { async function processPublicationMaintenance(limit = 25) { scheduleGitHubMaintenance(); - await processPendingInteractionWakeups(limit); } // The app refills free endpoint slots on commits and durable deadlines. @@ -3475,7 +3474,8 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { withCredentialMutationLease, receiptReactionCompletionRunId, }); const { processSelectedPublication } = publicationWorker; - const { processPendingInteractionWakeups } = createChatInteractionContinuations(db, { + const { processPendingInteractionWakeups, registerInteractionContinuationWork } = createChatInteractionContinuations(db, { + preparePublications: (scope, canContinue) => processPendingPublications(25, { maintenance: false, scope, canContinue }), redactError, CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS, get heartbeat() { return options.heartbeat; }, }); const { handleAction, handleModalSubmit, reconcileTerminalConfirmationActions, registerTerminalConfirmationWork } = createChatInteractionCallbacks(db, { @@ -3502,6 +3502,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const { prepareTeamsBoardSend } = createTeamsBoardSendPreparation(db, { endpointRecord, runtimeFor }); const { getPublicationBatchStatus, publishComment, publishBoardMessage } = createChatPublicationRequests(db, { endpointRecord, stageTeamsBoardFileIntent, processPendingSlackBoardMessages, processPendingPublications, prepareTeamsBoardSend }); return { + registerInteractionContinuationWork, registerTerminalConfirmationWork, loadFailedRetryNoticeScopes, reconcileFailedRetryNotices, diff --git a/server/src/services/chat-channels/interactions/confirmation-actions.ts b/server/src/services/chat-channels/interactions/confirmation-actions.ts index 91c60570b1d..ddb4c89d258 100644 --- a/server/src/services/chat-channels/interactions/confirmation-actions.ts +++ b/server/src/services/chat-channels/interactions/confirmation-actions.ts @@ -1,3 +1,4 @@ +import { notifyChatContinuationWork } from "../../chat-continuation-notifications.js"; import { connectionIntentService } from "../../connection-intents.js"; import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "../../issue-assignment-wakeup.js"; import { chatInteractionPresentation } from "../../chat-interaction-presentation.js"; @@ -580,6 +581,7 @@ export function createChatConfirmationActions(db: Db, options: ChatConfirmationO }) .onConflictDoNothing(); if (shouldWake && issue.assigneeAgentId) { + await notifyChatContinuationWork(tx, { companyId: issue.companyId, issueId: issue.id }); await tx .insert(chatActions) .values({ diff --git a/server/src/services/chat-channels/interactions/continuations.ts b/server/src/services/chat-channels/interactions/continuations.ts index 8b6697e91c3..4492a7629e2 100644 --- a/server/src/services/chat-channels/interactions/continuations.ts +++ b/server/src/services/chat-channels/interactions/continuations.ts @@ -1,8 +1,14 @@ +import { notifyChatContinuationWork, type ChatContinuationScope } from "../../chat-continuation-notifications.js"; +import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; +import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; +import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; import { and, asc, desc, eq, + inArray, + sql, isNotNull, isNull, lte, @@ -32,6 +38,7 @@ import { issueThreadInteractionService } from "../../issue-thread-interactions.j type InteractionContinuationsOptions = { heartbeat: IssueAssignmentWakeupDeps; + preparePublications: (scope: { companyId: string; endpointId: string; conversationId: string }, canContinue: () => boolean) => Promise; redactError: (error: unknown) => string; CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS: number; }; @@ -42,6 +49,9 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC async function processPendingInteractionWakeups( limit = 100, + actionId?: string, + preparePublications = false, + canContinue: () => boolean = () => true, ): Promise { const staleBefore = new Date(Date.now() - 30_000); const retryBefore = new Date( @@ -53,6 +63,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC .where( and( eq(chatActions.kind, "interaction_wakeup"), + actionId ? eq(chatActions.id, actionId) : undefined, or( and( eq(chatActions.status, "issued"), @@ -72,7 +83,17 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC .limit(limit); let processed = 0; for (const candidate of candidates) { - const [claimed] = await db + if (preparePublications && candidate.conversationId) { + await options.preparePublications({ companyId: candidate.companyId, + endpointId: candidate.endpointId, conversationId: candidate.conversationId }, canContinue); + } + if (!canContinue()) break; + const writeAction = (write: (tx: Parameters[0]>[0]) => PromiseLike) => + db.transaction(async tx => { + await notifyChatContinuationWork(tx, { companyId: candidate.companyId, actionId: candidate.id }); + return write(tx); + }); + const [claimed] = await writeAction(tx => tx .update(chatActions) .set({ status: "processing", updatedAt: new Date() }) .where( @@ -93,7 +114,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC ), ), ) - .returning(); + .returning()); if (!claimed) continue; const payload = claimed.payload; const requestedByActorType = @@ -122,7 +143,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC !requestedByActorType || !requestedByActorId ) { - await db + await writeAction(tx => tx .update(chatActions) .set({ status: "failed", @@ -134,7 +155,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC eq(chatActions.id, claimed.id), eq(chatActions.status, "processing"), ), - ); + )); continue; } const currentIssue = await db @@ -167,7 +188,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC currentIssue.status === "done" || currentIssue.status === "cancelled" ) { - await db + await writeAction(tx => tx .update(chatActions) .set({ status: "processed", @@ -179,7 +200,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC eq(chatActions.id, claimed.id), eq(chatActions.status, "processing"), ), - ); + )); processed += 1; continue; } @@ -325,7 +346,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC .limit(1) .then((rows) => rows[0] ?? null)); if (!queuedRun && !durable) { - await db + await writeAction(tx => tx .update(chatActions) .set({ status: "issued", @@ -337,10 +358,10 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC eq(chatActions.id, claimed.id), eq(chatActions.status, "processing"), ), - ); + )); continue; } - await db + await writeAction(tx => tx .update(chatActions) .set({ status: "processed", @@ -358,7 +379,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC eq(chatActions.id, claimed.id), eq(chatActions.status, "processing"), ), - ); + )); processed += 1; } catch (error) { const durable = isUniqueViolation(error) @@ -393,7 +414,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC ? previousResult.attemptCount : 0; const attemptCount = previousAttempts + 1; - await db + await writeAction(tx => tx .update(chatActions) .set({ status: durable ? "processed" : "issued", @@ -412,7 +433,7 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC eq(chatActions.id, claimed.id), eq(chatActions.status, "processing"), ), - ); + )); if (!durable) { logger.warn( { @@ -428,5 +449,53 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC } return processed; } - return { processPendingInteractionWakeups }; + function registerInteractionContinuationWork( + coordinator: ReturnType, + canRun: () => boolean, + ) { + type Entry = { id: string; companyId: string; issueId: string | null; dueAt: number }; + const selection = { + id: chatActions.id, companyId: chatActions.companyId, + issueId: sql`${chatActions.payload}->>'issueId'`, + status: chatActions.status, result: chatActions.result, updatedAt: chatActions.updatedAt, + }; + const entry = (row: { id: string; companyId: string; issueId: string | null; status: string; + result: unknown; updatedAt: Date }): Entry => ({ + id: row.id, companyId: row.companyId, issueId: row.issueId, + dueAt: row.status === "processing" ? row.updatedAt.getTime() + 30_000 + : row.result === null ? 0 : row.updatedAt.getTime() + CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS, + }); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.chatInteractionContinuations, + decodeScope: (hint: string): ChatContinuationScope | undefined => hint === "*" ? undefined : JSON.parse(hint), + matches: (value: Entry, scope?: ChatContinuationScope) => !scope || + (value.companyId === scope.companyId && (!scope.actionId || value.id === scope.actionId) && + (!scope.issueId || value.issueId === scope.issueId)), + load: async (scope?: ChatContinuationScope, signal?: AbortSignal): Promise => { + const entries: Entry[] = []; + let cursor: { companyId: string; id: string } | undefined; + while (!signal?.aborted) { + const rows = await db.select(selection).from(chatActions).where(and( + sql`${chatActions.kind} = 'interaction_wakeup' AND ${chatActions.status} IN ('issued', 'processing')`, + scope ? eq(chatActions.companyId, scope.companyId) : undefined, + scope?.actionId ? eq(chatActions.id, scope.actionId) : undefined, + scope?.issueId ? eq(sql`${chatActions.payload}->>'issueId'`, scope.issueId) : undefined, + cursor ? sql`(${chatActions.companyId}, ${chatActions.id}) > (${cursor.companyId}, ${cursor.id})` : undefined, + )).orderBy(asc(chatActions.companyId), asc(chatActions.id)).limit(100); + entries.push(...rows.map(entry)); + if (rows.length < 100) return entries; + cursor = rows[rows.length - 1]; + } + throw signal?.reason ?? new Error("Interaction continuation recovery stopped"); + }, + check: async (value: Entry, signal?: AbortSignal) => { + await processPendingInteractionWakeups(1, value.id, true, () => canRun() && !signal?.aborted); + const [current] = await db.select(selection).from(chatActions).where(and( + eq(chatActions.id, value.id), inArray(chatActions.status, ["issued", "processing"]), + )); + return current ? entry(current) : null; + }, + }, canRun); + } + return { processPendingInteractionWakeups, registerInteractionContinuationWork }; } diff --git a/server/src/services/chat-channels/publications/queue.ts b/server/src/services/chat-channels/publications/queue.ts index 7aa0537fe70..a1b3b3e7bf3 100644 --- a/server/src/services/chat-channels/publications/queue.ts +++ b/server/src/services/chat-channels/publications/queue.ts @@ -181,13 +181,22 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti async function processPendingPublications( limit = 25, - { waitForCompletion = true, maintenance = true }: { waitForCompletion?: boolean; maintenance?: boolean } = {}, + { waitForCompletion = true, maintenance = true, scope, canContinue = () => true }: { + waitForCompletion?: boolean; maintenance?: boolean; canContinue?: () => boolean; + scope?: { companyId: string; endpointId: string; conversationId: string }; + } = {}, ) { - if (isShuttingDown()) return 0; + if (isShuttingDown() || !canContinue()) return 0; if (maintenance) { await enqueueInboundWakeupPublications(); await reconcileTerminalConfirmationActions(limit); } + if (isShuttingDown() || !canContinue()) return 0; + const scopeCondition = scope ? and(eq(chatPublications.companyId, scope.companyId), + eq(chatPublications.endpointId, scope.endpointId), eq(chatPublications.conversationId, scope.conversationId)) : undefined; + const pendingTasks = () => scope + ? [publicationEndpointTasks.get(scope.endpointId)].filter((task): task is Promise => Boolean(task)) + : [...publicationEndpointTasks.values()]; const now = new Date(); const staleBefore = new Date(now.getTime() - 60_000); // A process that disappears after the provider accepted a post but before @@ -196,6 +205,7 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti // checking the provider conversation. const quarantinedPublications = await db.transaction(async tx => { const condition = and( + scopeCondition, sql`not exists (select 1 from chat_endpoints e where e.id = ${chatPublications.endpointId} and e.publication_mode = 'explicit')`, eq(chatPublications.state, "streaming"), lte(chatPublications.updatedAt, staleBefore), @@ -278,7 +288,7 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti let failed = false; let firstError: unknown; try { - while (attemptedIds.length < limit && !failed && !isShuttingDown()) { + while (attemptedIds.length < limit && !failed && !isShuttingDown() && canContinue()) { if (publicationEndpointTasks.size >= PUBLICATION_ENDPOINT_CONCURRENCY) { if (!waitForCompletion) break; await Promise.race(publicationEndpointTasks.values()); @@ -295,7 +305,7 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti .select() .from(chatPublications) .where( - publicationEligibility({ now, busyEndpointIds, coolingTeamsPublicationIds, attemptedIds }), + and(scopeCondition, publicationEligibility({ now, busyEndpointIds, coolingTeamsPublicationIds, attemptedIds })), ) .orderBy( asc(chatPublications.createdAt), @@ -308,8 +318,9 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti // exposing a new head that must be queried before declaring idle. if (busyEndpointIds.some((id) => !publicationEndpointTasks.has(id))) continue; - if (!waitForCompletion || publicationEndpointTasks.size === 0) break; - await Promise.race(publicationEndpointTasks.values()); + const pending = pendingTasks(); + if (!waitForCompletion || pending.length === 0) break; + await Promise.race(pending); continue; } let started = false; @@ -318,7 +329,7 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti publicationEndpointTasks.size >= PUBLICATION_ENDPOINT_CONCURRENCY || attemptedIds.length >= limit || failed || - isShuttingDown() + (isShuttingDown() || !canContinue()) ) break; if (publicationEndpointTasks.has(selectedPublication.endpointId)) @@ -330,6 +341,7 @@ export function createChatPublicationQueue(db: Db, options: PublicationQueueOpti // endpoint-exclusive credential fence instead of timing out behind it. const task = Promise.resolve() .then(async () => { + if (isShuttingDown() || !canContinue()) return; await processSelectedPublication(selectedPublication); await settleExternalConversation(db, selectedPublication.companyId, selectedPublication.issueId).catch((err) => { logger.warn({ err, publicationId: selectedPublication.id }, "Slack conversation settlement deferred to reconciliation"); diff --git a/server/src/services/chat-continuation-notifications.ts b/server/src/services/chat-continuation-notifications.ts new file mode 100644 index 00000000000..78b92bf8b58 --- /dev/null +++ b/server/src/services/chat-continuation-notifications.ts @@ -0,0 +1,8 @@ +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; + +export type ChatContinuationScope = { companyId: string; issueId?: string; actionId?: string }; + +export async function notifyChatContinuationWork(tx: object, scope: ChatContinuationScope) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatInteractionContinuations, + JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId, actionId: scope.actionId })); +} diff --git a/server/src/services/chat-interaction-publications.ts b/server/src/services/chat-interaction-publications.ts index 72b1779e68d..37e0199a5bf 100644 --- a/server/src/services/chat-interaction-publications.ts +++ b/server/src/services/chat-interaction-publications.ts @@ -1,3 +1,4 @@ +import { notifyChatContinuationWork } from "./chat-continuation-notifications.js"; import { chatInteractionForm } from "./chat-interaction-forms.js"; import { slackInteractionRequiresBoard } from "./chat-channels/slack/cards.js"; import { answeredChatQuestionBody, chatInteractionPresentation } from "./chat-interaction-presentation.js"; @@ -710,51 +711,54 @@ export async function enqueueTerminalIssueInteractionChatPublications( interaction.resolvedByAgentId === issue.assigneeAgentId ) ) { - await db - .insert(chatActions) - .values({ - companyId: interaction.companyId, - endpointId: wakeBinding.endpointId, - conversationId: wakeBinding.conversationId, - kind: "interaction_wakeup", - providerActionId: `interaction_wakeup:${interaction.id}`, - payload: { - version: 1, - interactionId: interaction.id, - interactionKind: interaction.kind, - interactionStatus: interaction.status, - issueId: interaction.issueId, - agentId: issue.assigneeAgentId, - sourceCommentId: interaction.sourceCommentId ?? null, - sourceRunId: interaction.sourceRunId ?? null, - requestedByActorType, - requestedByActorId, - ...(planTarget - ? { - planReviewInteraction: { - id: interaction.id, - kind: interaction.kind, - status: interaction.status, - target: planTarget, - acceptedTargetRevision: - interaction.status === "accepted" ? planTarget : null, - result: interaction.result, - }, - } - : {}), - ...(interaction.status === "accepted" && planTarget - ? { - forceFreshSession: true, - workspaceRefreshReason: "accepted_plan_confirmation", - } - : {}), - ...(interaction.resolvedByUserId - ? { requestedByUserId: interaction.resolvedByUserId } - : {}), - }, - status: "issued", - }) - .onConflictDoNothing(); + await db.transaction(async tx => { + await notifyChatContinuationWork(tx, { companyId: interaction.companyId, issueId: interaction.issueId }); + await tx + .insert(chatActions) + .values({ + companyId: interaction.companyId, + endpointId: wakeBinding.endpointId, + conversationId: wakeBinding.conversationId, + kind: "interaction_wakeup", + providerActionId: `interaction_wakeup:${interaction.id}`, + payload: { + version: 1, + interactionId: interaction.id, + interactionKind: interaction.kind, + interactionStatus: interaction.status, + issueId: interaction.issueId, + agentId: issue.assigneeAgentId, + sourceCommentId: interaction.sourceCommentId ?? null, + sourceRunId: interaction.sourceRunId ?? null, + requestedByActorType, + requestedByActorId, + ...(planTarget + ? { + planReviewInteraction: { + id: interaction.id, + kind: interaction.kind, + status: interaction.status, + target: planTarget, + acceptedTargetRevision: + interaction.status === "accepted" ? planTarget : null, + result: interaction.result, + }, + } + : {}), + ...(interaction.status === "accepted" && planTarget + ? { + forceFreshSession: true, + workspaceRefreshReason: "accepted_plan_confirmation", + } + : {}), + ...(interaction.resolvedByUserId + ? { requestedByUserId: interaction.resolvedByUserId } + : {}), + }, + status: "issued", + }) + .onConflictDoNothing(); + }); } } diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index d113ff09bdf..428bc88b2ca 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -59,6 +59,7 @@ export const DELIVERY_QUEUES = { chatPublications: "chat-publications", chatNativeProgress: "chat-native-progress", chatInboundWakeNotices: "chat-inbound-wake-notices", + chatInteractionContinuations: "chat-interaction-continuations", chatTerminalConfirmations: "chat-terminal-confirmations", chatFailedRetryNotices: "chat-failed-retry-notices", chatRunMilestones: "chat-run-milestones",