Repository navigation
Description
Epic: graph-2026-10-consolidation Tier: judgment Execution: sequant_run
- Blocked by: tracker: graph-2026-10-consolidation — one definition per helper for the 16 duplicate groups the accretion audit found at ad71b341 #1470
- Blocked by: refactor(logs): one run-log module — parseLogFile, listLogFiles, resolveLogDir, formatDuration defined once #1471
Problem
killProcessGroup is defined three times: byte-identical in src/lib/workflow/drivers/codex.ts:774 and drivers/opencode.ts:880 (SIGTERM the group, fall back to the leader), and a third shape in src/mcp/tools/run.ts:1068 that takes the child process and escalates to SIGKILL after SIGKILL_GRACE_MS (#1222). pushLines(buffer: RingBuffer, text) is byte-identical in both drivers. This is the deferral clause "AsyncSubprocess abstraction — until multiple subsystems need shared process lifecycle" in docs/internal/architecture-target.md: the accretion trigger async_subprocess has read fired since 2026-09-08 (fire fcc45c51e344aabb in the live ledger), and three copies is the observed count.
Acceptance Criteria
- AC-1: One
killProcessGroupand onepushLinesexist in non-testsrc/. Evidence:rg -l 'function killProcessGroup\(' src -g '!*.test.ts' | wc -l; rg -l '^\s*(export )?function pushLines\(|^\s+pushLines\(text: string\)' src/lib/workflow -g '!*.test.ts' | wc -l→1then1. - AC-2: The shared helper takes the
ChildProcess, sends SIGTERM to its group first, swallows ESRCH, falls back to a direct kill on other errors, escalates to SIGKILL after the caller'sgraceMsunless the child has already exited, and is idempotent per child (D-1). Evidence:npx vitest run src/lib/process-group.integration.test.ts→ ≥ 4 passed, 0 failed (real detached children, skipped on win32:bash -c 'trap "" TERM; sleep 30'closes withsignalCodeSIGKILL under a 200 ms grace;sleep 30exits on SIGTERM with no SIGKILL sent; a child that already exited gets no signal; two calls on one child send one SIGTERM). - AC-2b: An escalated kill still reports as a timeout in both driver evaluators. Evidence:
npx vitest run src/lib/workflow/drivers/codex.test.ts src/lib/workflow/drivers/opencode.test.ts -t "timeout"→ ≥ 4 passed, 0 failed (the existing497 AC-3 a SIGTERM close is reported as a timeoutcases plus one per driver where the close signal is SIGKILL and the helper reportedrequested: true). - AC-3: Both drivers and the MCP tool import the shared helper,
run.tsstill exportsSIGKILL_GRACE_MS, and the existing kill tests pass unchanged. Evidence:rg -l 'process-group\.js' src/lib/workflow/drivers/codex.ts src/lib/workflow/drivers/opencode.ts src/mcp/tools/run.ts | wc -l→3;rg -c 'export const SIGKILL_GRACE_MS' src/mcp/tools/run.ts→1;npx vitest run src/lib/workflow/drivers/codex.test.ts src/lib/workflow/drivers/opencode.test.ts src/mcp/tools/run.test.ts→ 0 failed. - AC-4: The deferral clause stops firing (must run against the real dependency). Evidence:
ACCRETION_HOME=$(mktemp -d) node ~/Projects/accretion-audit/dist/cli.js triggers --repo "$PWD" --config ~/Projects/accretion-audit/dogfood/sequant.triggers.json --offline --json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const r=JSON.parse(s).results.find(x=>x.id==='async_subprocess');console.log(r.status);process.exit(r.status==='not_fired'?0:1)})"→not_fired, exit 0 (today:fired,3 files >= 2; the command is read-only, the temp home is for uniformity with the other accretion ACs).
Prior fixes / producers
- Prior fixes: MCP server: replace spawnSync with async spawn for sequant_run #388 (spawnSync → spawn, first copy), MCP: add progress notifications for sequant_run with graceful fallback #435, feat: add opencode agent driver — first backend that can inherit the full skill methodology #862 (opencode copy), feat: add OpenAI Codex CLI agent driver #497 (codex copy), fix(run): a watchdog-killed run writes no run log and half-deletes a clean worktree — worktree removal outruns the 5 s SIGKILL grace #1222 (SIGKILL grace on the MCP copy only). Four fixes, one of which reached one copy of three: this is a class, so the ACs state the outcome for every caller.
- Producers of "kill this subprocess tree": three (above). The containment issues fix(containment): a phase agent killed its own orchestrator — no Bash signal guard, no process-group isolation, machine re-prompts read as human consent #934 and Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856 are about who sends the signal and when, not about the helper; they stay open and gain one call site to reason about instead of three.
- Owner gate OQ-1 (graph §9): SIGKILL escalation for the drivers, default yes. If no,
graceMsis optional and absent means no escalation; AC-2 keeps its cases with the drivers' call omitting the grace. - The escalation grace in
run.tsisDEFAULT_FORCE_EXIT_TIMEOUT_MS + 1000because its child is asequant runwith a 10 s force-exit (fix(run): a watchdog-killed run writes no run log and half-deletes a clean worktree — worktree removal outruns the 5 s SIGKILL grace #1222). The drivers' children have no such contract: give them their own constant, do not reuse the MCP value by import.
May touch
src/lib/process-group.ts (new) and its test, src/lib/workflow/ring-buffer.ts, src/lib/workflow/drivers/codex.ts, src/lib/workflow/drivers/opencode.ts, src/mcp/tools/run.ts, their tests, the changelog entry. Not docs/internal/architecture-target.md: the trigger's quoted clause must stay byte-identical for AC-4 (graph doc records the satisfaction, D-4). Serialize after #1471 (mcp/tools/run.ts).
Non-Goals
- The AsyncSubprocess abstraction itself, async spawn wrappers, or anything in arch: async I/O modernization — unblock true parallel execution #506's scope.
src/lib/workflow/drivers/aider.ts: it spawns withoutdetachedand callsproc.kill("SIGTERM"); a group kill there would signal the orchestrator's own group. It stays as is.- Process-group isolation of phase agents (fix(containment): a phase agent killed its own orchestrator — no Bash signal guard, no process-group isolation, machine re-prompts read as human consent #934) or the 106 s watchdog (Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856).
- Any edit under
plugin/,.claude/skills/ortemplates/skills/(I-1).
Activity
admarble commentedon Oct 19, 2026
Runner context, 2026-10-19, before launch (consolidation W2, beside #1473; judgment tier, all phases on Opus; stop-at-PR). main = ec9d583.
Changed since filing:
src/mcp/tools/run.tsnow importsresolveLogDirfromsrc/lib/run-logs.ts(refactor(logs): one run-log module — parseLogFile, listLogFiles, resolveLogDir, formatDuration defined once #1471, 1423db8).The kill-helper work must keep both. refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473 runs at the same time; its files don't include
run.tsor the drivers.For every phase, and the qa phase by name: run the full suite at most once, in the foreground, under
timeout, after a WIP commit. Each MCP-dispatched phase has a 30-minute wall, and this wave runs 7 issues at once. Prefer the targetednpx vitest run <files>for the ACs.CHANGELOG: add
[Unreleased]lines, notchangelog.d/fragments. #1370 has not merged.Freeze: nothing under
plugin/,.claude/skills/ortemplates/skills/.Health baseline: if this PR changes a measured metric, regenerate
scripts/qa/health-baseline.jsonwithnpx tsx scripts/qa/health-report.ts --write-baselineafter the last source change. Never hand-edit it.npm run lint:healthmust print "no metric rose".admarble commentedon Oct 19, 2026
Complexity: Complex (5 ACs, 3 directories —
refactorlabel)AC Quality Check
Every AC is one line and has an
Evidence:clause. I ran each command-shaped Evidence againstmain(ec9d583):3,24 passed | 91 skipped-t "timeout"already passes 4 tests across the two files today, so "≥ 4 passed" holds with no change. Tighten it to ≥ 6 passed, or name the two new SIGKILL cases in the-tfilter. Also, opencode's existing case is named862 AC-1 reports a SIGTERM close as a timeout, not497 AC-3 …. The filter still finds it.0,1, suite greenfired(3 files ≥ 2)(function|const)\s+killProcessGroup\boversrc/minus tests. A driver-local alias written asconst killProcessGroup = …would keep it firing. The existingconst killGroup = …is fine.A hidden constraint in AC-1's regex:
^\s+pushLines\(text: string\)matches only a method whose parameter list is exactly(text: string). The per-line cap (TAIL_LINE_CHARS = 2000, a driver constant) therefore can't be a second parameter. It has to go to the constructor:new RingBuffer(TAIL_LINES, { maxLineChars: TAIL_LINE_CHARS }).Scope Assessment
Non-Goals: present (AsyncSubprocess abstraction / #506,
aider.ts, #934 / #856, the plugin/skills freeze).src/lib,src/lib/workflow{,/drivers},src/mcp/tools)Verdict: ✅ SCOPE_OK
Dependencies: #1471 is CLOSED (merged as 1423db8). #1470 is the graph tracker; it stays open by design and doesn't block this. In flight: the #1472 worktree is at main with no diff. #1473 doesn't touch these files. No conflict.
Acceptance Criteria
AC-1: One
killProcessGroupand onepushLinesin non-testsrc/Verification: Integration Test (rg counts)
Scenario: Given the three helper copies and the two
pushLinescopies → When the copies are collapsed → Thenrgreturns1/1.Assumptions:
pushLinesbecomesRingBuffer.pushLines(text: string)and takes no other parameters. The cap goes through the constructor.AC-2: Shared helper semantics, with real detached children
Verification: Integration Test (
src/lib/process-group.integration.test.ts, which theintegrationproject runs,describe.skipIf(win32))Scenario: Given a real
spawn(..., { detached: true })child → WhenkillProcessGroup(child, { graceMs: 200 })runs → Then:signalCode === "SIGKILL"sleep 30closes on SIGTERM and no SIGKILL is sentAssumptions:
child.exitCode != null || child.signalCode != null. Use loose!=: the driver mocks have neither property (undefined), and a strict check would treat them as exited and break the existing abort tests.child.on("close", …), notonce. The mock'sonis avi.fnand the mock has noonce.WeakSet<ChildProcess>.process.killwhile still passing through to the real one.AC-2b: SIGKILL after a requested kill reports as a timeout in both evaluators
Verification: Unit Test (
evaluateCodexRun/ the opencode evaluator)Scenario: Given
{ signal: "SIGKILL", killRequested: true }→ When evaluated → ThenTimeout after Ns. A SIGKILL withkillRequestedfalse or absent still readsProcess killed by signal: SIGKILL.Assumptions: Add
killRequested?: booleantoCodexRunOutcomeand to the opencode outcome. The driver sets it from the helper's return value{ requested }.AC-3: All three callers import the helper,
SIGKILL_GRACE_MSis still exported, and existing tests pass unchangedVerification: Integration Test (rg + the three test files)
Scenario: Given the refactor → When the three suites run → Then 0 failures and no edits to the existing kill assertions (
[-5150, "SIGTERM"],proc.killnot called, the #1222 grace test).Assumptions:
run.tscallskillProcessGroup(proc, { graceMs: SIGKILL_GRACE_MS })and keeps the constant and its #1222 comment.AC-4: The
async_subprocesstrigger readsnot_firedVerification: Integration Test (the accretion CLI against the real repo)
Scenario: Given one definition file → When
triggers --offlineruns → Thennot_fired, exit 0.Assumptions:
docs/internal/architecture-target.mdis untouched, and~/Projects/accretion-audit/dist/cli.jsexists (it does).Implementation Plan
Phase 1: Shared primitives
src/lib/process-group.ts(new): exportkillProcessGroup(child: ChildProcess, opts: { graceMs?: number } = {}): { requested: boolean }.{ requested: false }if the child already exited or its pid is undefined.WeakSet, return{ requested: true }without signalling.process.kill(-pid, "SIGTERM"), swallow ESRCH, and fall back toprocess.kill(pid, "SIGTERM")on other errors (this is the drivers' fallback, kept verbatim).graceMsis set, register anon("close")flag and an.unref()'d timer that sends SIGKILL the same way unless the child has closed.graceMsabsent there is no escalation (OQ-1's "no" branch keeps working).src/lib/workflow/ring-buffer.ts: add an optional{ maxLineChars }constructor option and apushLines(text: string)method. It splits on\n, skips empty lines, and caps each line as${slice}… [N chars]. The capped form is byte-identical to today's.Phase 2: Callers
drivers/codex.tsanddrivers/opencode.ts:killProcessGroupandpushLines.{ maxLineChars: TAIL_LINE_CHARS }.const killGroup = () => { if (killProcessGroup(proc, { graceMs: DRIVER_SIGKILL_GRACE_MS }).requested) killRequested = true; }.killRequestedinto the evaluator's outcome and widenisTimeouttosignal === "SIGTERM" || (signal === "SIGKILL" && outcome.killRequested === true).process-group.tsasexport const DRIVER_SIGKILL_GRACE_MS = 5000, or define it in each driver file. Recommendprocess-group.ts, so there's one definition and the drivers don't diverge.src/mcp/tools/run.ts:killProcessGroupandsendSignal, and import the helper.{ graceMs: SIGKILL_GRACE_MS }at all four call sites.resolveLogDirimport (refactor(logs): one run-log module — parseLogFile, listLogFiles, resolveLogDir, formatDuration defined once #1471) and the fix(mcp): sequant_run reports another run's issues and verdict when its own run log is missing — a runId lookup miss falls back to the time window #1515 runId-miss fallback.process.kill(pid)where it usedproc.kill(), and repeated calls (a timeout racing an abort) stop scheduling duplicate SIGKILL timers.Phase 3: Tests, changelog, health
src/lib/process-group.integration.test.tswith cases (a) to (d) from AC-2.RingBuffer.pushLinesunit cases toring-buffer.test.ts(capping, skipping empty lines, eviction).killRequestedevaluator case to each driver test, and one negative case (SIGKILL without a request is not a timeout).[Unreleased]line (not achangelog.d/fragment).npx tsx scripts/qa/health-report.ts --write-baselineafter the last source change if a metric moved, then confirmnpm run lint:healthprints "no metric rose".timeout, after a WIP commit.Design Review
src/lib/process-group.ts, a leaf module with no imports frommcp/orworkflow/. Drivers and MCP both depend downward on it.pushLinesbelongs onRingBuffer, which already owns the line tail.ProcessGroupclass or handle object, which is the AsyncSubprocess abstraction and a Non-Goal; (b) puttingkillRequestedtracking inside the helper with awasKillRequested(child)query. That's global state the evaluator would reach into, while the driver-local flag stays pure. (c) Anopts.maxCharsargument onpushLines, which AC-1's regex forbids.git log -S killProcessGroupshows MCP server: replace spawnSync with async spawn for sequant_run #388, MCP: add progress notifications for sequant_run with graceful fallback #435, feat: add opencode agent driver — first backend that can inherit the full skill methodology #862, feat: add OpenAI Codex CLI agent driver #497 and Upstream: Claude Code v2.1.286 Assessment #1414's harness, plus fix(run): a watchdog-killed run writes no run log and half-deletes a clean worktree — worktree removal outruns the 5 s SIGKILL grace #1222 on one copy only. That's ≥2 prior fixes, and this issue is the class fix: it collapses all three producers, so it isn't precedent for a fourth. No divergence.requested: true, is that right?" Yes: a kill was requested for that child.WeakSetis global." It's keyed by object identity, so there's no leak and no cross-child bleed.codex.ts:774,opencode.ts:880,run.ts:1076(+sendSignal). After this change there is one.aider.ts'sproc.kill("SIGTERM")is excluded by Non-Goal.pushLinesproducers:codex.ts:757andopencode.ts:788, collapsing to one.evaluateCodexRun(codex.ts:411) and the opencode evaluator (opencode.ts:452). Both are updated together, with a test per driver.SIGKILL_GRACE_MSis consumed byrun.test.ts:1139, unchanged.Feature Quality Planning
All standard checks pass. Notable items:
!= nullfor exit detection,onrather thanonce, andprocess.kill(which the tests spy on) for every signal. Never usechild.kill()in the helper: the codex test assertsproc.killis not called..unref()on the grace timer so a stuck child can't hold the event loop open.run.tssends SIGKILL even if the child closed before the kill call (itscloselistener is registered too late). The already-exited check closes that window.process.kill(-pid)throws a non-ESRCH error there and falls through to the direct kill, which is the same as today. The integration test skips on win32.Derived ACs
Process killed by signal: SIGKILLin both evaluators (Evidence: the negative case in step 7)RingBuffer.pushLinesoutput for a >2000-char line is byte-identical to the old driver form (Evidence:ring-buffer.test.ts)Open Questions
DRIVER_SIGKILL_GRACE_MS = 5000, defined inprocess-group.ts. Impact if no: the drivers omitgraceMs, and AC-2b's new cases become dead paths.≥ 6 passed(it passes 4 today). Impact if left as is: QA can't tell a missing SIGKILL case from a present one.process-group.ts. Impact: if it's defined per driver, the two values can drift.Recommended Workflow
Phases: spec → testgen → exec → qa
Quality Loop: enabled
Reasoning: This is a
refactorwith three callers and a semantic change (escalation plus timeout classification), so the quality loop is on. AC-2 and AC-2b are Integration/Unit-verified with declared Evidence (npx vitest run src/lib/process-group.integration.test.ts, the driver-t "timeout"run), so testgen should stub the four real-child cases and the two SIGKILL evaluator cases before implementation.Label Review
Current: refactor, graph-2026-10-consolidation
Recommended: + planned
Reason: The labels already match the scope. No UI files are involved.
Quality Loop: enabled explicitly (the
refactorlabel).admarble commentedon Oct 19, 2026
Test Stubs Generated
rgEvidence)killRequested)RingBuffer.pushLines)Files
src/lib/process-group.integration.test.ts(new,describe.skipIf(win32))src/lib/workflow/ring-buffer.test.ts(new)src/lib/workflow/drivers/codex.test.ts,opencode.test.ts(appended AC-2b blocks; test names contain "timeout" so the-t "timeout"filter picks them up)All stubs throw
Test stub - implement this test, so the appended driver suites go red until/execfills them in.Per the /spec AC quality check, AC-2b's
-t "timeout"evidence passes 4 tests today. With these 4 new stubs the target is >= 8 passed.Next steps:
/exec 1472, then fill the stubs and run the targeted vitest files.admarble commentedon Oct 19, 2026
Correction to the runner context above (health baseline), 2026-10-19:
scripts/qa/health-baseline.jsononly to record a metric that went down.npm run lint:healthreports a metric rose (for examplefunctions.longest.linesoremptyCatch.total), do not regenerate to make it pass. Restructure so the metric holds: put new logic in a new small function instead of growing an existing long one.admarble commentedon Oct 19, 2026
QA Verdict: AC_MET_BUT_NOT_A_PLUS
AC coverage: 4/4 met
Gaps:
phases.qa.agentas the independence knob #1521) in the generated health baseline, so the required test check never ranSuggestions:
trapto install. That is a small flake risk on a loaded CI runner.main(4 tests already match there). The real count is 10, but the owner may want to edit the AC text to "≥ 6".chore(#1472): baseline records emptyCatch 118 and absorbs proseGate.l…