Skip to content

refactor(drivers,mcp): one killProcessGroup(child, { graceMs }) with SIGKILL escalation; pushLines on RingBuffer (closes the AsyncSubprocess trigger) #1472

Closed

Description

@admarble

Epic: graph-2026-10-consolidation Tier: judgment Execution: sequant_run

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 killProcessGroup and one pushLines exist in non-test src/. 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 → 1 then 1.
  • 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's graceMs unless 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 with signalCode SIGKILL under a 200 ms grace; sleep 30 exits 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 existing 497 AC-3 a SIGTERM close is reported as a timeout cases plus one per driver where the close signal is SIGKILL and the helper reported requested: true).
  • AC-3: Both drivers and the MCP tool import the shared helper, run.ts still exports SIGKILL_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

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

Activity

  1. added
    refactor
    graph-2026-10-consolidation
    on Oct 16, 2026
  2. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    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:

    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 targeted npx vitest run <files> for the ACs.
    CHANGELOG: add [Unreleased] lines, not changelog.d/ fragments. #1370 has not merged.
    Freeze: nothing under plugin/, .claude/skills/ or templates/skills/.
    Health baseline: if this PR changes a measured metric, regenerate scripts/qa/health-baseline.json with npx tsx scripts/qa/health-report.ts --write-baseline after the last source change. Never hand-edit it. npm run lint:health must print "no metric rose".

  3. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (5 ACs, 3 directories — refactor label)

    AC Quality Check

    Every AC is one line and has an Evidence: clause. I ran each command-shaped Evidence against main (ec9d583):

    AC Today Gates?
    AC-1 3, 2 ✅ fails today
    AC-2 file missing ✅
    AC-2b 4 passed | 91 skipped ⚠️ Vacuous as written. -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 -t filter. Also, opencode's existing case is named 862 AC-1 reports a SIGTERM close as a timeout, not 497 AC-3 …. The filter still finds it.
    AC-3 0, 1, suite green ✅ (first count fails today)
    AC-4 fired (3 files ≥ 2) ✅. The trigger pattern is (function|const)\s+killProcessGroup\b over src/ minus tests. A driver-local alias written as const killProcessGroup = … would keep it firing. The existing const 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).

    Metric Value Status
    Feature count 1 (one helper + one method) ✅
    AC items 5 ✅
    Directory spread 3 (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 killProcessGroup and one pushLines in non-test src/

    Verification: Integration Test (rg counts)
    Scenario: Given the three helper copies and the two pushLines copies → When the copies are collapsed → Then rg returns 1 / 1.
    Assumptions: pushLines becomes RingBuffer.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 the integration project runs, describe.skipIf(win32))
    Scenario: Given a real spawn(..., { detached: true }) child → When killProcessGroup(child, { graceMs: 200 }) runs → Then:

    • (a) a child that traps TERM closes with signalCode === "SIGKILL"
    • (b) sleep 30 closes on SIGTERM and no SIGKILL is sent
    • (c) a child that has already exited gets no signal
    • (d) two calls send one SIGTERM

    Assumptions:

    • "Already exited" is detected with 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.
    • Listen with child.on("close", …), not once. The mock's on is a vi.fn and the mock has no once.
    • Track idempotency in a module-level WeakSet<ChildProcess>.
    • For (b) and (d), count signals by spying on process.kill while 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 → Then Timeout after Ns. A SIGKILL with killRequested false or absent still reads Process killed by signal: SIGKILL.
    Assumptions: Add killRequested?: boolean to CodexRunOutcome and 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_MS is still exported, and existing tests pass unchanged

    Verification: 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.kill not called, the #1222 grace test).
    Assumptions: run.ts calls killProcessGroup(proc, { graceMs: SIGKILL_GRACE_MS }) and keeps the constant and its #1222 comment.

    AC-4: The async_subprocess trigger reads not_fired

    Verification: Integration Test (the accretion CLI against the real repo)
    Scenario: Given one definition file → When triggers --offline runs → Then not_fired, exit 0.
    Assumptions: docs/internal/architecture-target.md is untouched, and ~/Projects/accretion-audit/dist/cli.js exists (it does).


    Implementation Plan

    Phase 1: Shared primitives

    1. src/lib/process-group.ts (new): export killProcessGroup(child: ChildProcess, opts: { graceMs?: number } = {}): { requested: boolean }.
      • Return { requested: false } if the child already exited or its pid is undefined.
      • If the child is already in the WeakSet, return { requested: true } without signalling.
      • Otherwise add it, send process.kill(-pid, "SIGTERM"), swallow ESRCH, and fall back to process.kill(pid, "SIGTERM") on other errors (this is the drivers' fallback, kept verbatim).
      • When graceMs is set, register an on("close") flag and an .unref()'d timer that sends SIGKILL the same way unless the child has closed.
      • With graceMs absent there is no escalation (OQ-1's "no" branch keeps working).
    2. src/lib/workflow/ring-buffer.ts: add an optional { maxLineChars } constructor option and a pushLines(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

    1. drivers/codex.ts and drivers/opencode.ts:
      • Delete the local killProcessGroup and pushLines.
      • Construct the buffers with { maxLineChars: TAIL_LINE_CHARS }.
      • Change the kill to const killGroup = () => { if (killProcessGroup(proc, { graceMs: DRIVER_SIGKILL_GRACE_MS }).requested) killRequested = true; }.
      • Pass killRequested into the evaluator's outcome and widen isTimeout to signal === "SIGTERM" || (signal === "SIGKILL" && outcome.killRequested === true).
      • Grace constant: the drivers need their own constant (the issue says not to import the MCP value). Define it once in process-group.ts as export const DRIVER_SIGKILL_GRACE_MS = 5000, or define it in each driver file. Recommend process-group.ts, so there's one definition and the drivers don't diverge.
    2. src/mcp/tools/run.ts:

    Phase 3: Tests, changelog, health

    1. Add src/lib/process-group.integration.test.ts with cases (a) to (d) from AC-2.
    2. Add RingBuffer.pushLines unit cases to ring-buffer.test.ts (capping, skipping empty lines, eviction).
    3. Add one SIGKILL+killRequested evaluator case to each driver test, and one negative case (SIGKILL without a request is not a timeout).
    4. Add a CHANGELOG [Unreleased] line (not a changelog.d/ fragment).
    5. Run npx tsx scripts/qa/health-report.ts --write-baseline after the last source change if a metric moved, then confirm npm run lint:health prints "no metric rose".
    6. Run the targeted vitest files only. Run the full suite at most once, in the foreground, under timeout, after a WIP commit.

    Design Review

    1. Where does this belong? src/lib/process-group.ts, a leaf module with no imports from mcp/ or workflow/. Drivers and MCP both depend downward on it. pushLines belongs on RingBuffer, which already owns the line tail.
    2. Simplest correct approach? One function plus one method. Rejected: (a) a ProcessGroup class or handle object, which is the AsyncSubprocess abstraction and a Non-Goal; (b) putting killRequested tracking inside the helper with a wasKillRequested(child) query. That's global state the evaluator would reach into, while the driver-local flag stays pure. (c) An opts.maxChars argument on pushLines, which AC-1's regex forbids.
    3. Pattern and re-patch count: git log -S killProcessGroup shows 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.
    4. What would a senior reviewer challenge?
      • "Why does SIGKILL become a timeout?" Because otherwise the escalation that OQ-1 asks for turns every stuck timeout into "Process killed by signal: SIGKILL", which is a regression in the operator-facing message.
      • "The idempotent second call returns requested: true, is that right?" Yes: a kill was requested for that child.
      • "The WeakSet is global." It's keyed by object identity, so there's no leak and no cross-child bleed.
    5. Producers and consumers (whole-repo grep):
      • Producers of a group kill: codex.ts:774, opencode.ts:880, run.ts:1076 (+ sendSignal). After this change there is one. aider.ts's proc.kill("SIGTERM") is excluded by Non-Goal.
      • pushLines producers: codex.ts:757 and opencode.ts:788, collapsing to one.
      • Consumers of the close signal: evaluateCodexRun (codex.ts:411) and the opencode evaluator (opencode.ts:452). Both are updated together, with a test per driver.
      • SIGKILL_GRACE_MS is consumed by run.test.ts:1139, unchanged.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • Mock compatibility is the main risk. Use loose != null for exit detection, on rather than once, and process.kill (which the tests spy on) for every signal. Never use child.kill() in the helper: the codex test asserts proc.kill is not called.
    • Timer hygiene. Call .unref() on the grace timer so a stuck child can't hold the event loop open.
    • pid-reuse window. Today run.ts sends SIGKILL even if the child closed before the kill call (its close listener is registered too late). The already-exited check closes that window.
    • win32. 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

    Source Derived AC Priority
    Error handling A SIGKILL close without a requested kill still reads Process killed by signal: SIGKILL in both evaluators (Evidence: the negative case in step 7) Medium
    Regression RingBuffer.pushLines output for a >2000-char line is byte-identical to the old driver form (Evidence: ring-buffer.test.ts) Medium

    Open Questions

    1. OQ-1, SIGKILL escalation for the drivers — Recommendation: yes (the owner's default). Grace is DRIVER_SIGKILL_GRACE_MS = 5000, defined in process-group.ts. Impact if no: the drivers omit graceMs, and AC-2b's new cases become dead paths.
    2. AC-2b threshold — Recommendation: the owner edits the line to ≥ 6 passed (it passes 4 today). Impact if left as is: QA can't tell a missing SIGKILL case from a present one.
    3. Where the driver grace constant lives — Recommendation: 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 refactor with 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 refactor label).

  4. added
    planned
    on Oct 19, 2026
  5. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Test Stubs Generated

    AC Verification Happy Path Failure Paths
    AC-1 Integration (rg counts) Skipped (no file; checked by the rg Evidence) -
    AC-2 Integration 4 tests (a-d) 4 stubs (ESRCH, non-ESRCH fallback, no graceMs, undefined pid)
    AC-2b Unit 2 tests (codex, opencode) 2 negative (SIGKILL without killRequested)
    AC-3 Integration (rg + suites) Skipped (covered by existing suites) -
    AC-4 Integration (accretion CLI) Skipped (run the Evidence command) -
    Derived Unit 3 tests (RingBuffer.pushLines) 2 edge cases

    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 /exec fills 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.

  6. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Correction to the runner context above (health baseline), 2026-10-19:

    • Regenerate scripts/qa/health-baseline.json only to record a metric that went down.
    • If npm run lint:health reports a metric rose (for example functions.longest.lines or emptyCatch.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.
    • If holding it is impossible, leave the baseline unchanged and name the rise in the PR body for the owner.
  7. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 4/4 met

    Gaps:

    Suggestions:

    • Integration case (a) waits a fixed 150 ms for bash's trap to install. That is a small flake risk on a loaded CI runner.
    • AC-2b's "≥ 4 passed" passes on unmodified main (4 tests already match there). The real count is 10, but the owner may want to edit the AC text to "≥ 6".
  8. added a commit that references this issue on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    graph-2026-10-consolidationplannedrefactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions