From 4f6e1c3608b47cdbf0648f1c7a6c485c44a945bb Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:59:25 -0300 Subject: [PATCH 1/3] Keep observed peer exits separate from shutdown deadlines A pipe can remain open after its peer exits. Stop the signal clock at exit while allowing buffered output to finish. Report an unconfirmed shutdown without probing a socket as if the process had exited. Verified: bun run test:unit cli/test/unit/verifySmokePeerShutdown.test.ts cli/test/unit/verifySmokeTalkTurns.test.ts cli/test/unit/verifySmokeScan.test.ts; bun run check:types; bun run lint .agents/skills/verify/scripts/omp-smoke.ts .agents/skills/verify/scripts/smokePeerShutdown.ts cli/test/unit/verifySmokePeerShutdown.test.ts cli/test/fixtures/talk/unconfirmed-peer.ts; bun fmt --no-script --check cli/test/unit/verifySmokePeerShutdown.test.ts --- .agents/skills/verify/SKILL.md | 3 +- .agents/skills/verify/scripts/omp-smoke.ts | 144 ++++++++---------- .../verify/scripts/smokePeerShutdown.ts | 84 ++++++++++ cli/test/fixtures/talk/unconfirmed-peer.ts | 41 +++++ cli/test/unit/verifySmokePeerShutdown.test.ts | 97 ++++++++++++ 5 files changed, 285 insertions(+), 84 deletions(-) create mode 100644 .agents/skills/verify/scripts/smokePeerShutdown.ts create mode 100644 cli/test/fixtures/talk/unconfirmed-peer.ts create mode 100644 cli/test/unit/verifySmokePeerShutdown.test.ts diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index 44e05a65..2e3ca1b3 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -172,7 +172,7 @@ exit 0 | `new-session-send` | Sender: `send` with `to` set to the full new session id | As `talk-send`, for the new instance id. | | `new-session-old-instance-not-live` | Sender: `send` with `instance` set to the old instance id, which the same sender process listed before | The result reads `talk: the send failed: not-live`. After 0.5 s, a sentinel `send` to the new instance is delivered, the answer continues the `new-session-send` answer, the peer is still in the new session, and no entry of that answer holds the message id or the payload text of that send. | | `fork-list`, `fork-send`, `fork-old-instance-not-live` | RPC `fork` with `entryId` set to the last assistant message of the new session. Then the same actions as for `new_session`, with the instance id of `new-session-list` as the old instance id. | As the `new-session-` lines. Also, the answer that confirmed `fork-send`, which is the kept answer, holds the talk entry of `new-session-send`, which the fork inherited. The sentinel answer of `fork-old-instance-not-live` continues the kept answer, so it holds that entry again with the same `id`, `parentId`, `details.messageId`, and `content`. | -| `closed-peer-not-live` | The peer stdin ends and the peer exits. Sender: `send` with `instance` set to the instance id of `fork-list`. | The result reads `talk: the send failed: not-live`. | +| `closed-peer-not-live` | After the driver confirms the peer exited, the sender calls `send` with the instance id from `fork-list`. | The result reads `talk: the send failed: not-live`. Without a confirmed exit, the check fails without sending. | | `extensions-loaded`, `isolated`, `real-state` | The whole run; the warnings include the standard error of the peer | As in the `hooks` mode | | `sessions` | Both omp processes | The sender exits 0 after its last turn. The peer exits 0 after its stdin ends. | | `registry` | The peer from its start and the sender from its start; the script reads the result after `talk-offered`, while both wait. The peer again from the new session id of each `new_session` and `fork`, apart from the list step. The final scan of the peer before its stdin ends, and of the sender before its last turn. | As in the `hooks` mode, for each of the two processes, with the work folder of the run as `cwd`. After a session change, the valid private entry also has the new session id, and its instance id is the instance id of the list. Each final scan finds no entry of the registrations of its process in the default folder. When a check before it fails and no final scan found a problem, this line reads `not run`. | @@ -286,6 +286,7 @@ The other lines are as above. talk is off on this omp and registers no session, | `FAIL talk-offered: the first fixture turn of the took more than 30 s` | The responder did not identify an opening prompt before the deadline. It did not inspect that turn's tool list. | Check whether omp sent the prompt. If it did, compare its message format with `latestEvent` in `smokeTalkTurns.ts`. | | `FAIL talk-offered: the first fixture turn of the does not offer the talk tool` | The named process sent its opening turn without `talk` in the tool list. | Check `extensions-loaded`. If the extension loaded, check tool registration and whether omp offers `talk` as a provider tool instead of a Bash command. | | V6 `talk` prints `the call talk-sender- took more than 30 s` | The driver did not receive a matching completion before the deadline. The message alone does not say whether a tool result arrived. | Check whether the tool ran and returned. If it did, check the call ID and the latest event. Run `bun run test:unit cli/test/unit/verifySmokeTalkTurns.test.ts`. | +| `talk` or `talk-ui` reports `the peer omp exit was not confirmed after SIGKILL` | The final 10 s wait ended without a peer exit event. A closed socket does not prove exit. | Check the peer's shutdown. To reproduce the reporting path without leaving a process running, repeat V6 with `bun --preload ./cli/test/fixtures/talk/unconfirmed-peer.ts` in place of `bun`. Both modes must fail `sessions`; `talk` must also fail `closed-peer-not-live`. | | V6 `talk` reports another failure in `talk-`, `new-session-`, `fork-`, or `closed-peer-` | The step name identifies where the driver stopped, not which operation failed. | Read the reason after the step name. Check the named RPC command, tool result, or fixture operation. | | V6 `talk` prints `FAIL handover-refused` | A print session did not refuse the `handover` action before its side turn: the result has no refusal, the fake model got a side-turn request with the handover template, the peer holds the note or a handover entry, or the call took more than 30 s because a flow opened in a session without a terminal | Check the refusals of `handoverFlow` in `cli/talk/extension.ts` and `runHandover` in `cli/talk/tool/tool.ts` (#260 H3) | | V6 `talk-ui` prints `FAIL ui-ready` or `FAIL old-omp` with `footer with the model name` | The TUI omp did not start in the pseudo-terminal, for example because it shows the setup wizard | Read the screen text in the reason. Check `startup.setupWizard` in the isolated `config.yml` and the omp version (V2) | diff --git a/.agents/skills/verify/scripts/omp-smoke.ts b/.agents/skills/verify/scripts/omp-smoke.ts index 000cf80a..1f97657f 100755 --- a/.agents/skills/verify/scripts/omp-smoke.ts +++ b/.agents/skills/verify/scripts/omp-smoke.ts @@ -70,6 +70,7 @@ import { TalkPosixSystem, TalkTrustError, } from "../../../../cli/talk/transport/trustPosix.ts"; +import { PEER_CLOSE_MS, peerShutdown, type PeerResult } from "./smokePeerShutdown.ts"; import { type Attribution, decodeAttribution, @@ -357,11 +358,14 @@ function isolatedEnv(isolation: Isolation): Record { return env; } -interface OmpResult { +interface OmpDiagnostics { + readonly stderr: string; +} + +interface OmpResult extends OmpDiagnostics { readonly argv: readonly string[]; readonly code: number | "timeout" | null; readonly stdout: string; - readonly stderr: string; } /** @@ -1261,7 +1265,7 @@ function pluginMarkers(plugin: LinkedPlugin | null): string[] { */ function countWarnings( skillWarnings: readonly Json[], - results: readonly OmpResult[], + results: readonly OmpDiagnostics[], stateDir: string, markers: readonly string[], ): string[] { @@ -1304,7 +1308,7 @@ interface Run { readonly workDir: string; readonly requests: JsonObject[]; readonly script: Script; - readonly results: OmpResult[]; + readonly results: OmpDiagnostics[]; readonly omp: (argv: readonly string[], options?: OmpOptions) => Promise; readonly plugin: LinkedPlugin | null; /** The modification time of the fresh sweep stamp in the scratch home. */ @@ -1383,7 +1387,7 @@ async function install(failures: string[], setup: InstallSetup = DEFAULT_SETUP): if (setup.configYaml !== null) writeFileSync(join(isolation.stateDir, "agent", "config.yml"), setup.configYaml); - const results: OmpResult[] = []; + const results: OmpDiagnostics[] = []; const omp = async (argv: readonly string[], options: OmpOptions = {}): Promise => { const result = await runOmp( argv, @@ -2030,9 +2034,6 @@ const LIST_ATTEMPTS = 20; const LIST_RETRY_MS = 250; /** The wait before a check that expects no entry, so that a late append would show. */ const SETTLE_MS = 500; -const PEER_CLOSE_MS = 10_000; -/** Allow buffered RPC output to drain after exit, but not an inherited pipe to keep the fixture open. */ -const RPC_OUTPUT_DRAIN_MS = 250; /** The number of session id characters that a `list` line shows. */ const SHORT_ID_LENGTH = 8; @@ -2079,9 +2080,9 @@ interface RpcPeer { readonly send: (command: JsonObject) => Promise; /** * Ends stdin and waits for the exit; SIGTERM, then SIGKILL, when omp does not exit in time. A process that - * already exited, or never started, gives its result at once. Repeated calls share the first result. + * already exited still receives its bounded output drain. Repeated calls share the first result. */ - readonly close: () => Promise; + readonly close: () => Promise; } /** A spawned RPC omp: its handle, and its ready line, which fails when the process ends first or takes too long. */ @@ -2107,32 +2108,32 @@ function startRpcOmp( let ended = false; const waiting = new Map>(); const ready = Promise.withResolvers(); - let drainTimer: NodeJS.Timeout | undefined; - const exited = Promise.withResolvers(); const output = createInterface({ input: child.stdout }); - /** Settle once, after the peer exits and its output drains or the drain deadline expires. */ - const end = (code: number | null, problem: string): void => { - if (ended) return; - ended = true; - clearTimeout(drainTimer); - children.delete(child); - output.close(); - child.stdin.destroy(); - child.stdout.destroy(); - child.stderr.destroy(); - const gone = new Error(`${problem}: ${short(stderr)}`); - for (const reply of waiting.values()) reply.reject(gone); - waiting.clear(); - ready.reject(gone); - exited.resolve(code); - }; + const shutdown = peerShutdown({ + endInput: () => child.stdin.end(), + signal: (signal) => child.kill(signal), + unref: () => child.unref(), + release: (problem) => { + ended = true; + children.delete(child); + output.close(); + child.stdin.destroy(); + child.stdout.destroy(); + child.stderr.destroy(); + const gone = new Error(`${problem}: ${short(stderr)}`); + for (const reply of waiting.values()) reply.reject(gone); + waiting.clear(); + ready.reject(gone); + return stderr; + }, + }); child.stdin.on("error", () => undefined); child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString("utf8"); }); child.on("error", (error) => { stderr += String(error); - if (child.pid === undefined) end(null, "the peer omp did not start"); + if (child.pid === undefined) shutdown.failedToStart(); }); output.on("line", (line) => { const message = parseJsonText(line); @@ -2151,14 +2152,8 @@ function startRpcOmp( ); else reply.resolve(message["data"] ?? null); }); - child.once("exit", (code) => { - // A descendant can hold stdout or stderr after the peer exits. Keep its - // buffered replies until `close`, but never wait indefinitely for EOF. - drainTimer = setTimeout(() => end(code, `the peer omp exited ${code}`), RPC_OUTPUT_DRAIN_MS); - }); - child.on("close", (code) => { - end(code, `the peer omp exited ${code}`); - }); + child.once("exit", shutdown.exited); + child.once("close", shutdown.pipesClosed); const send = (rpcCommand: JsonObject): Promise => { if (ended) return Promise.reject(new Error("the peer omp has ended")); @@ -2169,34 +2164,18 @@ function startRpcOmp( child.stdin.write(`${JSON.stringify({ id, ...rpcCommand })}\n`); return withTimeout(reply.promise, STEP_TIMEOUT_MS, `RPC ${String(rpcCommand["type"])}`); }; - const exitWithin = (ms: number): Promise => - withTimeout(exited.promise, ms, "the exit").catch(() => undefined); - const stop = async (): Promise => { - if (!ended) child.stdin.end(); - let code = await exitWithin(PEER_CLOSE_MS); - if (code === undefined) { - child.kill("SIGTERM"); - code = await exitWithin(PEER_CLOSE_MS); - } - if (code === undefined) { - child.kill("SIGKILL"); - code = await exitWithin(PEER_CLOSE_MS); - if (code === undefined) { - child.unref(); - end(null, "the peer omp did not exit after SIGKILL"); - return { argv, code: "timeout", stdout: "", stderr }; - } - } - return { argv, code, stdout: "", stderr }; - }; - let closing: Promise | undefined; - const close = (): Promise => (closing ??= stop()); return { - peer: { pid: child.pid, send, close }, + peer: { pid: child.pid, send, close: shutdown.close }, ready: withTimeout(ready.promise, STEP_TIMEOUT_MS, "the ready line of the peer omp"), }; } +function peerSessionFailure(result: PeerResult | null, excerpt: (stderr: string) => string): string { + if (result === null) return "the peer omp did not run"; + if (result.kind === "unconfirmed") return result.reason; + return result.code === 0 ? "" : `the peer omp exited ${result.code}: ${excerpt(result.stderr)}`; +} + /** * Copies the kit plugin folder, with the shipped `talk.js` and its manifest entry, to the scratch folder. * Returns the copy, which omp links. The copy keeps each symbolic link as it is, so a relative link does not @@ -2412,7 +2391,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> const pass = (): void => { results.set(step, ""); }; - let peer: FixtureProcess = { kind: "absent" }; + let peer: FixtureProcess = { kind: "absent" }; let senderRun: Promise | null = null; // The registrations that the mode attributed for each omp process, and the problems of the `registry` line. const peerAttributed: Attributed[] = []; @@ -2763,6 +2742,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> // The smoke ends the peer here; the sender stays live until the end of the mode. await finalScan(peerAttributed); peer = { kind: "closed", result: await rpc.close() }; + if (peer.result.kind === "unconfirmed") failStep(peer.result.reason); const closed = await sender.call(TALK_TOOL, { action: "send", instance: afterFork.instance, @@ -2794,16 +2774,13 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> return senderRun; }); const sessionFailures: string[] = []; - for (const [name, result] of [ - ["sender", senderResult], - ["peer", peerResult], - ] as const) { - if (result === null) sessionFailures.push(`the ${name} omp did not run`); - else if (result.code !== 0) - sessionFailures.push( - `the ${name} omp exited ${result.code}: ${short(result.stderr || result.stdout)}`, - ); - } + if (senderResult === null) sessionFailures.push("the sender omp did not run"); + else if (senderResult.code !== 0) + sessionFailures.push( + `the sender omp exited ${senderResult.code}: ${short(senderResult.stderr || senderResult.stdout)}`, + ); + const peerFailure = peerSessionFailure(peerResult, short); + if (peerFailure) sessionFailures.push(peerFailure); if (peerResult !== null) run.results.push(peerResult); const warnings = countWarnings( [], @@ -3224,10 +3201,10 @@ class TerminalOmp { * One omp process of a talk mode: not started, open while the driver holds a handle to close (whether or not the * process passed its readiness check), or closed with its exit result. */ -type FixtureProcess = +type FixtureProcess = | { readonly kind: "absent" } | { readonly kind: "open"; readonly handle: Handle } - | { readonly kind: "closed"; readonly result: OmpResult }; + | { readonly kind: "closed"; readonly result: Completion }; /** One `talk` call of the RPC peer that the driver waits for. */ interface MarkedCall { @@ -3377,8 +3354,8 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null const pass = (): void => { results.set(step, ""); }; - let terminal: FixtureProcess = { kind: "absent" }; - let peer: FixtureProcess = { kind: "absent" }; + let terminal: FixtureProcess = { kind: "absent" }; + let peer: FixtureProcess = { kind: "absent" }; /** * omp before 19.2.0: one capability notice, no load error, no `/talk` command, and no `talk` tool. The first @@ -3921,14 +3898,15 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null if (peer.kind === "open") peer = { kind: "closed", result: await peer.handle.close() }; const peerResult = peer.kind === "closed" ? peer.result : null; const sessionFailures: string[] = []; - const sessions: Array = [["TUI", terminalResult]]; - if (checks === UI_CHECKS) sessions.push(["peer", peerResult]); - for (const [name, result] of sessions) { - if (result === null) sessionFailures.push(`the ${name} omp did not run`); - else if (result.code !== 0) - sessionFailures.push( - `the ${name} omp exited ${result.code}: ${short(result.stderr.slice(-600))}`, - ); + const excerpt = (stderr: string): string => short(stderr.slice(-600)); + if (terminalResult === null) sessionFailures.push("the TUI omp did not run"); + else if (terminalResult.code !== 0) + sessionFailures.push( + `the TUI omp exited ${terminalResult.code}: ${excerpt(terminalResult.stderr)}`, + ); + if (checks === UI_CHECKS) { + const peerFailure = peerSessionFailure(peerResult, excerpt); + if (peerFailure) sessionFailures.push(peerFailure); } for (const result of [terminalResult, peerResult]) if (result !== null) run.results.push(result); const warnings = countWarnings( diff --git a/.agents/skills/verify/scripts/smokePeerShutdown.ts b/.agents/skills/verify/scripts/smokePeerShutdown.ts new file mode 100644 index 00000000..7e71c593 --- /dev/null +++ b/.agents/skills/verify/scripts/smokePeerShutdown.ts @@ -0,0 +1,84 @@ +export const PEER_CLOSE_MS = 10_000; +const RPC_OUTPUT_DRAIN_MS = 250; + +/** A null code is a confirmed signal exit. An unconfirmed shutdown has no exit code. */ +export type PeerResult = + | { readonly kind: "exited"; readonly code: number | null; readonly stderr: string } + | { readonly kind: "unconfirmed"; readonly reason: string; readonly stderr: string }; + +export interface PeerControls { + readonly endInput: () => void; + readonly signal: (signal: "SIGTERM" | "SIGKILL") => void; + readonly unref: () => void; + /** Reject remaining RPC requests, release the pipes, and return the collected stderr. */ + readonly release: (reason: string) => string; +} + +export interface PeerShutdown { + readonly exited: (code: number | null) => void; + readonly pipesClosed: () => void; + readonly failedToStart: () => void; + readonly close: () => Promise; +} + +type Phase = + | { readonly kind: "running" | "done" } + | { readonly kind: "stopping"; readonly timer: NodeJS.Timeout } + | { readonly kind: "draining"; readonly timer: NodeJS.Timeout; readonly code: number | null }; + +/** Deadlines for sending signals stop at exit, even if a descendant holds the output pipes. */ +export function peerShutdown(controls: PeerControls): PeerShutdown { + let phase: Phase = { kind: "running" }; + const result = Promise.withResolvers(); + + function clearDeadline(): void { + if (phase.kind === "stopping" || phase.kind === "draining") clearTimeout(phase.timer); + } + + function finish(): void { + if (phase.kind !== "draining") return; + const { code } = phase; + clearDeadline(); + phase = { kind: "done" }; + result.resolve({ + kind: "exited", + code, + stderr: controls.release(`the peer omp exited ${code}`), + }); + } + + function unconfirmed(reason: string): void { + clearDeadline(); + phase = { kind: "done" }; + result.resolve({ kind: "unconfirmed", reason, stderr: controls.release(reason) }); + } + + function stop(stage: "stdin" | "SIGTERM" | "SIGKILL"): void { + const timer = setTimeout(() => { + if (stage === "SIGKILL") { + controls.unref(); + unconfirmed("the peer omp exit was not confirmed after SIGKILL"); + } else stop(stage === "stdin" ? "SIGTERM" : "SIGKILL"); + }, PEER_CLOSE_MS); + phase = { kind: "stopping", timer }; + if (stage === "stdin") controls.endInput(); + else controls.signal(stage); + } + + return { + exited: (code) => { + if (phase.kind === "done" || phase.kind === "draining") return; + clearDeadline(); + phase = { kind: "draining", code, timer: setTimeout(finish, RPC_OUTPUT_DRAIN_MS) }; + }, + pipesClosed: finish, + failedToStart: () => { + if (phase.kind === "running" || phase.kind === "stopping") + unconfirmed("the peer omp did not start"); + }, + close: () => { + if (phase.kind === "running") stop("stdin"); + return result.promise; + }, + }; +} diff --git a/cli/test/fixtures/talk/unconfirmed-peer.ts b/cli/test/fixtures/talk/unconfirmed-peer.ts new file mode 100644 index 00000000..156617f9 --- /dev/null +++ b/cli/test/fixtures/talk/unconfirmed-peer.ts @@ -0,0 +1,41 @@ +/** Bun preload for the V6 failure control. Never pass it to either omp child. */ +import { mock, spyOn } from "bun:test"; +import * as shutdown from "../../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"; +import { ScriptedSession } from "../../../../.agents/skills/verify/scripts/smokeTalkTurns.ts"; + +const realShutdown = shutdown.peerShutdown; +let afterClose = false; +mock.module( + import.meta.resolve("../../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"), + () => ({ + ...shutdown, + peerShutdown(controls: shutdown.PeerControls): shutdown.PeerShutdown { + const peer = realShutdown(controls); + return { + ...peer, + async close() { + const result = await peer.close(); + if (result.kind !== "exited" || result.code !== 0) + throw new Error("the control requires a clean real peer exit"); + afterClose = true; + return { + kind: "unconfirmed", + reason: "fixture: peer exit was not confirmed after SIGKILL", + stderr: result.stderr, + }; + }, + }; + }, + }), +); + +const realCall = ScriptedSession.prototype.call; +spyOn(ScriptedSession.prototype, "call").mockImplementation(function ( + this: ScriptedSession, + name, + args, +) { + if (afterClose && args["action"] === "send") + throw new Error("unexpected sender probe after unconfirmed peer exit"); + return realCall.call(this, name, args); +}); diff --git a/cli/test/unit/verifySmokePeerShutdown.test.ts b/cli/test/unit/verifySmokePeerShutdown.test.ts new file mode 100644 index 00000000..be0494ff --- /dev/null +++ b/cli/test/unit/verifySmokePeerShutdown.test.ts @@ -0,0 +1,97 @@ +import { PassThrough } from "node:stream"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { peerShutdown } from "../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"; + +function fixture() { + const pipe = new PassThrough(); + let output = ""; + pipe.setEncoding("utf8").on("data", (text: string) => { + output += text; + }); + const endInput = vi.fn(); + const signal = vi.fn(); + const unref = vi.fn(); + const peer = peerShutdown({ + endInput, + signal, + unref, + release: () => { + pipe.destroy(); + return output; + }, + }); + return { peer, pipe, endInput, signal, unref }; +} + +describe("verification peer shutdown", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it("keeps the exit code and accepts buffered output across the final kill deadline", async () => { + const { peer, pipe, signal, unref } = fixture(); + const result = peer.close(); + await vi.advanceTimersByTimeAsync(29_999); + expect(signal.mock.calls).toEqual([["SIGTERM"], ["SIGKILL"]]); + peer.exited(47); + await vi.advanceTimersByTimeAsync(2); + pipe.write("buffered after exit"); + await vi.advanceTimersByTimeAsync(248); + expect(pipe.destroyed).toBe(true); + expect(await result).toEqual({ kind: "exited", code: 47, stderr: "buffered after exit" }); + expect(unref).not.toHaveBeenCalled(); + }); + + it("reports an unconfirmed exit at the final deadline even when a clean exit arrives later", async () => { + const { peer, pipe, unref } = fixture(); + const result = peer.close(); + pipe.write("last diagnostic"); + await vi.advanceTimersByTimeAsync(30_000); + const end = await result; + expect(end).toEqual({ + kind: "unconfirmed", + reason: "the peer omp exit was not confirmed after SIGKILL", + stderr: "last diagnostic", + }); + expect(pipe.destroyed).toBe(true); + expect(unref).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + peer.exited(0); + peer.pipesClosed(); + expect(await peer.close()).toBe(end); + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([0, null])( + "does not signal after observing exit %s while the pipes drain", + async (code) => { + const { peer, signal, endInput } = fixture(); + const first = peer.close(); + expect(peer.close()).toBe(first); + await vi.advanceTimersByTimeAsync(9_999); + peer.exited(code); + await vi.advanceTimersByTimeAsync(2); + peer.pipesClosed(); + expect(await first).toEqual({ kind: "exited", code, stderr: "" }); + expect(endInput).toHaveBeenCalledTimes(1); + expect(signal).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }, + ); + + it("does not treat missing pipes after spawn failure as an observed exit", async () => { + const { peer, endInput, signal } = fixture(); + peer.failedToStart(); + peer.pipesClosed(); + expect(await peer.close()).toEqual({ + kind: "unconfirmed", + reason: "the peer omp did not start", + stderr: "", + }); + expect(endInput).not.toHaveBeenCalled(); + expect(signal).not.toHaveBeenCalled(); + }); +}); From 9b145ef67e1c01f4c5ce39ff18b9e5e6c08ac6c2 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:04:26 -0300 Subject: [PATCH 2/3] Test shutdown through child events and retain the peer diagnostic Observe the sender without replacing its behavior. Check the last millisecond of the pipe drain and report signal termination without inventing an exit status. Verified: bun run test:unit cli/test/unit/verifySmokePeerShutdown.test.ts cli/test/unit/verifySmokeTalkTurns.test.ts cli/test/unit/verifySmokeScan.test.ts; bun run check:types; bun fmt --no-script --check cli/test/unit/verifySmokePeerShutdown.test.ts; isolated V6 talk and talk-ui with and without the unconfirmed-peer preload --- .agents/skills/verify/SKILL.md | 4 +- .agents/skills/verify/scripts/omp-smoke.ts | 33 +++++--------- .../verify/scripts/smokePeerShutdown.ts | 39 +++++++++++----- cli/test/fixtures/talk/unconfirmed-peer.ts | 9 ++-- cli/test/unit/verifySmokePeerShutdown.test.ts | 45 ++++++++++++------- 5 files changed, 76 insertions(+), 54 deletions(-) diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index 2e3ca1b3..96b97934 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -175,7 +175,7 @@ exit 0 | `closed-peer-not-live` | After the driver confirms the peer exited, the sender calls `send` with the instance id from `fork-list`. | The result reads `talk: the send failed: not-live`. Without a confirmed exit, the check fails without sending. | | `extensions-loaded`, `isolated`, `real-state` | The whole run; the warnings include the standard error of the peer | As in the `hooks` mode | | `sessions` | Both omp processes | The sender exits 0 after its last turn. The peer exits 0 after its stdin ends. | -| `registry` | The peer from its start and the sender from its start; the script reads the result after `talk-offered`, while both wait. The peer again from the new session id of each `new_session` and `fork`, apart from the list step. The final scan of the peer before its stdin ends, and of the sender before its last turn. | As in the `hooks` mode, for each of the two processes, with the work folder of the run as `cwd`. After a session change, the valid private entry also has the new session id, and its instance id is the instance id of the list. Each final scan finds no entry of the registrations of its process in the default folder. When a check before it fails and no final scan found a problem, this line reads `not run`. | +| `registry` | The peer from its start and the sender from its start; the script reads the result after `talk-offered`, while both wait. The peer again from the new session id of each `new_session` and `fork`, apart from the list step. The final scan of the peer before its stdin ends, and of the sender before its last turn. | As in the `hooks` mode, for each of the two processes, with the work folder of the run as `cwd`. After a session change, the valid private entry also has the new session id, and its instance id is the instance id of the list. Each final scan finds no entry of the registrations of its process in the default folder. An earlier failure can leave this check `not run`. A later failure does not reset a completed check. | | `registry-removed` | After the cleanup | The registry folder does not exist. | A failed scenario check stops the scenario. Each scenario line after it prints `FAIL : not run, because an earlier check failed`. The lines from `extensions-loaded` on run in each case, except `registry`, which needs `talk-offered`. @@ -286,7 +286,7 @@ The other lines are as above. talk is off on this omp and registers no session, | `FAIL talk-offered: the first fixture turn of the took more than 30 s` | The responder did not identify an opening prompt before the deadline. It did not inspect that turn's tool list. | Check whether omp sent the prompt. If it did, compare its message format with `latestEvent` in `smokeTalkTurns.ts`. | | `FAIL talk-offered: the first fixture turn of the does not offer the talk tool` | The named process sent its opening turn without `talk` in the tool list. | Check `extensions-loaded`. If the extension loaded, check tool registration and whether omp offers `talk` as a provider tool instead of a Bash command. | | V6 `talk` prints `the call talk-sender- took more than 30 s` | The driver did not receive a matching completion before the deadline. The message alone does not say whether a tool result arrived. | Check whether the tool ran and returned. If it did, check the call ID and the latest event. Run `bun run test:unit cli/test/unit/verifySmokeTalkTurns.test.ts`. | -| `talk` or `talk-ui` reports `the peer omp exit was not confirmed after SIGKILL` | The final 10 s wait ended without a peer exit event. A closed socket does not prove exit. | Check the peer's shutdown. To reproduce the reporting path without leaving a process running, repeat V6 with `bun --preload ./cli/test/fixtures/talk/unconfirmed-peer.ts` in place of `bun`. Both modes must fail `sessions`; `talk` must also fail `closed-peer-not-live`. | +| `talk` or `talk-ui` reports `the peer omp exit was not confirmed after SIGKILL` | The final 10 s wait ended without an exit event. A closed socket does not prove exit. | Repeat V6 with `bun --preload ./cli/test/fixtures/talk/unconfirmed-peer.ts` in place of `bun`. Require exit 1 and `FAIL sessions: fixture: peer exit was not confirmed after SIGKILL` followed by the stderr excerpt. For `talk`, also require `FAIL closed-peer-not-live: fixture: peer exit was not confirmed after SIGKILL`. All other checks must pass. Reject any `fixture: attempted post-close send` on stderr. | | V6 `talk` reports another failure in `talk-`, `new-session-`, `fork-`, or `closed-peer-` | The step name identifies where the driver stopped, not which operation failed. | Read the reason after the step name. Check the named RPC command, tool result, or fixture operation. | | V6 `talk` prints `FAIL handover-refused` | A print session did not refuse the `handover` action before its side turn: the result has no refusal, the fake model got a side-turn request with the handover template, the peer holds the note or a handover entry, or the call took more than 30 s because a flow opened in a session without a terminal | Check the refusals of `handoverFlow` in `cli/talk/extension.ts` and `runHandover` in `cli/talk/tool/tool.ts` (#260 H3) | | V6 `talk-ui` prints `FAIL ui-ready` or `FAIL old-omp` with `footer with the model name` | The TUI omp did not start in the pseudo-terminal, for example because it shows the setup wizard | Read the screen text in the reason. Check `startup.setupWizard` in the isolated `config.yml` and the omp version (V2) | diff --git a/.agents/skills/verify/scripts/omp-smoke.ts b/.agents/skills/verify/scripts/omp-smoke.ts index 1f97657f..1fc24cf8 100755 --- a/.agents/skills/verify/scripts/omp-smoke.ts +++ b/.agents/skills/verify/scripts/omp-smoke.ts @@ -70,7 +70,12 @@ import { TalkPosixSystem, TalkTrustError, } from "../../../../cli/talk/transport/trustPosix.ts"; -import { PEER_CLOSE_MS, peerShutdown, type PeerResult } from "./smokePeerShutdown.ts"; +import { + PEER_CLOSE_MS, + peerSessionFailure, + peerShutdown, + type PeerResult, +} from "./smokePeerShutdown.ts"; import { type Attribution, decodeAttribution, @@ -2092,9 +2097,7 @@ interface RpcStart { } /** - * Starts omp in RPC mode. The handle comes at spawn, apart from the ready line, so a mode records the process - * before it waits: a peer that exits or stalls before its ready line still gets its final scan, its close, and - * its exit result. + * Returns the peer handle before readiness so both modes can scan and close it even if startup stalls. */ function startRpcOmp( argv: readonly string[], @@ -2109,7 +2112,7 @@ function startRpcOmp( const waiting = new Map>(); const ready = Promise.withResolvers(); const output = createInterface({ input: child.stdout }); - const shutdown = peerShutdown({ + const shutdown = peerShutdown(child, { endInput: () => child.stdin.end(), signal: (signal) => child.kill(signal), unref: () => child.unref(), @@ -2152,8 +2155,6 @@ function startRpcOmp( ); else reply.resolve(message["data"] ?? null); }); - child.once("exit", shutdown.exited); - child.once("close", shutdown.pipesClosed); const send = (rpcCommand: JsonObject): Promise => { if (ended) return Promise.reject(new Error("the peer omp has ended")); @@ -2170,12 +2171,6 @@ function startRpcOmp( }; } -function peerSessionFailure(result: PeerResult | null, excerpt: (stderr: string) => string): string { - if (result === null) return "the peer omp did not run"; - if (result.kind === "unconfirmed") return result.reason; - return result.code === 0 ? "" : `the peer omp exited ${result.code}: ${excerpt(result.stderr)}`; -} - /** * Copies the kit plugin folder, with the shipped `talk.js` and its manifest entry, to the scratch folder. * Returns the copy, which omp links. The copy keeps each symbolic link as it is, so a relative link does not @@ -2409,8 +2404,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> reportRegistry(); }; try { - // The peer: omp in RPC mode. Its first provider turn answers the driver's prompt. The mode holds its handle - // before the ready line, so a peer that ends or stalls first still gets its final scan and its exit result. + // The peer's first provider turn answers the driver's prompt. const started = startRpcOmp( ["--mode", "rpc", "--model", `${MODEL_PROVIDER}/${PEER_MODEL_ID}`, "--no-title"], run.workDir, @@ -2755,9 +2749,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> results.set(step, error instanceof Error ? error.message : String(error)); } - // The sender ends after its next turn, and a slow peer turn that still waits ends; a sender that still - // waits in a tool call is stopped. After a failed step, the peer ends here too; a peer that exited or stalled - // before its ready line is still open here, so it gets its final scan and its exit result as well. + // Finish any pending turns. After a failed step, scan the peer before closing its handle. await finalScan(senderAttributed); sender.finish(); peerModel.release(); @@ -3198,8 +3190,7 @@ class TerminalOmp { } /** - * One omp process of a talk mode: not started, open while the driver holds a handle to close (whether or not the - * process passed its readiness check), or closed with its exit result. + * An open handle needs cleanup even before readiness. A closed handle has a shutdown result, not proof of exit. */ type FixtureProcess = | { readonly kind: "absent" } @@ -3858,8 +3849,6 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null await screen.waitFor(UI_READY_TEXT, 0, "footer with the model name"); if (checks === OLD_OMP_CHECKS) await oldOmpFlow(screen); else { - // The mode holds the peer handle before the ready line, so a peer that ends or stalls first still gets its - // final scan and its exit result. const started = startRpcOmp( ["--mode", "rpc", "--model", `${MODEL_PROVIDER}/${PEER_MODEL_ID}`, "--no-title"], run.workDir, diff --git a/.agents/skills/verify/scripts/smokePeerShutdown.ts b/.agents/skills/verify/scripts/smokePeerShutdown.ts index 7e71c593..7957a239 100644 --- a/.agents/skills/verify/scripts/smokePeerShutdown.ts +++ b/.agents/skills/verify/scripts/smokePeerShutdown.ts @@ -6,6 +6,26 @@ export type PeerResult = | { readonly kind: "exited"; readonly code: number | null; readonly stderr: string } | { readonly kind: "unconfirmed"; readonly reason: string; readonly stderr: string }; +function exitReason(code: number | null): string { + return code === null ? "a signal terminated the peer omp" : `the peer omp exited ${code}`; +} + +export function peerSessionFailure( + result: PeerResult | null, + excerpt: (stderr: string) => string, +): string { + if (result === null) return "the peer omp did not run"; + if (result.kind === "exited" && result.code === 0) return ""; + const reason = result.kind === "unconfirmed" ? result.reason : exitReason(result.code); + const detail = excerpt(result.stderr); + return detail ? `${reason}: ${detail}` : reason; +} + +interface PeerEvents { + once(event: "exit", listener: (code: number | null) => void): unknown; + once(event: "close", listener: () => void): unknown; +} + export interface PeerControls { readonly endInput: () => void; readonly signal: (signal: "SIGTERM" | "SIGKILL") => void; @@ -15,8 +35,6 @@ export interface PeerControls { } export interface PeerShutdown { - readonly exited: (code: number | null) => void; - readonly pipesClosed: () => void; readonly failedToStart: () => void; readonly close: () => Promise; } @@ -27,7 +45,7 @@ type Phase = | { readonly kind: "draining"; readonly timer: NodeJS.Timeout; readonly code: number | null }; /** Deadlines for sending signals stop at exit, even if a descendant holds the output pipes. */ -export function peerShutdown(controls: PeerControls): PeerShutdown { +export function peerShutdown(events: PeerEvents, controls: PeerControls): PeerShutdown { let phase: Phase = { kind: "running" }; const result = Promise.withResolvers(); @@ -43,7 +61,7 @@ export function peerShutdown(controls: PeerControls): PeerShutdown { result.resolve({ kind: "exited", code, - stderr: controls.release(`the peer omp exited ${code}`), + stderr: controls.release(exitReason(code)), }); } @@ -65,13 +83,14 @@ export function peerShutdown(controls: PeerControls): PeerShutdown { else controls.signal(stage); } + events.once("exit", (code) => { + if (phase.kind === "done" || phase.kind === "draining") return; + clearDeadline(); + phase = { kind: "draining", code, timer: setTimeout(finish, RPC_OUTPUT_DRAIN_MS) }; + }); + events.once("close", finish); + return { - exited: (code) => { - if (phase.kind === "done" || phase.kind === "draining") return; - clearDeadline(); - phase = { kind: "draining", code, timer: setTimeout(finish, RPC_OUTPUT_DRAIN_MS) }; - }, - pipesClosed: finish, failedToStart: () => { if (phase.kind === "running" || phase.kind === "stopping") unconfirmed("the peer omp did not start"); diff --git a/cli/test/fixtures/talk/unconfirmed-peer.ts b/cli/test/fixtures/talk/unconfirmed-peer.ts index 156617f9..b9a17aaa 100644 --- a/cli/test/fixtures/talk/unconfirmed-peer.ts +++ b/cli/test/fixtures/talk/unconfirmed-peer.ts @@ -9,8 +9,8 @@ mock.module( import.meta.resolve("../../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"), () => ({ ...shutdown, - peerShutdown(controls: shutdown.PeerControls): shutdown.PeerShutdown { - const peer = realShutdown(controls); + peerShutdown(...args: Parameters): shutdown.PeerShutdown { + const peer = realShutdown(...args); return { ...peer, async close() { @@ -21,7 +21,7 @@ mock.module( return { kind: "unconfirmed", reason: "fixture: peer exit was not confirmed after SIGKILL", - stderr: result.stderr, + stderr: result.stderr || "fixture shutdown diagnostic", }; }, }; @@ -35,7 +35,6 @@ spyOn(ScriptedSession.prototype, "call").mockImplementation(function ( name, args, ) { - if (afterClose && args["action"] === "send") - throw new Error("unexpected sender probe after unconfirmed peer exit"); + if (afterClose && args["action"] === "send") console.error("fixture: attempted post-close send"); return realCall.call(this, name, args); }); diff --git a/cli/test/unit/verifySmokePeerShutdown.test.ts b/cli/test/unit/verifySmokePeerShutdown.test.ts index be0494ff..1c5a6e0a 100644 --- a/cli/test/unit/verifySmokePeerShutdown.test.ts +++ b/cli/test/unit/verifySmokePeerShutdown.test.ts @@ -1,6 +1,10 @@ +import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { peerShutdown } from "../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"; +import { + peerSessionFailure, + peerShutdown, +} from "../../../.agents/skills/verify/scripts/smokePeerShutdown.ts"; function fixture() { const pipe = new PassThrough(); @@ -11,7 +15,8 @@ function fixture() { const endInput = vi.fn(); const signal = vi.fn(); const unref = vi.fn(); - const peer = peerShutdown({ + const events = new EventEmitter(); + const peer = peerShutdown(events, { endInput, signal, unref, @@ -20,7 +25,7 @@ function fixture() { return output; }, }); - return { peer, pipe, endInput, signal, unref }; + return { peer, events, pipe, endInput, signal, unref }; } describe("verification peer shutdown", () => { @@ -32,21 +37,21 @@ describe("verification peer shutdown", () => { }); it("keeps the exit code and accepts buffered output across the final kill deadline", async () => { - const { peer, pipe, signal, unref } = fixture(); + const { peer, events, pipe, signal, unref } = fixture(); const result = peer.close(); await vi.advanceTimersByTimeAsync(29_999); expect(signal.mock.calls).toEqual([["SIGTERM"], ["SIGKILL"]]); - peer.exited(47); - await vi.advanceTimersByTimeAsync(2); + events.emit("exit", 47); + await vi.advanceTimersByTimeAsync(249); pipe.write("buffered after exit"); - await vi.advanceTimersByTimeAsync(248); + await vi.advanceTimersByTimeAsync(1); expect(pipe.destroyed).toBe(true); expect(await result).toEqual({ kind: "exited", code: 47, stderr: "buffered after exit" }); expect(unref).not.toHaveBeenCalled(); }); it("reports an unconfirmed exit at the final deadline even when a clean exit arrives later", async () => { - const { peer, pipe, unref } = fixture(); + const { peer, events, pipe, unref } = fixture(); const result = peer.close(); pipe.write("last diagnostic"); await vi.advanceTimersByTimeAsync(30_000); @@ -59,8 +64,8 @@ describe("verification peer shutdown", () => { expect(pipe.destroyed).toBe(true); expect(unref).toHaveBeenCalledTimes(1); await vi.advanceTimersByTimeAsync(1); - peer.exited(0); - peer.pipesClosed(); + events.emit("exit", 0); + events.emit("close", 0); expect(await peer.close()).toBe(end); expect(vi.getTimerCount()).toBe(0); }); @@ -68,13 +73,13 @@ describe("verification peer shutdown", () => { it.each([0, null])( "does not signal after observing exit %s while the pipes drain", async (code) => { - const { peer, signal, endInput } = fixture(); + const { peer, events, signal, endInput } = fixture(); const first = peer.close(); expect(peer.close()).toBe(first); await vi.advanceTimersByTimeAsync(9_999); - peer.exited(code); + events.emit("exit", code); await vi.advanceTimersByTimeAsync(2); - peer.pipesClosed(); + events.emit("close", code); expect(await first).toEqual({ kind: "exited", code, stderr: "" }); expect(endInput).toHaveBeenCalledTimes(1); expect(signal).not.toHaveBeenCalled(); @@ -83,9 +88,9 @@ describe("verification peer shutdown", () => { ); it("does not treat missing pipes after spawn failure as an observed exit", async () => { - const { peer, endInput, signal } = fixture(); + const { peer, events, endInput, signal } = fixture(); peer.failedToStart(); - peer.pipesClosed(); + events.emit("close", null); expect(await peer.close()).toEqual({ kind: "unconfirmed", reason: "the peer omp did not start", @@ -94,4 +99,14 @@ describe("verification peer shutdown", () => { expect(endInput).not.toHaveBeenCalled(); expect(signal).not.toHaveBeenCalled(); }); + + it("reports signal termination without inventing an exit status", async () => { + const { peer, events, pipe } = fixture(); + pipe.write("last output"); + events.emit("exit", null, "SIGTERM"); + events.emit("close", null, "SIGTERM"); + expect(peerSessionFailure(await peer.close(), (s) => s)).toBe( + "a signal terminated the peer omp: last output", + ); + }); }); From 448d443ac153e4ccb101c41400d35dea35d263a9 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:07:13 -0300 Subject: [PATCH 3/3] Keep the shutdown control visible after whitespace-only stderr Append the fixture diagnostic without dropping real output. Both the full-output and tail-only formatters now receive a nonblank excerpt. Verified: four preload cases with both excerpt policies; bun run test:unit cli/test/unit/verifySmokePeerShutdown.test.ts cli/test/unit/verifySmokeTalkTurns.test.ts cli/test/unit/verifySmokeScan.test.ts; bun run check:types; isolated V6 talk and talk-ui, normal and unconfirmed --- cli/test/fixtures/talk/unconfirmed-peer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/test/fixtures/talk/unconfirmed-peer.ts b/cli/test/fixtures/talk/unconfirmed-peer.ts index b9a17aaa..d8de59d8 100644 --- a/cli/test/fixtures/talk/unconfirmed-peer.ts +++ b/cli/test/fixtures/talk/unconfirmed-peer.ts @@ -21,7 +21,7 @@ mock.module( return { kind: "unconfirmed", reason: "fixture: peer exit was not confirmed after SIGKILL", - stderr: result.stderr || "fixture shutdown diagnostic", + stderr: `${result.stderr}\nfixture shutdown diagnostic`, }; }, };