Skip to content

refactor(workflow): split runIssueWithLogging (1,620 lines) into stage functions of ≤ 200 counted lines, behaviour-preserving #1507

Closed

Description

@admarble

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 main by 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-qa on 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/$AFTER are 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/workflow and 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-wide longest < 200 would 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

  1. added
    graph-2026-10-fundamentals
    on Oct 18, 2026
  2. admarble commented on Oct 22, 2026

    @admarble
    ContributorAuthor

    Runner context, 2026-10-21, before launch (fundamentals W3; stop-at-PR; judgment tier, all phases on Opus). main = df795ca.

    Changed since filing:

    How to split:

    • Prefer stage functions in the same file. batch-executor.test.ts mocks modules with vi.mock, and code moved into a sibling file must still resolve the same mocked imports.
    • If a stage does move out, put it under src/lib/workflow/batch-executor/ and re-export it from batch-executor.ts only when something imports it. knip counts unused exports.
    • Keep the order of side effects exactly: state writes, log-writer calls, progress lines, PR and comment calls, and the noteSuppressed calls. Pass an explicit context object between stages, not module-level state.
    • Look for early returns and finally blocks, and keep each one on the same path. A return inside 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.ts must 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 .functions must show over200 6 and over400 1.

    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 targeted npx vitest run <files> runs.
    CHANGELOG: add [Unreleased] lines under the existing headings, not changelog.d/ fragments, and never add a second heading of the same name.
    Health baseline: regenerate scripts/qa/health-baseline.json with npx tsx scripts/qa/health-report.ts --write-baseline only to record metrics that went down, here the functions keys. If a full regenerate moves any other key up, hand-edit only the keys that went down and say so in the PR body. If npm run lint:health reports a rise, restructure so it holds.
    PR body and commits: no claude.ai/code/session_ links anywhere (Gitleaks rule claude-session-url).
    Freeze: nothing under plugin/, .claude/skills/ or templates/skills/.

  3. admarble commented on Oct 22, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (6 ACs, 3 directories: src/lib/workflow/, scripts/qa/, root CHANGELOG)

    Tier note: no complex/refactor label is set, but this is a 1,072-counted-line behaviour-preserving refactor (the title's type is refactor), so it gets Complex treatment.

    AC Quality Check

    • AC-6: the linter flags "the other six functions" as open-ended. False positive. The evidence pins exact counts (over200 == 6, over400 == 1), so the set is bounded.
    • Evidence run on main (df795ca) before acceptance:
      • AC-1 → 1 (runIssueWithLogging at 1135, 1072 lines). Fails today. Not vacuous.
      • AC-6 → false (baseline 7 / 2). Fails today. Not vacuous.
      • AC-2 → 0, AC-3 → 154/154 pass, AC-4 → 1 1. These hold on main by construction. They are constraints on the PR, not gates (the issue says so for AC-2).
    • AC-3's evidence is too narrow. runIssueWithLogging is 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.integration and run-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.
    • AC-4 checks 2 of the file's 26 exports. See derived AC-8.

    Scope Assessment

    Non-Goals: present (no behaviour or log-wording change, no catch conversion, no gh routing, no F-07 files, no plugin//skills edits).

    Metric Value Status
    Feature count 3 (heuristic) ❌
    AC items 6 ⚠️
    Directory spread 4 (heuristic) ⚠️

    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.ts exceeds 200 counted lines

    Verification: 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-function message.
    Assumptions: Nested closures count as their own functions and as lines of the function that contains them. openOrUpdatePR (118 lines) and buildBundle must 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, on main's build and the PR's build, then the jq diff → 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, plus npx tsx scripts/qa/health-report.ts --json | jq .functions shows 6 / 1)
    Assumptions: functions.longest also changes, to RunOrchestrator.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.mock keeps resolving). The two run-scoped objects are passed explicitly; there is no module state.

    • IssueRunEnv (read-only): the destructured ctx, log, warn, issueConfig, autoWaitLedger, startTime.
    • IssueRunState (mutable): phaseResults, resumeHandle, loopTriggered, phases, specAlreadyRan, the haltedBy* flags, divergenceBundle, iterationRecords, modelEscalations, ladderState, lastTrigger, consecutiveDivergenceSuspect.

    Phase 1: Shared helpers, lifted closures (commit, then run the 2 AC-3 files)

    1. Collapse the duplicated producers (Design Review Q5) into module-private helpers that return byte-identical values:
      • buildPhaseErrorContext(result), used by the spec log at 1562 and the loop log at 2133.
      • phaseLogStatus(record, result), the success/timeout/failure ternary.
      • persistResumeHandle(stateManager, issueNumber, handle, label), used at 1502 and 2015. Keep each call site's own noteSuppressed label: "spec resume handle" and "phase resume handle".
    2. Lift openOrUpdatePR (1256–1374), makeWaitTransition and buildBundle to module-level functions that take env/state.

    Phase 2: Setup and spec stages (commit, then test)

    1. 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 early IssueResult. The guard's return (1195) becomes "the caller returns this result".
    2. Split 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 early IssueResult at 1656.
      • resolvePhasesFromSpec: resolveSpecRecommendation and its source-specific log lines.
    3. finalizePhasePlan(env, state) covers 1714–1790: the non-auto-detect branch, the resume filter, testgen/security-review insertion and onPhasePlan.

    Phase 3: Quality loop (commit after each extraction, then test)

    1. runQualityLoop(env, state) keeps the while and the three loop exits at 2531–2546. It calls runIteration.
    2. runIteration keeps the for over 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 the breaks at 1981 and 2290. It may need its own sub-split into dispatchPhase and recordPhaseOutcome, 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: both breaks leave the for.
      • assessIterationProgress(env, state, ...), covering 2477–2528.
    3. Control-flow rule: every former break or return becomes 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

    1. finalizeIssueRun(env, state, relayActivation) covers 2550–2776. Split it into settleIssueStatus (ready gate, final status, checkpoint) and deliverIssueBranch (rebase, PR, relay deactivation, the returned object), because the block is about 226 lines.
    2. runIssueWithLogging becomes about 30 lines of stage calls.
    3. Run npx tsx scripts/qa/health-report.ts --write-baseline. Keep only the functions keys. If any other key rose, hand-edit and say so in the PR body. Add a CHANGELOG [Unreleased] line under the existing heading.
    4. Run the 10 test files (AC-3 + AC-7), lint, typecheck and knip. Run the full suite at most once, in the foreground, under timeout, after a WIP commit.

    Design Review

    1. Where does this logic belong? In batch-executor.ts, as module-private functions. vi.mock in 10 test files targets the modules this file imports. Same-file stages keep those mocks working with zero test edits (AC-2).
    2. What's the simplest correct approach? Mechanical extraction along the existing comment-delimited stages, with an explicit env/state pair. Rejected alternatives:
      • (a) An IssueRunner class: a larger diff that turns locals into this. fields and changes no behaviour.
      • (b) Stage modules under batch-executor/: they need re-exports, which knip flags, and they risk mock-resolution drift.
      • (c) A generic pipeline/stage registry: indirection with one caller.
        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.
    3. Existing pattern, re-patch count: 23 commits to this file in 31 days. This issue is the class fix the fundamentals graph targets. The ACs state an outcome (no function over 200), not a site. No deliberately local record 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 to run/executePhaseWithRetry, and its ratchet AC is what keeps this outcome from regressing.
    4. What would a senior reviewer challenge?
      • "A mutable state bag is just module state with extra steps." It is per-call and passed explicitly, which is what the runner asked for.
      • "Why not cut the loop/spec duplication further?" Spec's log entry deliberately omits diffStats/commitHash/verdict/summary. Merging the two createPhaseLogFromTiming calls would add fields to spec's log entry, which is a behaviour change. Only the parts that are byte-identical get shared.
      • "Signals instead of exceptions?" Yes: exceptions would change the existing finally/catch semantics.
    5. Producers and consumers:
      • Run-log phase entries (logWriter.logPhase) have 2 producers in this function (spec 1562, loop 2133). Their errorContext and status are collapsed in step 1. The remaining field difference is intentional, as stated in Q4. Consumers: sequant logs, MCP sequant_logs and the AC-5 golden diff.
      • Resume-handle persistence has 2 producers (1502, 2015) and is collapsed in step 1.
      • IssueResult has 3 producers (1195, 1656, 2748), all inside this function. Consumers: executeBatch, run-orchestrator.ts, run.ts and 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:

    • Order preservation is the main risk. The suite asserts call order through ordered mocks (mock.calls order, toHaveBeenNthCalledWith). Extracting into awaited helpers keeps the order only if no await is added or removed. Do not wrap a sync block in an async helper that is then awaited: the extra microtask can reorder fire-and-forget makeWaitTransition writes.
    • noteSuppressed labels (26) move unchanged. AC-1 counts every function, so check each new stage with the eslint rule as it lands.
    • 30-minute wall: commit after each Phase 1–4 step.

    Derived ACs

    Source Derived AC Priority
    AC-3 coverage gap AC-7: all 10 files that call runIssueWithLogging pass 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 failed High
    AC-4 coverage gap AC-8: the export list is identical. Evidence: diff <(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 → same High
    Hygiene AC-9: npm run lint, npx tsc --noEmit, npx knip and npm run lint:health are clean Medium

    Open Questions

    1. The ADR is outside "May touch". Recommendation: include 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.
    2. Should derived AC-7/AC-8 be edited into the issue's AC lines? Recommendation: yes. QA enforces only the AC lines, so a derived AC that lives only in this comment is advisory. Impact if not: a ladder or ready-gate regression could pass AC-3.

    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 test phase: there is no UI. AC-5 belongs to the runner.


    Label Review

    Current: graph-2026-10-fundamentals
    Recommended: add refactor, planned
    Reason: It is a behaviour-preserving restructure, and refactor makes the Complex tier and the quality loop label-driven.
    Quality Loop: enabled by this spec (complex refactor, SCOPE_WARNING).

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

    @admarble
    ContributorAuthor

    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.

  6. admarble commented on Oct 22, 2026

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

    AC coverage: 8/9 met

    Gaps:

    Pending ACs:

    • AC-5

    Needs human review:

    • AC-5 golden-run phase-sequence diff not yet produced by the runner
    • Required CI check still pending at review time
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-fundamentalsplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions