Repository navigation
Description
Epic: graph-2026-10-fundamentals Tier: judgment Execution: split Blocked by: #1506
Problem
runIssueWithLogging in src/lib/workflow/batch-executor.ts:1135 spans 1,620 lines (1,049 counted by ESLint with blanks and comments skipped). The file holds 25 of the 119 silent catches (F-03) and sits among the four workflow files that took 40 of the last 83 fix commits. A fix to a 1,620-line function cannot be reviewed as a unit, and every fix arrives with a median 132 test lines. The consolidation tracker #1470 lists "no execution-layer refactor" as a non-goal and none of #1471/#1472/#1475 touch this file, so this split has no file-scope conflict. The function is exported and referenced 115 times in batch-executor.test.ts (4,331 lines), which is the characterization suite (D-H).
Acceptance Criteria
- AC-1: No function in the file exceeds 200 counted lines. Evidence:
npx eslint --rule 'max-lines-per-function: [error, {max: 200, skipBlankLines: true, skipComments: true}]' src/lib/workflow/batch-executor.ts --format json | jq '[.[].messages[] | select(.ruleId=="max-lines-per-function")] | length'→0 - AC-2: No test lines are added (I-3, constraint: holds on
mainby construction, binding on the PR). Evidence:git diff --numstat $(git merge-base origin/main HEAD)..HEAD -- '*.test.ts' '*.test.tsx' | awk '{a+=$1} END{print a+0}'→0 - AC-3: The existing suite passes unchanged. Evidence:
npx vitest run src/lib/workflow/batch-executor.test.ts src/lib/workflow/batch-executor.suppressed.integration.test.ts→0 failed - AC-4: The exported API is unchanged. Evidence:
for s in runIssueWithLogging parseDependencies; do grep -cE "export (async )?function $s\(" src/lib/workflow/batch-executor.ts; done | tr '\n' ' '→1 1 - AC-5: Golden run (runner, OQ-8): ad-motion #285 (a fixed-change fixture issue filed for golden runs) run with
--phases spec,exec,qa --force --full-qaon main's build and on the PR's build (owner, OQ-8, 2026-10-21) produces the same phase sequence. Evidence:diff <(jq -S '[.issues[] | {issue: .issueNumber, status: .status, phases: [.phases[] | {phase: .phase, status: .status}]}]' "$BEFORE") <(jq -S '[.issues[] | {issue: .issueNumber, status: .status, phases: [.phases[] | {phase: .phase, status: .status}]}]' "$AFTER") && echo identical→identical(where$BEFORE/$AFTERare the two run-log files the runner names on the PR) - AC-6: The baseline moves down with the PR: this split removes exactly its own function from the over-200 and over-400 counts and adds none (owner decision 2026-10-21; the other six functions over 200 lines are all in
src/lib/workflowand fall under refactor(workflow): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1508 AC-1, so the repo-widelongest < 200would hold only after refactor(workflow): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1508). Evidence:jq '.functions.over200 == 6 and .functions.over400 == 1' scripts/qa/health-baseline.json→true
Prior fixes / producers
- Prior fixes touching this function:
git log --since='28 days ago' --format='%h %s' -- src/lib/workflow/batch-executor.ts | wc -l→ 21 at planning (2026-10-18). This is the class the whole graph targets; the ACs state the outcome (no function over 200), not a site. - Producers: one file, one owner. The run-log writer it calls is
log-writer.ts(F-03's scope, already merged by this node's launch).
May touch
src/lib/workflow/batch-executor.ts and, if a stage moves out, new sibling files under src/lib/workflow/batch-executor/ with the same export surface re-exported from batch-executor.ts. No test file (I-3). scripts/qa/health-baseline.json (I-4). CHANGELOG entry.
Non-Goals
- Any behaviour change, including log wording.
- Converting catches (F-03 did) or routing
gh(F-05 did) — the split moves the converted code. run-orchestrator.ts,phase-executor.ts,worktree-manager.ts(F-07).- No edits under
plugin/,.claude/skills/,templates/skills/(I-1).
Done when
batch-executor.ts has no function over 200 counted lines, no test changed, and the golden run is identical.
Activity
admarble commentedon Oct 22, 2026
Runner context, 2026-10-21, before launch (fundamentals W3; stop-at-PR; judgment tier, all phases on Opus). main = df795ca.
Changed since filing:
runIssueWithLoggingstarts atbatch-executor.ts:1135and is 1072 counted lines today, not 1,049. The file is 2,777 lines;batch-executor.test.tsis 4,339.noteSuppressed(scope, err, "<what>")calls from feat(run): a dropped error leaves a trace — noteSuppressed() counts into the run log, batch-executor's 25 silent catches converted #1504, with labels such as"spec start"and"updatePRInfo". They name the step, not the function. When you move a catch into a stage function, keep its label as it is. Log wording is a Non-Goal, and these labels go out on the debug sink.jq '.functions.over200 == 6 and .functions.over400 == 1' scripts/qa/health-baseline.json→true. The oldlongest < 200could not pass, becauseRunOrchestrator.run(649) is refactor(workflow): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1508's.--phases spec,exec,qa. The runner produces both run logs; exec and QA do not run it. QA: mark AC-5 as pending the runner, not as a gap.How to split:
batch-executor.test.tsmocks modules withvi.mock, and code moved into a sibling file must still resolve the same mocked imports.src/lib/workflow/batch-executor/and re-export it frombatch-executor.tsonly when something imports it. knip counts unused exports.noteSuppressedcalls. Pass an explicit context object between stages, not module-level state.returns andfinallyblocks, and keep each one on the same path. Areturninside a stage only ends that stage, so the caller has to check for it.AC-1 counts every function in the file.
npx eslint --rule 'max-lines-per-function: [error, {max: 200, skipBlankLines: true, skipComments: true}]' src/lib/workflow/batch-executor.tsmust report nothing, so no new stage function may be over 200 either. Check AC-6 the same way:npx tsx scripts/qa/health-report.ts --json | jq .functionsmust showover2006 andover4001.AC-2 means no test file changes at all. If a test fails, the split changed behavior; fix the split, not the test.
30-minute wall: each MCP-dispatched phase has one. The #1506 exec died at it. Commit a working state at least every 10 minutes during exec; a killed exec is then re-dispatched from your last commit. Run the two AC-3 files after each stage you extract, not only at the end.
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. Prefer targetednpx vitest run <files>runs.CHANGELOG: add
[Unreleased]lines under the existing headings, notchangelog.d/fragments, and never add a second heading of the same name.Health baseline: regenerate
scripts/qa/health-baseline.jsonwithnpx tsx scripts/qa/health-report.ts --write-baselineonly to record metrics that went down, here thefunctionskeys. If a full regenerate moves any other key up, hand-edit only the keys that went down and say so in the PR body. Ifnpm run lint:healthreports a rise, restructure so it holds.PR body and commits: no
claude.ai/code/session_links anywhere (Gitleaks ruleclaude-session-url).Freeze: nothing under
plugin/,.claude/skills/ortemplates/skills/.admarble commentedon Oct 22, 2026
Complexity: Complex (6 ACs, 3 directories:
src/lib/workflow/,scripts/qa/, root CHANGELOG)Tier note: no
complex/refactorlabel is set, but this is a 1,072-counted-line behaviour-preserving refactor (the title's type isrefactor), so it gets Complex treatment.AC Quality Check
over200 == 6,over400 == 1), so the set is bounded.main(df795ca) before acceptance:1(runIssueWithLoggingat 1135, 1072 lines). Fails today. Not vacuous.false(baseline 7 / 2). Fails today. Not vacuous.0, AC-3 → 154/154 pass, AC-4 →1 1. These hold onmainby construction. They are constraints on the PR, not gates (the issue says so for AC-2).runIssueWithLoggingis called from 10 test files, not 2:batch-executor,batch-executor.suppressed.integration,batch-executor.model-ladder,model-ladder,ready-gate-run,run-orchestrator,skills-preflight,skills-preflight.integration,run-skills-commit-warning.integrationandrun-base-parity.integration. The ladder, ready-gate and divergence paths that the split moves are covered mainly by the other 8. See derived AC-7.Scope Assessment
Non-Goals: present (no behaviour or log-wording change, no catch conversion, no
ghrouting, no F-07 files, noplugin//skills edits).Verdict:⚠️ SCOPE_WARNING. The tool says SPLIT_RECOMMENDED; this spec overrides it. The "3 features" are one refactor of one function, plus its baseline update and a CHANGELOG line. A further split would leave a half-extracted function between PRs. The quality loop is enabled.
Acceptance Criteria
AC-1: No function in
batch-executor.tsexceeds 200 counted linesVerification: Integration Test (the eslint command in the issue →
0)Scenario: Given the split → When the eslint rule runs on the file → Then no
max-lines-per-functionmessage.Assumptions: Nested closures count as their own functions and as lines of the function that contains them.
openOrUpdatePR(118 lines) andbuildBundlemust therefore move out, not just shrink.AC-2: No test lines added
Verification: Integration Test (
git diff --numstat→0)Scenario: Given the PR → When it is diffed against the merge base → Then no
*.test.ts(x)additions. A failing test means the split changed behaviour: fix the split, not the test.AC-3: The existing suite passes unchanged
Verification: Unit Test (vitest, the 2 named files → 0 failed; see derived AC-7 for the other 8)
AC-4: The exported API is unchanged
Verification: Integration Test (grep →
1 1). See derived AC-8 for the full export list.AC-5: Golden run gives an identical phase sequence
Verification: Manual Test (runner-owned). ad-motion #279 with
--phases spec,exec,qa, onmain's build and the PR's build, then thejqdiff →identical. QA: mark this AC as pending the runner, not as a gap.AC-6: The baseline moves down by exactly this function
Verification: Integration Test (
jq ... health-baseline.json→true, plusnpx tsx scripts/qa/health-report.ts --json | jq .functionsshows 6 / 1)Assumptions:
functions.longestalso changes, toRunOrchestrator.run(649). That key went down, so it may be regenerated too. No other key may rise (npm run lint:health).Implementation Plan
Same-file stage functions, module-private (not exported, so knip has nothing to flag and every
vi.mockkeeps resolving). The two run-scoped objects are passed explicitly; there is no module state.IssueRunEnv(read-only): the destructuredctx,log,warn,issueConfig,autoWaitLedger,startTime.IssueRunState(mutable):phaseResults,resumeHandle,loopTriggered,phases,specAlreadyRan, thehaltedBy*flags,divergenceBundle,iterationRecords,modelEscalations,ladderState,lastTrigger,consecutiveDivergenceSuspect.Phase 1: Shared helpers, lifted closures (commit, then run the 2 AC-3 files)
buildPhaseErrorContext(result), used by the spec log at 1562 and the loop log at 2133.phaseLogStatus(record, result), thesuccess/timeout/failureternary.persistResumeHandle(stateManager, issueNumber, handle, label), used at 1502 and 2015. Keep each call site's ownnoteSuppressedlabel:"spec resume handle"and"phase resume handle".openOrUpdatePR(1256–1374),makeWaitTransitionandbuildBundleto module-level functions that takeenv/state.Phase 2: Setup and spec stages (commit, then test)
initIssueRun(ctx)covers 1158–1442: the banner, the fix(run): a failed git worktree add must fail the issue, not run its phases in the main checkout (two CLIs race on .git/config) #1469 worktree-required guard, state init and relay activation. It returns{ env, state, relayActivation }or an earlyIssueResult. The guard'sreturn(1195) becomes "the caller returns this result".runSpecStage(env, state)(1449–1713, ~265 lines, over 200 by itself) into three functions:dispatchSpecPhase: progress, state,executePhaseWithRetry, resume handle.recordSpecOutcome: the log entry, the state write,recordWindowHaltState, and the SPEC_DIVERGENCE bundle plus the earlyIssueResultat 1656.resolvePhasesFromSpec:resolveSpecRecommendationand its source-specific log lines.finalizePhasePlan(env, state)covers 1714–1790: the non-auto-detect branch, the resume filter, testgen/security-review insertion andonPhasePlan.Phase 3: Quality loop (commit after each extraction, then test)
runQualityLoop(env, state)keeps thewhileand the three loop exits at 2531–2546. It callsrunIteration.runIterationkeeps theforover phases and the snapshot logic at 1861–1869. It calls:runPhaseStep(env, state, phase, iteration), the body at 1879–2292. It returns"next" | "break", covering thebreaks at 1981 and 2290. It may need its own sub-split intodispatchPhaseandrecordPhaseOutcome, because the logging and state blocks alone are about 110 lines.handlePhaseFailure(...), covering 2293–2461: the halt flags and the /loop spawn. It returns"break"on both paths (2455 and 2460), which keeps today's semantics: bothbreaks leave thefor.assessIterationProgress(env, state, ...), covering 2477–2528.breakorreturnbecomes a returned signal that the caller checks on the very next line. Preserve the side-effect order at each boundary: state write → log-writer → progress line → PR/comment →noteSuppressed.Phase 4: Finalize, baseline, CHANGELOG
finalizeIssueRun(env, state, relayActivation)covers 2550–2776. Split it intosettleIssueStatus(ready gate, final status, checkpoint) anddeliverIssueBranch(rebase, PR, relay deactivation, the returned object), because the block is about 226 lines.runIssueWithLoggingbecomes about 30 lines of stage calls.npx tsx scripts/qa/health-report.ts --write-baseline. Keep only thefunctionskeys. If any other key rose, hand-edit and say so in the PR body. Add a CHANGELOG[Unreleased]line under the existing heading.timeout, after a WIP commit.Design Review
batch-executor.ts, as module-private functions.vi.mockin 10 test files targets the modules this file imports. Same-file stages keep those mocks working with zero test edits (AC-2).IssueRunnerclass: a larger diff that turns locals intothis.fields and changes no behaviour.batch-executor/: they need re-exports, which knip flags, and they risk mock-resolution drift.ADR required: the exec PR adds
docs/adr/0020-…recording the same-file stage split and the env/state context pair. 0018 and 0019 set this precedent for the graph. See Open Question 1.deliberately localrecord is needed and there is no divergence. refactor(workflow): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1508 applies the same pattern torun/executePhaseWithRetry, and its ratchet AC is what keeps this outcome from regressing.statebag is just module state with extra steps." It is per-call and passed explicitly, which is what the runner asked for.diffStats/commitHash/verdict/summary. Merging the twocreatePhaseLogFromTimingcalls would add fields to spec's log entry, which is a behaviour change. Only the parts that are byte-identical get shared.finally/catchsemantics.logWriter.logPhase) have 2 producers in this function (spec 1562, loop 2133). TheirerrorContextand status are collapsed in step 1. The remaining field difference is intentional, as stated in Q4. Consumers:sequant logs, MCPsequant_logsand the AC-5 golden diff.IssueResulthas 3 producers (1195, 1656, 2748), all inside this function. Consumers:executeBatch,run-orchestrator.ts,run.tsand MCP. The 3 producers stay separate because their shapes differ by path; the step-8 signals preserve them unchanged.Feature Quality Planning
Most dimensions do not apply (no new I/O, UI, auth or config). Notable items:
mock.callsorder,toHaveBeenNthCalledWith). Extracting intoawaited helpers keeps the order only if noawaitis added or removed. Do not wrap a sync block in anasynchelper that is thenawaited: the extra microtask can reorder fire-and-forgetmakeWaitTransitionwrites.noteSuppressedlabels (26) move unchanged. AC-1 counts every function, so check each new stage with the eslint rule as it lands.Derived ACs
runIssueWithLoggingpass unchanged. Evidence:npx vitest run src/lib/workflow/{batch-executor,batch-executor.suppressed.integration,batch-executor.model-ladder,model-ladder,ready-gate-run,run-orchestrator,skills-preflight,skills-preflight.integration,run-skills-commit-warning.integration,run-base-parity.integration}.test.ts→0 faileddiff <(git show origin/main:src/lib/workflow/batch-executor.ts | grep -E '^export ' | sort) <(grep -E '^export ' src/lib/workflow/batch-executor.ts | sort) && echo same→samenpm run lint,npx tsc --noEmit,npx knipandnpm run lint:healthare cleanOpen Questions
docs/adr/0020-…anyway. It is docs only, and feat(run): a dropped error leaves a trace — noteSuppressed() counts into the run log, batch-executor's 25 silent catches converted #1504/refactor(platform): every gh call goes through PlatformProvider; FakeGitHubProvider replays captured gh output so no test fakes gh through child_process #1506 set the precedent with 0018/0019. Impact if wrong: drop one file from the PR.Recommended Workflow
Phases: exec → qa
Quality Loop: enabled
Reasoning: A complex behaviour-preserving refactor, which is what the quality loop is for. No testgen: AC-2 forbids new test lines. No
testphase: there is no UI. AC-5 belongs to the runner.Label Review
Current:
graph-2026-10-fundamentalsRecommended: add
refactor,plannedReason: It is a behaviour-preserving restructure, and
refactormakes the Complex tier and the quality loop label-driven.Quality Loop: enabled by this spec (complex refactor, SCOPE_WARNING).
admarble commentedon Oct 22, 2026
Runner correction to the context above: the golden-run testbed is ad-motion #285, not #279 (owner decision; reason on #1501). AC-5 is updated. It is still runner-produced; QA marks it as pending the runner.
admarble commentedon Oct 22, 2026
QA Verdict: NEEDS_VERIFICATION
AC coverage: 8/9 met
Gaps:
Pending ACs:
Needs human review: