Skip to content

refactor(commands): split initCommand, doctorCommand, syncCommand and updateCommand to ≤ 200 counted lines; max-lines-per-function ratchet for src/commands #1509

Closed

Description

@admarble

Epic: graph-2026-10-fundamentals Tier: mechanical Execution: sequant_run Blocked by: #1502

Problem

Five command entry points exceed 200 counted lines (ESLint counting, measured 2026-10-18): initCommand (init.ts:618, 588), doctorCommand (doctor.ts:545, 555), syncCommand (sync.ts:452, 325), updateCommand (update.ts:69, 256), readyCommand (ready.ts, 206). They are linear sequences of steps, each already covered by unit and integration tests (init.test.ts + 3 integration files, doctor.test.ts + 2, sync.test.ts + 2, update.test.ts + 1, ready tests under src/commands/). None of these files is in a consolidation node's scope (#1471 touches commands/logs.ts and commands/stats.ts; #1475 touches commands/locks.ts).

Acceptance Criteria

  • AC-1: No function over 200 counted lines in src/commands. Evidence: npx eslint --rule 'max-lines-per-function: [error, {max: 200, skipBlankLines: true, skipComments: true}]' 'src/commands/**/*.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 for this directory. Evidence: grep -c "src/commands/\*\*" eslint.config.js → ≥ 1
  • 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 command suites pass unchanged. Evidence: npx vitest run src/commands/init src/commands/doctor src/commands/sync src/commands/update src/commands/ready → 0 failed
  • AC-6: The baseline moves down with the PR. Evidence: jq '.functions.over200' scripts/qa/health-baseline.json → ≤ 7

Prior fixes / producers

May touch

src/commands/init.ts, src/commands/doctor.ts, src/commands/sync.ts, src/commands/update.ts, src/commands/ready.ts, new sibling modules under src/commands/<name>/ for extracted steps, eslint.config.js (one appended block scoped to src/commands/**), scripts/qa/health-baseline.json (I-4), CHANGELOG entry. No test file (I-3).

Non-Goals

  • Any behaviour or output-wording change (the integration tests match output).
  • Any new shared helper that already exists (check src/lib/ first; D-C's accretion check applies).
  • No edits under plugin/, .claude/skills/, templates/skills/ (I-1).

Done when

src/commands has no function over 200 counted lines, the rule enforces it, and no test changed.

Activity

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

    @admarble
    ContributorAuthor

    Runner context, 2026-10-19, before launch (fundamentals W2, beside #1504 and #1512; stop-at-PR). main = 23a60b3.

    Changed since filing:

    #1475 (src/commands/locks.ts, lib/locks/) may run beside this. Stay within the five named command files.

    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. Prefer the targeted npx vitest run <files> for the ACs.
    CHANGELOG: add [Unreleased] lines under the existing ### Added / ### Changed headings, not changelog.d/ fragments, and never add a second heading of the same name.
    Lint: #1503 made no-unused-vars, no-empty-object-type and prefer-const errors, and knip counts unused exports. Don't export what nothing imports.
    Health baseline: regenerate scripts/qa/health-baseline.json (npx tsx scripts/qa/health-report.ts --write-baseline) only to record a metric that went down. If npm run lint:health reports a rise, restructure so it holds. Otherwise leave the baseline alone and name the rise in the PR body. Owner ruling: a proseGate.lines rise caused by tests in files that mention SKILL.md only as a path may be absorbed, and must be said so.
    Freeze: nothing under plugin/, .claude/skills/ or templates/skills/.

  3. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (6 ACs, 1 directory)

    AC Quality Check

    All six ACs are single-line with an Evidence: clause. Run against main (23a60b3):

    AC Today Gates?
    AC-1 5 (doctor 573, init 589, sync 325, update 256, ready 206) ✅ fails today
    AC-2 0 ✅ fails today
    AC-3 green constraint, passes today by design
    AC-4 0 constraint, passes today by design
    AC-5 passes today constraint (behaviour-preservation)
    AC-6 12 ✅ fails today

    Notes: AC-6 only works out exactly: 12 − 5 = 7, so all five functions must be fixed, and no other function may cross 200. AC-5's path prefixes (init, doctor, sync, update, ready) also match init.*.test.ts, doctor.*.test.ts, ready.*.test.ts and the integration files. No ambiguity.

    Scope Assessment

    Non-Goals: present (no behaviour or wording change, no new duplicate helpers, no edits under plugin/, .claude/skills/, templates/skills/).

    Metric Value Status
    Feature count 1 (extract steps, add ratchet) ✅
    AC items 6 ✅
    Directory spread 1 (src/commands) + eslint.config.js, baseline, CHANGELOG ✅

    Verdict: ✅ SCOPE_OK. Large diff (~2,000 lines moved), but mechanical.


    Acceptance Criteria

    AC-1: No function over 200 counted lines in src/commands

    Verification: Integration Test (lint command)
    Scenario: Given the five oversize commands → When steps are extracted → Then the ESLint count is 0.
    Assumptions: The rule counts skipBlankLines and skipComments; the heavy comment blocks in these files don't count, so only code lines matter.

    AC-2: Ratchet in eslint.config.js

    Verification: Integration Test (grep + lint)
    Scenario: Given the config has no max-lines-per-function block → When one block scoped to src/commands/**/*.ts is appended → Then grep ≥ 1, and a deliberately long function in a scratch file fails lint (mutation check).
    Assumptions: The #1503 relaxed block is gone (runner comment), so there is nothing to edit — append only. **/*.test.ts is already globally ignored.

    AC-3: Lint stays green

    Verification: Integration Test (npm run lint)
    Scenario: Then no new no-unused-vars / prefer-const errors; knip doesn't see new unused exports.

    AC-4: No test lines added

    Verification: Integration Test (git numstat)
    Scenario: Then added test lines = 0.

    AC-5: Command suites pass unchanged

    Verification: Integration Test (targeted vitest)
    Scenario: Then 0 failed from npx vitest run src/commands/init src/commands/doctor src/commands/sync src/commands/update src/commands/ready.
    Assumptions: Tests mock by module path (vi.mock("../lib/…")). Moving a call into a new module doesn't break mocks of the callee modules, but a mock of something the command file itself exports, or an ordered child_process mock queue, would shift. Read the tests before moving any call that spawns processes.

    AC-6: Baseline moves to ≤ 7

    Verification: Integration Test (jq)
    Scenario: Then npx tsx scripts/qa/health-report.ts --write-baseline writes over200: 7, and npm run lint:health passes. over400 should drop from 4 to 0–2 (init, doctor are ≥ 400 today).


    Implementation Plan

    Decision: where do extracted steps live? The issue permits src/commands/<name>/ sibling modules. Recommended: one directory per command, named for the command, with steps as plain functions taking a small context object. Rejected: extracting into src/lib/ (reaches beyond the "May touch" list and invites the duplicate-helper check) and splitting by closure (same total line count, no gain).

    Phase 1: Ratchet first, red (1 step)

    1. Append the src/commands/**/*.ts block to eslint.config.js (max-lines-per-function 200, skipBlankLines, skipComments; **/*.test.ts ignored already). Lint now reports exactly five errors, which is the work list.

    Phase 2: Split the five functions (parallel-safe; one file each)

    Each split must be a pure move: same call order, same output strings, same exit codes. Keep early-returns and process.exit in the command function; extract the bodies between them.

    1. ready.ts (206, trivial): extract the progress-UI setup (lines ~275–335) into a helper. Needs ~10 lines out.
    2. update.ts (256): src/commands/update/ with steps: resolveConfigTokens (the legacy-migration block, ~139–200), planChanges (changes + summary), applyChanges. The MCP pin and partial-install refusal stay ordered before any write (feat(update): respect the manifest's install scope — update on a skills-only install installs hooks, agents and settings.json #1482).
    3. sync.ts (325): src/commands/sync/ with resolveInstallScope, reportDrift/fast-path verify, previewApply, apply. Must reuse the install-scope logic from feat(update): respect the manifest's install scope — update on a skills-only install installs hooks, agents and settings.json #1482 shared with update.ts; extract once, import from both, no second copy (accretion dups must not report a new group).
    4. doctor.ts (573): check list is linear. Group Check 0..10 into src/commands/doctor/ modules by theme (install integrity: manifest/skills/hooks/settings; environment: git/gh/claude/agents; extras). Each returns its checks entries; doctorCommand concatenates in the original order. Keep issueFormInfoLine (feat(init): the issue form from the writing-issues guide becomes one template file that init writes to .github/ISSUE_TEMPLATE when the directory is absent; doctor reports its absence #1528) where it is called today.
    5. init.ts (589): src/commands/init/ with runPreflight (templates-root check, --upgrade-skills, --manifest-only), resolveStacks (the ~120-line stack prompt), scaffold (dirs, gitignore, config, settings), copyAndReport. Keep writeIssueFormIfAbsent call order.

    Phase 3: Baseline, CHANGELOG, verification

    1. Run AC-1..AC-5 commands. Regenerate the baseline (--write-baseline) only after over200 is 7 and lint:health shows nothing rising. Run knip/npm run lint for unused exports (don't export what nothing imports; use non-exported helpers where the command file is the sole caller).
    2. [Unreleased] line under the existing ### Changed heading in CHANGELOG (no new heading, no changelog.d/).
    3. Targeted vitest only, then one foreground full suite under timeout after a WIP commit (30-min wall).

    Dependencies: #1502 is closed. Phase 2 steps are independent, so they could be parallel in /exec, but they share the lint config and baseline; the WIP-commit-per-file rule (commit every 10 min) applies.


    Design Review

    1. Where does this logic belong? In src/commands/<command>/, next to the command that calls it. The commands layer owns orchestration; no new lib surface.
    2. Simplest correct approach? Pure move-extract with explicit params, no behaviour edits. Rejected: a generic step-runner/pipeline abstraction (new concept, risks output-order changes); raising the limit (defeats the AC).
    3. Pattern and re-patch history? Pattern: ratchet-per-directory lint (the relaxed block it replaces came from chore(lint): end the 2026-01 "temporarily relaxed" rules, add knip as an advisory job with a numeric baseline #1503). init.ts + sync.ts took 18 fix commits in 90 days (issue's own count), which is a class, not a site. This work addresses the class (size) for the directory; it adds no new fix to any of those 18 bugs. No divergence from the prescribed lever.
    4. What would a senior reviewer challenge? "A 600-line move diff hides behaviour changes." Answer: tests untouched (AC-4/5), output strings unchanged, and the PR should state per function which line ranges moved to which module so the diff can be read with git diff --color-moved.
    5. Producers and consumers. init.ts ← bin/cli.ts and tests; sync.ts/update.ts share feat(update): respect the manifest's install scope — update on a skills-only install installs hooks, agents and settings.json #1482 install-scope helpers (single owner needed); doctor.ts reuses checkSkillsInstalled with run pre-flight (feat(run): pre-flight the skills install — missing .claude/skills/ should fail fast, not flail for 30 minutes as a spec retry #813) — leave it as is. health-baseline.json is produced by health-report.ts only.

    No ADR required: not choosing between competing designs in a way that binds future work.


    Feature Quality Planning

    All standard checks pass. Notable items:

    • Mock-queue fragility (AC-5): ordered child_process mocks (reference_ordered_child_process_mocks) shift if an extraction changes the git/gh call order. Preserve order.
    • Untestable mutation check for AC-2: record Mutation-verified: AC-2 — delete the eslint block; <test> failed; restored. only if a test gates it; the AC is a lint command, so proof is the red lint in Phase 1 (the five errors) before the splits.
    • Sibling scan: other src/commands functions are < 200 today (lint reports exactly five). run.ts / ready.ts large helper closures are not flagged; no scope widening.
    • No derived ACs.

    Open Questions

    1. Directory layout: src/commands/doctor/ next to doctor.ts, or doctor-checks.ts flat files? Recommendation: directories per the issue. Impact if wrong: only import paths.
    2. Does doctor.ts end up as a one-line wrapper? Recommendation: keep exported doctorCommand and DoctorOptions in doctor.ts so imports and vi.mock paths in tests don't change. Impact: tests would need edits (violates AC-4).

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: enabled
    Reasoning: Mechanical refactor with existing test coverage; no new tests are allowed (AC-4), so testgen is skipped. No UI. Quality loop on because the diff is large and the behaviour-preservation check is the main risk.

    Label Review

    Current: graph-2026-10-fundamentals
    Recommended: + refactor, planned
    Reason: Refactor label signals the quality loop; planned marks spec done.
    Quality Loop: Enabled (set above).

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

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 6/6 met

    Gaps:

    • PR conflicts with main in the health baseline, so required CI never ran; merge origin/main and regenerate the baseline so it keeps over200=7 and main's lower emptyCatch.total=117 / unusedExports=341
    • The ratchet's comment names a layout this PR did not use; reword it to allow same-file helpers
    • The PR can't merge because of the conflict in the health baseline. Resolving it needs care: taking this branch's side keeps emptyCatch.total: 118 and unusedExports: 342. Main lowered those to 117 and 341, so the ratchet would get looser.
    • Fix: merge origin/main, then run npx tsx scripts/qa/health-report.ts --write-baseline again so the baseline has over200: 7 together with main's lower counts.

    Suggestions:

    • The new comment in eslint.config.js says the steps belong in "a sibling module under src/commands/<name>/", but this PR keeps them as non-exported helpers in the same file. Either reword the comment or accept both layouts.
  6. added 2 commits that reference this issue on Oct 19, 2026
  7. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Execution Verification (runner, 2026-10-19), PR #1561 @ f7802c7

    After merging main (through #1558), the runner re-ran AC-1..AC-6 verbatim:

    • AC-1: 0
    • AC-2: 1
    • AC-3: green
    • AC-4: 0
    • AC-5: 414 passed (the five command suites + templates.test.ts)
    • AC-6: 7
    • Build exit 0.

    The baseline records functions.over200 7 (from 12) and over400 2 (from 4), with main's lower emptyCatch/unusedExports counts kept.

    Control flow: the runner compared every early return in the old init/doctor/sync/update/ready command functions with the split.

    QA's documentation finding is fixed: the eslint ratchet comment now allows same-file step functions.

  8. added a commit that references this issue on Oct 20, 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-fundamentalsplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions