Skip to content

refactor(workflow): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1508

Closed

Description

@admarble

Epic: graph-2026-10-fundamentals Tier: judgment Execution: split Blocked by: #1471, #1475, #1507

Problem

After F-06 the remaining functions over 200 counted lines in src/lib/workflow are six (ESLint counting, blanks and comments skipped, measured 2026-10-18): RunOrchestrator.run (run-orchestrator.ts:790, 646), ensureWorktree (worktree-manager.ts:1057, 393), executePhaseWithRetry (phase-executor.ts:2030, 262), runReadyGate (ready-gate.ts:595, 253), executePhase (phase-executor.ts:1593, 233), ClaudeCodeDriver.executePhase (drivers/claude-code.ts, 230). #1471 edits phase-executor.ts; #1475 edits run-orchestrator.ts and worktree-manager.ts; this node waits for both so the splits move consolidated code. ready-gate.ts and drivers/claude-code.ts are in no consolidation node (#1472 touches aider, codex and opencode, not claude-code). The ESLint rule then holds the line for the whole directory.

Acceptance Criteria

  • AC-1: No function over 200 counted lines in the workflow layer. Evidence: npx eslint --rule 'max-lines-per-function: [error, {max: 200, skipBlankLines: true, skipComments: true}]' 'src/lib/workflow/**/*.ts' --ignore-pattern '**/*.test.ts' --format json | jq '[.[].messages[] | select(.ruleId=="max-lines-per-function")] | length' → 0
  • AC-2: The ratchet is in the config as its own block scoped to the workflow layer (the src/commands/** block already exists, so a bare grep -c of 1 is today's baseline and proves nothing). Evidence: awk '/src\/lib\/workflow\/\*\*/{f=1} f&&/max-lines-per-function/{print "found";exit}' eslint.config.js → found
  • AC-3: Lint is green with the rule (constraint: green today, must stay green after AC-2). Evidence: npm run lint > /dev/null 2>&1 && echo green → green
  • AC-4: No test lines are added (I-3, constraint). Evidence: git diff --numstat $(git merge-base origin/main HEAD)..HEAD -- '*.test.ts' '*.test.tsx' | awk '{a+=$1} END{print a+0}' → 0
  • AC-5: The workflow suites pass unchanged (constraint; the suite takes more than 90 s and the known local gpg-signing failure in driver-conformance is not this node's — CI's test check is the authority). Evidence: npx vitest run src/lib/workflow/ → 0 failed
  • AC-6: Golden run (runner, OQ-8), same command as F-06 AC-5. 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
  • AC-7: The baseline moves down with the PR. Evidence: jq '.functions.over200' scripts/qa/health-baseline.json → 0 (measured 2026-10-22 on main 039d202: all six over-200 functions are in the workflow layer and the src/commands/** ratchet already exists, so nothing may remain)

Prior fixes / producers

May touch

src/lib/workflow/run-orchestrator.ts, src/lib/workflow/worktree-manager.ts, src/lib/workflow/phase-executor.ts, src/lib/workflow/ready-gate.ts, src/lib/workflow/drivers/claude-code.ts, new sibling modules under src/lib/workflow/ for extracted stages (same exports re-exported), eslint.config.js (one appended block scoped to src/lib/workflow/**), scripts/qa/health-baseline.json (I-4), CHANGELOG entry. No test file (I-3).

Non-Goals

Done when

The workflow layer has no function over 200 counted lines, the lint rule enforces it, 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 23, 2026

    @admarble
    ContributorAuthor

    Runner context for the sequant_run session (2026-10-22, owner-approved launch).

    • AC-2 and AC-7 were rewritten today before launch. Read the ACs as the body reads now: AC-2 needs a max-lines-per-function block scoped to src/lib/workflow/**, and AC-7 needs functions.over200 of 0 in scripts/qa/health-baseline.json.
    • Commit to the worktree branch every ~10 minutes, after each function split lands and type-checks. The MCP orchestrator kills the run after 30 minutes without a phase event, and only committed work survives. Six functions across five files is more than refactor(workflow): split runIssueWithLogging (1,620 lines) into stage functions of ≤ 200 counted lines, behaviour-preserving #1507's single split, which took 26 minutes.
    • Never start or wait on a background full-suite run. npx vitest run src/lib/workflow/ is the suite for AC-5; the one known local failure is the gpg driver-conformance codex commit test, which is not this issue's.
    • No test file changes (AC-4). No edits under plugin/, .claude/skills/ or templates/skills/.
    • Commit messages carry no Co-Authored-By line and no session links.
    • AC-6 (the golden run) is the runner's: do not attempt it in the phase; mark it runner-owned in the PR body.
  3. admarble commented on Oct 23, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (7 ACs, 2 directories: src/lib/workflow/ (+drivers/), plus eslint.config.js and scripts/qa/)

    AC Quality Check

    I ran each command-shaped Evidence: on main @ 039d202:

    AC Today Gates?
    AC-1 6 (claude-code executePhase 230, phase-executor executePhase 236, executePhaseWithRetry 262, runReadyGate 253, RunOrchestrator.run 649, ensureWorktree 393) ✅ fails today
    AC-2 prints nothing (no src/lib/workflow/** string in the config) ✅ fails today. ⚠️ Weak spot: the awk sets its flag at the first src/lib/workflow/** match, so a comment with that string placed above the existing src/commands/** block (line 132) would match on that block's rule. Append the new block after the commands block, with no glob in a comment above it.
    AC-3 green constraint, green today, OK
    AC-4 0 constraint, OK
    AC-5 not run here (>90 s, runs in exec) constraint
    AC-6 runner-owned (per the owner comment) do not attempt in the phase
    AC-7 6 ✅ fails today

    Line counts have drifted a little since the 2026-10-18 figures in the body (executePhase 233→236, run 646→649). The ACs state outcomes, so this does not matter.


    Scope Assessment

    Non-Goals: present (no behaviour change, no src/commands, no #506, no plugin/ / .claude/skills/ / templates/skills/).

    Metric Value Status
    Feature count 1 (mechanical split + ratchet) ✅
    AC items 7 ✅
    Directory spread 2 (+ 2 config files) ✅

    Verdict: ⚠️ SCOPE_WARNING. The scope is coherent, but the work is large: about 2,000 counted lines over 6 functions in 5 files. #1507 took 26 minutes for one function, and the MCP watchdog kills a run after 30 minutes with no phase event. Commit after each function (owner comment).

    Blockers: #1471, #1475 and #1507 are all CLOSED ✅.


    Acceptance Criteria

    • AC-1 (Integration: ESLint JSON count). Given the six splits → When the AC-1 eslint command runs → Then 0. Assumption: the helpers stay ≤ 200 each, and so does run's remaining body.
    • AC-2 (Integration: config grep). A new block files: ["src/lib/workflow/**/*.ts"] with max-lines-per-function: [error, {max:200, skipBlankLines:true, skipComments:true}], appended after the src/commands/** block, with a short // #1508: comment in the refactor(commands): split initCommand, doctorCommand, syncCommand and updateCommand to ≤ 200 counted lines; max-lines-per-function ratchet for src/commands #1509 style. Tests are already excluded by the global ignores.
    • AC-3 (Integration). npm run lint passes with --max-warnings 0. New helpers must satisfy the type-aware rules (no any, explicit return types where the config demands them).
    • AC-4 (Integration: git numstat). No *.test.ts edits. This is why the design below keeps every split in the same file.
    • AC-5 (Integration). npx vitest run src/lib/workflow/ → 0 failed, except the known gpg driver-conformance local failure. CI test is the authority.
    • AC-6 (Manual, runner). Golden run diff identical. Mark it runner-owned in the PR body.
    • AC-7 (Integration). Regenerate with scripts/qa/health-report.ts (or hand-edit as refactor(#1507): split runIssueWithLogging (1,620 lines) into stage functions of ≤ 200 counted lines, behaviour-preserving #1578 did) → over200: 0, over400: 0, and longest updated to the new top function.

    Implementation Plan

    Follow ADR-0020 Option A: module-private stage functions in the same file. State passes explicitly as an env/state pair. Early return/break becomes a returned sentinel (RunResult | null, "next" | "break") that the caller checks on the next line. noteSuppressed labels move with their catches, unchanged, and log wording stays byte-identical.

    Phase 1: Small ones first (each one commits on its own)

    1. drivers/claude-code.ts ClaudeCodeDriver.executePhase (230). Extract private methods: abort/timeout wiring (L71–87), resume-token resolution (L101–120), the SDK stream loop (L166–225), and result/typed-error assembly (L226+).
    2. phase-executor.ts executePhase (236). Extract the dry-run plan print (L1594–1647) and buildPhaseEnv(...) for the env block (L1697–1760+).
    3. phase-executor.ts executePhaseWithRetry (262). Extract the single-attempt path (L2060–2137) and the per-attempt classification inside the cold-start loop (L2152–2287: capped / divergence / window-exhausted / transient / genuine) as a function returning { kind: "return", result } | { kind: "retry" } | { kind: "break" }. The MCP-fallback tail (L2288+) becomes its own function.
    4. ready-gate.ts runReadyGate (253). Extract runPhaseWithProgress (L586 closure → module function), gap-report persistence (L694–723), and the per-iteration verdict guards (L758–836) returning a halt result or null.

    Phase 2: The big two

    1. worktree-manager.ts ensureWorktree (393). Extract reuseExistingWorktree (L1118–1304), createWorktree with fetch, base ref and retryOnConfigLock add (L1305–1437), rebaseOntoChainBase (L1438–1495), and copyLocalConfigFiles (L1496+).
    2. run-orchestrator.ts RunOrchestrator.run (649). Split along its existing // ── banners into private static methods: setupServices (L785–842), runStateGuard + chain resume (L843–1010), acquireRunLocks (L1011–1081), chainContentPreflight (L1082–1124), provisionIssues (issue info + worktrees + the three skills pre-flights, L1125–1453; this may need two pieces to fit under 200), and executeAndFinalize (L1454+). wallClock/runStartedAt and the shutdown registrations go in an env object so the "every return closes the wall clock" invariant (L760) holds on each early exit.

    Phase 3: Ratchet + bookkeeping

    1. Append the src/lib/workflow/** block to eslint.config.js. Update scripts/qa/health-baseline.json. Add a CHANGELOG entry (or a changelog.d/ fragment if improve(release): changelog fragments instead of a shared [Unreleased] block — 121/192 main commits touch CHANGELOG.md #1351 lands first). Add an ADR (see the Design Review). Run AC-1/2/3/4/7 and the workflow suite.

    Design Review

    1. Where it belongs: the same files. The issue's "May touch" allows sibling modules, but see Q2.
    2. Simplest correct approach: same-file private helpers. Rejected: sibling modules that re-export (ADR-0020 Option C). 38 workflow test files use vi.mock. A helper moved to a new module escapes the mocks of modules it imports, which forces test edits (AC-4 forbids that). New exports would also raise knip's unusedExports (339). Rejected: class conversion for ensureWorktree/runReadyGate, which means a larger diff for no gain.
    3. Pattern & recurrence: ADR-0020 (refactor(workflow): split runIssueWithLogging (1,620 lines) into stage functions of ≤ 200 counted lines, behaviour-preserving #1507, refactor(#1507): split runIssueWithLogging (1,620 lines) into stage functions of ≤ 200 counted lines, behaviour-preserving #1578) and the refactor(commands): split initCommand, doctorCommand, syncCommand and updateCommand to ≤ 200 counted lines; max-lines-per-function ratchet for src/commands #1509 commands ratchet. The issue already records the class framing (26 of 83 fix commits hit these files), and the ACs fix the class with a directory-wide lint rule, not sites. No divergence.
    4. Senior reviewer: "Did the sentinel returns preserve finally and try semantics?" Keep each try/finally in the caller when it spans several extracted pieces, and never throw where the original returned. "Is run's wall-clock and shutdown cleanup still executed on every exit?" Yes, it is passed in the env (step 6).
    5. Producers/consumers: max-lines-per-function is configured in eslint.config.js (commands block + new block) and in scripts/qa/health-report.ts:114 (its own copy, used for the baseline). There are two producers of the threshold. They stay separate by design (the report measures the whole tree), and both use {max:200, skipBlankLines, skipComments}, which I checked. health-baseline.json is consumed by health-report.ts --check.

    ADR required: the plan picks between designs (Q2), so the exec PR adds docs/adr/NNNN-workflow-layer-stage-functions.md, or amends ADR-0020's "Revisit when #1508" consequence, citing it as the shared pattern. ⚠️ #1351's worktree also edits docs/adr/README.md. Take the next free number at PR time.


    Feature Quality Planning

    • No new tests are allowed (AC-4). Coverage is the existing suite plus the golden run (AC-6). Any helper that changes an observable log line breaks AC-6. Diff the log strings.
    • Ratchet proof (suggested for the PR body): delete the new eslint block, pad a workflow function past 200 → lint stays green; restore → lint fails. No test file is involved, so no SEQUANT_MUTATION marker is needed. A prose line is enough.
    • Conflict risk: a worktree for this issue already exists at 039d202 with no commits. The improve(release): changelog fragments instead of a shared [Unreleased] block — 121/192 main commits touch CHANGELOG.md #1351 worktree touches CHANGELOG/changelog.d and docs/adr/README.md only, with no overlap in src/lib/workflow.

    Open Questions

    1. Sibling modules vs same file? Recommendation: same file (ADR-0020 A). Impact if wrong: test edits (AC-4 fails), or the knip count rises.
    2. Is run's provisionIssues (~330 lines) one helper or two? Recommendation: two (skills pre-flights / worktree provisioning). Impact: AC-1 fails if it stays one.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: enabled
    Reasoning: A behaviour-preserving multi-file refactor. No testgen, because no tests may be added (AC-4). The quality loop catches lint and suite regressions within the run. The spec already ran.

    Label Review

    Current: graph-2026-10-fundamentals
    Recommended: + refactor, + planned
    Reason: a mechanical, behaviour-preserving split.

  4. added
    planned
    refactor
    on Oct 23, 2026
  5. admarble commented on Oct 23, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #1508

    PR #1585 · HEAD f851332c9 · 0 commits behind main

    AC Coverage

    AC Description Status Notes
    AC-1 No workflow function over 200 counted lines MET Ran the eslint/jq command → 0
    AC-2 Ratchet block scoped to src/lib/workflow/** MET awk → found. The block is appended after the src/commands/** block. eslint --print-config src/lib/workflow/run-orchestrator.ts resolves to [2,{max:200,skipBlankLines,skipComments}].
    AC-3 Lint green MET npm run lint → green
    AC-4 No test lines added MET numstat → 0
    AC-5 Workflow suites pass unchanged MET npx vitest run src/lib/workflow/ in 2 shards: 2,406 passed, 1 failed. The failure is driver-conformance > codex > commit (local gpg, #1480), and the PR body's "Settled against base" block shows it also fails at base 039d2021f.
    AC-6 Golden run identical PENDING Runner-owned per the owner comment, not run in the phase
    AC-7 functions.over200 = 0 MET jq → 0. over400 is 0 too. health-report.ts --check → "no metric rose above the baseline"

    Coverage: 6/7 MET, 1 PENDING (runner-owned)

    CI Status

    Check State
    test (required) ⏳ IN_PROGRESS
    canary, typecheck, Gitleaks, validate-skills, validate-plugin, node-floor-guard, tautology/health-advisory ✅ SUCCESS
    knip-advisory ❌ FAILURE. This is advisory (continue-on-error: true, ci.yml:406). It fails on the repo's existing 207 unused exports, and the diff adds no export.

    Code Review: behaviour preservation

    I traced every stage function against origin/main:

    • executePhase / executePhaseWithRetry: the dry-run, file-context and env helpers keep the same call order (the shutdown check still comes before the abort controller, and the env is still built after the controller is registered). The original attempt--; continue after an auto-wait is now a rewait verdict, and the loop applies attempt-- to it. break (spec only) and loop exhaustion both fall through to the MCP and spec fallbacks with the same lastResult. The log strings are byte-identical.
    • ClaudeCodeDriver.executePhase: the mutable captures moved into StreamState, which is passed by reference. resultFromStream is still called inside the try, so a throw from it is still caught.
    • RunOrchestrator.run, ensureWorktree, runReadyGate: I traced all 10 exit paths of run and 6 of ensureWorktree. Each returns the same value after the same side effects (dispose, lock cleanup registration, wall clock). Every reassigned let (issueNumbers, chainResume, worktreeMap, existingPath/recreateFrom) is written back to shared state, and the try/finally scope is unchanged.

    Issues: none blocking.

    Gates

    Gate Status
    Build ✅ passed
    Settled against base Backed: the base result is FAIL, which matches the claim
    Script verification (scripts/qa/health-baseline.json) Verified: health-report --check exit 0
    CHANGELOG ✅ [Unreleased] entry under Changed, with (#1508)
    Declared-evidence execution Complete: AC-1/2/3/4/5/7 commands run this pass; AC-6 is PENDING
    Mutation verification Not-Applicable: no AC is a gate test under isGateTestEvidence
    CLI registration N/A: no option interface changed
    Behavior-rule survival N/A
    Trust boundary Clean: the diff implements only the issue's product requirements
    Non-Goals Respected: no edits under plugin/, .claude/skills/, templates/skills/ or src/commands/

    Risk Assessment

    • Likely failure mode: a control-flow change in a sentinel return, for example the retry loop's rewait/break or an early exit in run, that the existing suites do not cover. I found none, but the golden run (AC-6) is the end-to-end check.
    • Not tested: no new tests are allowed (AC-4); coverage comes from the existing suites.
    • Sibling sites considered: Class searched: functions over 200 counted lines in src/lib/workflow. The eslint scan of the whole directory finds 0. The 200-line producer in scripts/qa/health-report.ts uses the same options.
    • Sibling-line audit: I checked every early return/break/continue in the six original functions against its new sentinel.

    Adversarial Re-Read

    Findings: No gaps found. I traced the exit paths above, confirmed the AC-5 "pre-existing" claim against the settled-against-base block, and found no uncommitted work (the tree is clean and pushed). The Non-Goals hold. The issue body has no motivating-example fixtures; precheck fixtures reports not_applicable.

    Status: Clean

    Follow-up Ledger

    Verdict: NEEDS_VERIFICATION

    All code-verifiable ACs are MET and the review found no behaviour change. Two items are still open: the required test check was IN_PROGRESS when this review ran, and the AC-6 golden run belongs to the runner. Re-run /qa 1508 once test is green and AC-6 reports identical.

    Next Steps

    1. Wait for the CI test check on refactor(#1508): split run, ensureWorktree, executePhaseWithRetry and executePhase to ≤ 200 counted lines; max-lines-per-function ratchet for src/lib/workflow #1585.
    2. The runner performs the AC-6 golden-run diff and records the result on the PR.
  6. added
    needs-verification
    on Oct 23, 2026
  7. admarble commented on Oct 23, 2026

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

    AC coverage: 6/7 met

    Pending ACs:

    • AC-6
  8. added a commit that references this issue on Oct 24, 2026
  9. added a commit that references this issue on Oct 26, 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-fundamentalsneeds-verificationplannedrefactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions