Skip to content

refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473

Closed

Description

@admarble

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

Problem

Five small helpers are defined twice or three times in non-test src/: ensureDir (lib/fs.ts exported and correct; relay/writer.ts a sync copy taking a file path; upstream/assessment.ts an async copy that swallows every error), escapeRegex (byte-identical in heuristics/behavior-rule-detector.ts, test-tautology-detector.ts, upstream/relevance.ts), formatTimestamp (commands/watch.ts takes an ISO string, lib/cli-ui/format.ts takes a Date, same hh:mm:ss), truncateToWidth (ui/tui/truncate.ts exported; lib/assess/renderer.ts a second width algorithm), and parseIssue (commands/locks.ts and commands/worktree.ts, identical except process.exitCode 1 vs 2).

Acceptance Criteria

  • AC-1: Each of ensureDir, escapeRegex, formatTimestamp, truncateToWidth and parseIssueNumber has exactly one definition in non-test src/, and parseIssue has none. Evidence: for s in ensureDir escapeRegex formatTimestamp truncateToWidth parseIssueNumber; do rg -l "function $s\(" src -g '!*.test.ts' | wc -l; done; rg -l 'function parseIssue\(' src -g '!*.test.ts' | wc -l → five lines of 1 then 0 (today: 3 3 2 2 0 then 2).
  • AC-2: ensureDir errors propagate from the upstream assessment writer with the mkdir diagnostic rather than the later writeFile one (D-2), and the relay writer still creates the parent directory of its file path. Note the module trap: src/lib/fs.ts imports fs/promises while src/lib/upstream/__tests__/assessment.test.ts:57 mocks node:fs/promises; vitest treats them as different modules, so normalise fs.ts to node:fs/promises or mock both. Evidence: npx vitest run src/lib/upstream/__tests__/assessment.test.ts src/lib/relay/__tests__/writer.test.ts -t "ensureDir" → ≥ 2 passed, 0 failed (writer.test.ts is new; an injected EACCES rejects the assessment write; the relay path's parent exists after a write); mutation-verified: restoring the swallowing catch {} in assessment.ts makes src/lib/upstream/__tests__/assessment.test.ts > ensureDir > a write error rejects fail.
  • AC-3: formatTimestamp accepts a Date or an ISO string and returns the same hh:mm:ss for both; an unparsable string returns the input unchanged (the watch.ts behaviour). Evidence: npx vitest run src/lib/cli-ui/format.test.ts -t "formatTimestamp" → ≥ 3 passed, 0 failed (new test file).
  • AC-4: src/lib/cli-ui/truncate.ts exports truncateToWidth (the TUI's hard cut: one column reserved for the ellipsis, … at width 1) and truncateAtWord (the assess renderer's word-boundary rule, moved unchanged). The TUI imports the first and the assess renderer the second, and neither one's output changes (D-3 as amended by the owner on 2026-10-19: the renderer's output is pinned byte for byte by frozen SKILL.md examples). Evidence: rg -l 'cli-ui/truncate.js' src/ui/tui src/lib/assess -g '!*.test.ts' | wc -l → 2, rg -c 'export function truncateAtWord\(' src/lib/cli-ui/truncate.ts → 1, npx vitest run src/lib/assess/renderer.test.ts src/lib/assess/skill-examples.test.ts src/ui/tui/truncate.test.ts → 0 failed, and git diff --name-only origin/main...HEAD | grep -cE '__snapshots__|SKILL\.md' → 0.
  • AC-5: parseIssueNumber in src/lib/cli-flags.ts returns number | null without touching process.exitCode, and locks still exits 1 while worktree still exits 2 on a bad argument. Evidence: npx vitest run src/lib/cli-flags.test.ts -t "parseIssueNumber" → ≥ 3 passed, 0 failed (valid, zero and non-numeric inputs; process.exitCode untouched), and rg -q 'process.exitCode = 1' src/commands/locks.ts && rg -q 'process.exitCode = 2' src/commands/worktree.ts && echo kept → kept. Mutation-verified: deleting the null branch of parseIssueNumber makes src/lib/cli-flags.test.ts > parseIssueNumber > non-numeric input returns null fail (the cli-flags path trips the parser's gate keyword, so the record is required).
  • AC-6: The detector no longer reports the five names on this branch (must run against the real dependency). Evidence: ACCRETION_HOME=$(mktemp -d) node ~/Projects/accretion-audit/dist/cli.js dups --repo "$PWD" --json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const n=new Set(JSON.parse(s).groups.map(g=>g.name));const hit=['ensureDir','escapeRegex','formatTimestamp','truncateToWidth','parseIssue'].filter(x=>n.has(x));console.log(hit.join(',')||'none');process.exit(hit.length?1:0)})" → none, exit 0.

Prior fixes / producers

May touch

src/lib/fs.ts, src/lib/regex.ts (new), src/lib/cli-flags.ts, src/lib/cli-ui/format.ts, src/lib/cli-ui/truncate.ts (new), src/ui/tui/truncate.ts, src/lib/relay/writer.ts, src/lib/upstream/assessment.ts, src/lib/heuristics/behavior-rule-detector.ts, src/lib/test-tautology-detector.ts, src/lib/upstream/relevance.ts, src/commands/watch.ts, src/commands/locks.ts, src/commands/worktree.ts, src/lib/assess/renderer.ts, their tests, the changelog entry. Serialize after #1471 (cli-ui/format.ts) and before #1474 (commands/locks.ts).
Folded in from #1471 (owner, 2026-10-19): src/lib/workflow/phase-executor.ts (drop the export { formatDuration } from "../cli-ui/format.js" re-export), src/commands/run-compat.ts and src/lib/workflow/phase-executor.test.ts (import formatDuration from cli-ui/format.ts).

Non-Goals

  • Changing the exit codes of locks or worktree, or any CLI message text.
  • The git helper in merge-check, skills-commit-state.ts and worktree-isolation.ts (different signatures, allowlisted noise per the Phase 0 labels).
  • Any edit under plugin/, .claude/skills/ or templates/skills/ (I-1).

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 #1472; 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: Standard (6 ACs, 12 directories)

    AC Quality Check

    All six ACs are single-line with an Evidence: clause. The commands are non-vacuous: AC-1 reads 3 3 2 2 0 / 2 on main (confirmed by grep), and the vitest targets (writer.test.ts, format.test.ts, the ensureDir and parseIssueNumber cases) do not exist yet.

    • AC-3 misdescribes watch.ts. new Date("garbage") does not throw, so the try/catch never fires and today's output is NaN:NaN:NaN. "Returns the input unchanged" is new behaviour, not the existing behaviour. Implement an explicit Number.isNaN(date.getTime()) guard and test it. The AC text should drop "(the watch.ts behaviour)".
    • AC-4 evidence counts IssueBox.tsx as one of the two importers. src/ui/tui/IssueBox.tsx must import cli-ui/truncate.js directly. src/ui/tui/truncate.ts is then deleted (or the AC-1 count stays 1 only via a re-export; deleting is cleaner). src/ui/tui/truncate.test.ts is kept and repointed at the new module (the AC runs it by that path).
    • AC-2's fix instruction is risky. Normalising fs.ts to node:fs/promises would break doctor.test.ts, stacks.test.ts and mcp/tools/run.test.ts, which mock "fs/promises". See Open Question 1.
    • AC-6 depends on ~/Projects/accretion-audit/dist/cli.js, which exists.

    Scope Assessment

    Non-Goals: present (exit codes, CLI text, git helper, plugin/ / .claude/skills/ / templates/skills/).

    Metric Value Status
    Feature count 1 (dedupe) ✅
    AC items 6 ✅
    Directory spread ~12 (mostly one-file edits) ⚠️

    Verdict: ✅ SCOPE_OK (wide but mechanical)


    Acceptance Criteria

    AC-1: One definition per helper

    Verification: Integration Test (the shell loop in Evidence:)
    Scenario: Given main (3 3 2 2 0, 2) → When the five dedupes land → Then 1 1 1 1 1 and 0.
    Assumptions: parseIssueNumber is a function declaration, not a const arrow, because the grep matches function parseIssueNumber(.

    AC-2: ensureDir errors propagate; relay still creates the parent

    Verification: Unit Test
    Scenario: Given mkdir rejects EACCES → When the assessment writer runs → Then it rejects with the mkdir error. Given a relay file path → When it is written → Then its parent dir exists.
    Assumptions: The relay writer is sync (mkdirSync) and takes a file path. fs.ts#ensureDir is async and takes a dir. See Phase 1, step 2.

    AC-3: formatTimestamp(Date | string)

    Verification: Unit Test (new src/lib/cli-ui/format.test.ts)
    Scenario: Given a Date and its ISO string → Then identical hh:mm:ss. Given "garbage" → Then "garbage".

    AC-4: Shared truncateToWidth

    Verification: Unit Test + snapshot
    Scenario: Given the assess renderer → When it uses the TUI algorithm → Then renderer tests pass. The … snapshots (3 in __snapshots__/renderer.test.ts.snap) may change, and the PR body lists any changes.
    Assumptions: The renderer currently prefers word boundaries (WORD_BOUNDARY_MIN_FILL = 0.7) and the TUI version hard-cuts. D-3 says to use the TUI algorithm, so the renderer loses word-boundary truncation. That is a visible behaviour change in /assess output.

    AC-5: parseIssueNumber in cli-flags.ts

    Verification: Unit Test
    Scenario: Given "12", "0", "abc" → Then 12, null, null, with process.exitCode untouched. locks sets 1 and worktree sets 2 at the call site.
    Note: The caller prints Invalid issue number: <arg> and sets the exit code. Keep the message in each caller or in a tiny shared line. Do not change the text. worktree.ts:98 also calls it (the verify path), so all five call sites need the update.

    AC-6: Detector reports none of the five names

    Verification: Integration Test (the accretion-audit command in Evidence:)
    Scenario: Given the branch after AC-1..5 → Then it prints none and exits 0.


    Implementation Plan

    Phase 1: Shared helpers (sequential; the first four steps touch disjoint files)

    1. escapeRegex: create src/lib/regex.ts and export it. Import it in behavior-rule-detector.ts, test-tautology-detector.ts and upstream/relevance.ts, and delete the three local copies. Add a small unit test, since the file is new.
    2. ensureDir: delete the swallowing copy in upstream/assessment.ts and import ensureDir from ../fs.js. Drop the mkdir import if it becomes unused. For relay/writer.ts, the sync file-path variant is the only non-duplicate shape. Either add ensureParentDirSync(filePath) to fs.ts and call it from the writer, or have the writer call mkdirSync(dirname(path), {recursive:true}) inline. The grep counts only function ensureDir(, so either satisfies AC-1. Prefer the fs.ts helper so there is one home. Add src/lib/relay/__tests__/writer.test.ts (new) and an ensureDir describe in assessment.test.ts.
    3. formatTimestamp: widen cli-ui/format.ts to Date | string with the NaN guard. watch.ts imports it and drops its copy. New format.test.ts.
    4. parseIssueNumber: add it to cli-flags.ts returning number | null. locks.ts (3 sites) and worktree.ts (2 sites) become parseIssueNumber(arg), which on null prints the same error and sets their own exit code. Delete both parseIssue copies.
    5. truncateToWidth: git mv src/ui/tui/truncate.ts src/lib/cli-ui/truncate.ts. Repoint IssueBox.tsx, truncate.test.ts and assess/renderer.ts. Delete the renderer copy. Run renderer.test.ts and update the snapshots deliberately. If word-boundary tests assert specific output, review each diff rather than blindly running -u.

    Phase 2: #1471 fold-in and hygiene

    1. Drop export { formatDuration } ... at phase-executor.ts:61. Point run-compat.ts:11 and phase-executor.test.ts:35 at cli-ui/format.ts. Grep the whole repo for other importers of formatDuration from phase-executor.
    2. Add [Unreleased] lines to CHANGELOG.md (not changelog.d/). Run npx tsx scripts/qa/health-report.ts --write-baseline after the last source change if a metric moved. npm run lint:health must print "no metric rose". Run AC-6 last.

    Verification order: tsc, the targeted npx vitest run <files>, the AC-1 loop, the AC-6 command, then one foreground full-suite run under timeout after a WIP commit.


    Design Review

    1. Where does this logic belong? Generic helpers in lib/ (fs.ts, regex.ts, cli-flags.ts) and UI helpers in lib/cli-ui/. Wide TUI-only helpers do not belong in ui/, because lib/assess would depend upward on it.
    2. Simplest correct approach? Move or delete the copies and import the survivor. Rejected: a barrel utils.ts (hides ownership), and keeping a re-export at ui/tui/truncate.ts (leaves a second path that the detector may flag).
    3. Existing pattern and re-patch count? The pattern is "one home per helper". The prior issues (ensureDir feat: add opencode agent driver — first backend that can inherit the full skill methodology #862 feat: opencode fidelity — hook shim (fail closed), subagent defs, MCP translation, error classes, CI smoke (#862 P1) #996 fix(sync): dry-run lists files apply never writes — the template walk maps templates/opencode/** to .claude/opencode/** (phantom drift nag in serve; update plants unrendered {{PHASE}} files) #1030 feat: add OpenAI Codex CLI agent driver #497, escapeRegex feat(spec,qa): detect behavior-rule implementations across skill+runtime touchpoints #552 fix(qa): tautology detector still flags a subprocess-driven CLI test file — __dirname-built paths evade #885's build-output heuristic #956 fix(upstream): file a finding issue only when the change touches something sequant uses; refresh the stale dependency map #1186 fix(skills): Claude Code ≥2.1.286 tells Claude to run any project skill named verify before every commit — Sequant's verify expects an issue number and posts to GitHub #1345, and so on) added copies with features, not fixes to the helper, so this fixes the class rather than the site. The recurrence is the reason for AC-6 as a standing detector check.
    4. What would a senior reviewer challenge? (a) "The renderer's word-boundary truncation was deliberate, so why drop it?" It is a recorded owner decision (D-3), and the PR must list snapshot changes. (b) "Why did the assessment writer swallow errors?" It is a latent bug that hid mkdir failures (D-2).
    5. Producers/consumers (whole-repo grep). ensureDir: consumers in init.ts, templates.ts, stack-config.ts, settings.ts, fs.ts itself. After the change the producers are fs.ts plus the relay sync helper. escapeRegex: 3 consumers, 1 producer. formatTimestamp: run-renderer.ts, watch.ts. truncateToWidth: IssueBox.tsx, renderer.ts. parseIssueNumber: 5 call sites in locks.ts and worktree.ts. No cross-package mirrors (plugin/, skills) are touched.

    Feature Quality Planning

    All standard checks pass. Notable items:


    Open Questions

    1. fs.ts module specifier. Normalise fs.ts to node:fs/promises (the AC's first option), or mock both specifiers in assessment.test.ts? Recommendation: mock both in assessment.test.ts, because three other suites (doctor, stacks, mcp/tools/run) mock plain "fs/promises" and normalising could break them. Impact if wrong: unrelated test failures, or the real mkdir runs in tests.
    2. AC-3 wording. Edit the AC to drop "the watch.ts behaviour" (the existing guard never fires). Recommendation: yes; behaviour is the same intent either way. Impact: none.
    3. Relay sync helper placement. Recommendation: fs.ts ensureParentDirSync, but an inline mkdirSync also satisfies AC-1.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: Mechanical refactor, tier mechanical. AC-2, AC-3 and AC-5 declare unit-test evidence, which would normally suggest testgen, but each names its test cases exactly, so exec can write them directly. Stop-at-PR per the runner comment.


    Label Review

    Current: refactor, graph-2026-10-consolidation
    Recommended: refactor, graph-2026-10-consolidation (no change)
    Quality Loop: Won't auto-enable; 6 ACs, SCOPE_OK.

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

    @admarble
    ContributorAuthor

    Owner decision, 2026-10-19: D-3 amended, and AC-4 rewritten in the body above. Exec halted with SPEC_DIVERGENCE because the original AC-4 would change the assess renderer's output, which frozen SKILL.md pins byte for byte (skill-examples.test.ts). The runner checked this: the renderer's copy prefers a word boundary and the TUI's cuts hard.

    Now: src/lib/cli-ui/truncate.ts exports two functions.

    • truncateToWidth, the TUI's hard cut, imported by src/ui/tui.
    • truncateAtWord, the renderer's word-boundary rule moved unchanged, imported by src/lib/assess/renderer.ts.

    Neither one's output changes, and there are no snapshot or SKILL.md edits. AC-1's "one definition of truncateToWidth" and AC-6's detector check hold, because the renderer's copy now has a different name. If truncateAtWord can call truncateToWidth for the hard cut without changing any renderer output, prefer that; otherwise keep it self-contained.

    For the re-run: commit 4e7bffa on this branch already holds the work for the other ACs. Build on it, and merge origin/main first; it is one commit behind. All the earlier runner context still applies, including the health-baseline correction and the qa-phase test note.

  6. added a commit that references this issue on Oct 19, 2026
  7. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 6/6 met

    Gaps:

    • CHANGELOG entry for refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473 is missing
    • Pre-existing failure claim is not backed by a settle-against-base block
    • PR body disclaims its own mutation markers; replace the disclaimer with the verified records
    • Third inline copy of the issue-number parse remains; should use parseIssueNumber
    • src/commands/locks.ts:610: locksCheckBatchCommand still has a third copy of the parse-issue logic, written inline in a loop, so AC-1's function grep doesn't catch it. Replacing it with parseIssueNumber would be trivial.
    • ensureParentDirSync is a new name next to ensureDir. That is acceptable because it is a different contract (sync, takes a file path), and its doc comment says so.
    • One behaviour change: watch now prints the raw timestamp string for an unparsable timestamp instead of NaN:NaN:NaN. This is the behaviour the AC prescribes.
  8. added 3 commits that reference 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