Repository navigation
Description
Epic: graph-2026-10-consolidation Tier: judgment Execution: sequant_run
- Blocked by: tracker: graph-2026-10-consolidation — one definition per helper for the 16 duplicate groups the accretion audit found at ad71b341 #1470
- Blocked by: refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473
Problem
Three predicate copies of git -C <worktree> status --porcelain decide worktree dirtiness with different failure defaults, on purpose and documented: src/lib/workflow/worktree-manager.ts:399 returns true on a git failure (the cleanup guard at :469 keeps an unknown worktree, #935); src/lib/workflow/run-orchestrator.ts:99 returns false (the chain-resume resolver contract at chain-resume.ts:77-80 says a missing worktree is the branch-tip check's case, #760); checkWorktreeFreshness at worktree-manager.ts:301 leaves its flag false on failure. A boolean must lie in one direction: today the shutdown log at :502 prints "preserved (uncommitted changes): " when the status was merely unreadable, including for a path that no longer exists. A fourth hand-copied check lives in chain-resume.integration.test.ts:105-112. Separately, formatSignalLine is an identical switch in commands/locks.ts:18 and run-orchestrator.ts:49, except a two-space indent and one shortened message.
Acceptance Criteria
- AC-1: One
worktreeStatus(path): "clean" | "dirty" | "unknown"inworktree-manager.tsis the only predicate spawn ofgit status --porcelaininsrc/lib/workflow; the three porcelain parsers (worktree-manager.tscheckpoint-z,phase-executor.ts--untracked-files=all,qa-stagnation.ts) are untouched. Evidence:rg -n '"status", "--porcelain"\]' src/lib/workflow -g '!*.test.ts' | wc -l→1(3 today:run-orchestrator.ts:102,worktree-manager.ts:303,:402). - AC-2: The primitive is truthful on real git: clean and dirty worktrees, a non-existent path, an existing non-repo directory, and a worktree whose admin dir was removed. Evidence:
npx vitest run src/lib/workflow/worktree-manager.test.ts -t "worktreeStatus"→ ≥ 5 passed, 0 failed (index.lockheld still reads clean/dirty, exit 0; the three failure cases readunknown); mutation-verified: mapping a non-zero exit tocleanmakessrc/lib/workflow/worktree-manager.test.ts > worktreeStatus > a non-existent path is unknownfail. - AC-3: Each caller keeps its documented default (D-1b):
worktreePreserveReasonpreserves onunknownwith a reason that is not "uncommitted changes"; the chain-resume resolver treatsunknownas not dirty and resumes on the branch tip. Evidence:npx vitest run src/lib/workflow/worktree-manager.test.ts src/lib/workflow/chain-resume.integration.test.ts -t "unknown|nonexistent|gone"→ ≥ 2 passed, 0 failed (worktreePreserveReason(abort, "/nonexistent")is non-null and not "uncommitted changes"; aready_for_mergelink whose worktree dir is removed but branch intact resumes withoutfailFast, using the real primitive instead of the hand copy). - AC-4: One
formatSignalLine(issue, pid, result, { indent })produces thelockslines unindented and the orchestrator lines with the two-space indent, with one message text per reason. Evidence:npx vitest run src/lib/locks/signal-line.test.ts→ ≥ 2 passed, 0 failed (new file beside the new export). - AC-5: The detector no longer reports the two 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=['isWorktreeDirty','formatSignalLine'].filter(x=>n.has(x));console.log(hit.join(',')||'none');process.exit(hit.length?1:0)})"→none, exit 0.
Prior fixes / producers
isWorktreeDirty: feat: resume a partially-completed chain from its last good link #760 (orchestrator copy, chain resume), fix(run): abort-path paper cuts — "work is preserved in <worktree>" is false under SIGTERM, andabort's doc comment cites the wrong issue #935 (signal shutdown). Two producers of one git call with opposite, documented failure defaults; D-1b keeps both defaults at the call sites and shares only the primitive. Neither default is pinned by a test today (worktree-manager.test.ts:652-677use readable worktrees only). No owner gate.formatSignalLine: defense: LockManager.signalOther should guard against signaling self/parent PID #637 only. Two producers of the same text.run-orchestrator.tsalready imports fromworktree-manager.ts(:31-39) andchain-resume.tsimports onlycompleted-status, so the shared primitive adds no cycle; the booleanCompletedLinkResolverinterface (chain-resume.ts:81) and its unit stubs stay as they are.
May touch
src/lib/workflow/worktree-manager.ts, src/lib/workflow/run-orchestrator.ts, src/lib/workflow/chain-resume.integration.test.ts, src/lib/locks/ (one new export beside signalOther), src/commands/locks.ts, their tests, the changelog entry. Serialize after #1473 (commands/locks.ts).
Non-Goals
- Changing any caller's default for
unknown, or the chain-resume contract. - The three porcelain parsers named in AC-1.
- Any edit under
plugin/,.claude/skills/ortemplates/skills/(I-1).
Activity
docs(#1470): graph-2026-10-consolidation founding doc, issue graph an…
admarble commentedon Oct 19, 2026
Runner context, 2026-10-19, before launch (consolidation W3, beside #1504/#1509/#1512; stop-at-PR; judgment tier, all phases on Opus). main = 755d475.
Changed since filing (10-16):
src/commands/locks.tsnow callsparseIssueNumbereverywhere (refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473, 755d475).cli-ui/format.tsholdsformatDurationandformatTimestamp(refactor(logs): one run-log module — parseLogFile, listLogFiles, resolveLogDir, formatDuration defined once #1471, refactor(lib): one definition each for ensureDir, escapeRegex, formatTimestamp, truncateToWidth, parseIssueNumber #1473).worktree-manager.tschanged in 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 (a failedgit worktree addfails the issue), fix(worktree): an existing branch for issue N is reused whatever the title — a gh blip or a retitle cuts feature/N-issue-n from main and QA reviews main #1487 (branch reuse by issue number), fix(run): phase agents never get SEQUANT_BASE_BRANCH — skills fall back to main on master-default repos #1460 and fix(worktree): a non-default bare --base is cut from local <base> but counted against origin/<base> (#1380 follow-up, #1234/#1386 class) #1406. Keep each fix's behaviour. The tests for each are inworktree-manager.test.ts.Parallel runs: #1509 (init/doctor/sync/update/ready) and #1504 (
batch-executor.ts) run at the same time. Stay within this issue's May-touch 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 targetednpx vitest run <files>for the ACs.CHANGELOG: add
[Unreleased]lines under the existing### Added/### Changedheadings, notchangelog.d/fragments, and never add a second heading of the same name.Lint: #1503 made
no-unused-vars,no-empty-object-typeandprefer-consterrors, 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. Ifnpm run lint:healthreports a rise, restructure so it holds. Otherwise leave the baseline alone and name the rise in the PR body. Owner ruling: aproseGate.linesrise caused by tests in files that mentionSKILL.mdonly as a path may be absorbed, and must be said so.Freeze: nothing under
plugin/,.claude/skills/ortemplates/skills/.admarble commentedon Oct 19, 2026
Complexity: Complex (5 ACs, 3 directories)
AC Quality Check
I ran each
Evidence:command againstmain(755d475). None of them passes today, but AC-3 is weaker than it looks:main3(worktree-manager.ts:368,:467,run-orchestrator.ts:102):303,:402) are out of date; the count is still right. The-zcheckpoint parser at:1685correctly does not match.-t "unknown|nonexistent|gone"already matches an unrelated test:#1247 AC-2 … isAutomatedPRBody: … unknown body is not overwritten. So "≥ 2 passed" needs only one new test, not the two the AC describes. See Open Question 1.isWorktreeDirty,formatSignalLine, exit 1All ACs are single-line, have
Evidence:clauses, and a## Non-Goalssection exists.Scope Assessment
Non-Goals: callers'
unknowndefaults and the chain-resume contract stay as they are; the three porcelain parsers are not touched; nothing underplugin/,.claude/skills/ortemplates/skills/.src/lib/workflow,src/lib/locks,src/commands)Verdict: ✅ SCOPE_OK
Acceptance Criteria
AC-1:
worktreeStatusis the only predicate spawn ofgit status --porcelaininsrc/lib/workflowVerification: Integration Test (the
rgcount) plus review.Scenario: Given the three call sites → When all three route through
worktreeStatus→ Then thergcount is1, and the-zand--untracked-files=allparsers andqa-stagnation.tsshow no diff.Assumptions:
checkWorktreeFreshness(:368) is in scope even though it isn't namedisWorktreeDirty, because the count of 1 requires it.AC-2: The primitive reports the truth on real git
Verification: Unit Test (real git in a tmpdir)
Scenario: Given clean, dirty,
index.lock-held, non-existent, non-repo and admin-dir-removed worktrees → WhenworktreeStatusruns → Then it returnsclean/dirty/ (clean or dirty) /unknown/unknown/unknown.Assumptions (checked locally, git 2.x): with
index.lockheld,git status --porcelainexits 0 and still lists?? x. Non-existent path, non-repo dir and removed.git/worktrees/<name>each exit 128. The non-repo dir must sit undermkdtemp(tmpdir()), outside any repo; otherwise git walks up the tree to an enclosing repo.AC-3: Each caller keeps its documented default
Verification: Unit Test (
worktreePreserveReason) + Integration Test (chain resume)Scenario A: Given
abortnon-null and the path/nonexistent→ WhenworktreePreserveReasonruns → Then the result is non-null and is not"uncommitted changes".Scenario B: Given a
ready_for_mergelink whose worktree dir isrm -rf'd but whose branch is intact → WhencomputeChainResumePlanruns with the real primitive → Then there is nofailFast, andresumeBaseis the branch.Assumptions: On
unknown,worktreePreserveReasonmust return its own reason beforehasCommitsAheadOfBaseruns. That check also fails towardtrueon a missing path, so falling through would mislabel the log line as "commits ahead of base".AC-4: One
formatSignalLine(issue, pid, result, { indent })Verification: Unit Test
Scenario: Given each
SignalReason→ When it is formatted with no indent and withindent: " "→ Then the two lines differ only by the prefix, with one text per reason.Assumptions: The only existing text assertion is
locks-cli.integration.test.ts:221(cross-host), and that text is the same in both copies.AC-5: The detector no longer reports
isWorktreeDirty/formatSignalLineVerification: Integration Test (real
accretion-auditCLI)Assumptions (checked): the detector groups only named function declarations in 2+ files. The interface method
chain-resume.ts:81and the object-literal properties (isWorktreeDirty: (p) => …) don't count. So the orchestrator's resolver must use an inline arrow, not a renamed localfunction isWorktreeDirty.Implementation Plan
Phase 1: Tri-state primitive (
src/lib/workflow/worktree-manager.ts)export type WorktreeStatus = "clean" | "dirty" | "unknown"andexport function worktreeStatus(worktreePath): WorktreeStatus. It spawnsgit -C <path> status --porcelainwithstdio: "pipe"and noencoding, matching this module's.toString()idiom (therun.test.tsmocks return Buffers). It returnsunknownonresult.errororstatus !== 0, anddirtywhen the trimmed stdout is non-empty. The doc comment says why there are three states: a boolean has to be wrong in one direction or the other (fix(run): abort-path paper cuts — "work is preserved in <worktree>" is false under SIGTERM, andabort's doc comment cites the wrong issue #935 vs feat: resume a partially-completed chain from its last good link #760).isWorktreeDirty(:464). Its only consumer isworktreePreserveReason; leaving it would trip knip.worktreePreserveReason:const status = worktreeStatus(path); if (status === "dirty") return "uncommitted changes"; if (status === "unknown") return "worktree status unreadable";, then the existing phase and ahead-of-base checks. Rule order stays the same, and the default (preserve on unknown) is unchanged.checkWorktreeFreshness:result.hasUncommittedChanges = worktreeStatus(worktreePath) === "dirty";at the same position, so the orderedmockReturnValueOncequeue inrun.test.ts:1837+keeps its order (fetch → status → merge-base …). Its default (false on failure) is unchanged.Phase 2: Orchestrator + chain-resume test
run-orchestrator.ts: delete the localisWorktreeDirty(:90-112, doc comment included). ImportworktreeStatusinto the existing./worktree-manager.jsimport block (:31-39). In the resolver (:919):isWorktreeDirty: (worktreePath) => worktreeStatus(worktreePath) === "dirty",plus a one-line comment:unknownis not dirty, and the branch-tip check covers a gone worktree (feat: resume a partially-completed chain from its last good link #760,chain-resume.ts:77-80).chain-resume.integration.test.ts:105-112: replace the hand copy with the same arrow over the importedworktreeStatus. Add the AC-3 Scenario B case:rmSync(link1Worktree)with the branch kept, then expect nofailFastandresumeBase === link1Branch. Name it so it matches AC-3's filter (e.g. "…worktree dir is gone…").Phase 3: Signal line (
src/lib/locks/)src/lib/locks/signal-line.ts:export function formatSignalLine(issue, pid, result: SignalOtherResult, options?: { indent?: string }): string. It holds one switch and prefixesoptions?.indent ?? "".stale-pid-untrusteduses the longerlocks.tstext ("…recycled onto an unrelated process"); see Open Question 2. Re-export it fromsrc/lib/locks/index.ts.commands/locks.ts: delete the local function and import from../lib/locks/index.js(it already importsSignalOtherResultthere; drop that type import if nothing else uses it, or lint fails).run-orchestrator.ts:1071: callformatSignalLine(issueNumber, previous.pid, result, { indent: " " }), and drop the now-unusedSignalOtherResulttype import if nothing else uses it.src/lib/locks/signal-line.test.ts: (a) everySignalReasonyields a non-empty line containing#<issue>, andpidwhere applicable; (b)indent: " "output ===" " +the unindented output for every reason.Phase 4: Tests + changelog
worktree-manager.test.ts: newdescribe("worktreeStatus", …)(real git,realpathSync(mkdtempSync(tmpdir()))like the#1222block at:608) with six cases: clean, dirty,index.lockheld, "a non-existent path is unknown" (this exact name, since the AC-2 mutation record cites it), existing non-repo dir, and admin dir removed (rmSync(join(clone, ".git/worktrees/<name>"))). AddworktreePreserveReason(abort, "/nonexistent")→ non-null and!== "uncommitted changes", named to match AC-3's filter.status !== 0 → "unknown"to→ "clean", confirmworktree-manager.test.ts > worktreeStatus > a non-existent path is unknownfails, restore, and record theSEQUANT_MUTATIONmarker in the PR body. Do the same for AC-3: delete theunknownreason line, and the/nonexistenttest fails (it falls through to "commits ahead of base", which is non-null, so the assertion has to be on the text, not just non-null; see the risk below).CHANGELOG.md[Unreleased]→ existing### Changed: one line. The shutdown log now says "worktree status unreadable" instead of "uncommitted changes" whengit statusfails.Dependencies: #1473 is closed and merged at 755d475, the current main; it was the
commands/locks.tsserialization point. #1470 is the open tracker (not a code blocker). There is no overlap with the parallel #1504 (batch-executor.ts) or #1509 (init/doctor/…) worktrees.Design Review
worktree-manager.ts, the module that owns worktree git calls;run-orchestratoralready imports from it, andchain-resume.tsstays git-free behind its boolean resolver interface.formatSignalLinebelongs insrc/lib/locks/besideSignalOtherResult, the type it switches on.unknowninto its own documented default in one expression. Rejected: a boolean with afailDefaultparameter. It removes the duplication, but the shutdown log still can't tell "dirty" from "unreadable", and that wrong log line is the bug this issue fixes. Also rejected: changingCompletedLinkResolverto tri-state (a Non-Goal, and it breaks the unit stubs).isWorktreeDirty: feat: resume a partially-completed chain from its last good link #760 (orchestrator copy) and fix(run): abort-path paper cuts — "work is preserved in <worktree>" is false under SIGTERM, andabort's doc comment cites the wrong issue #935 (shutdown copy), two producers that disagree on failure. This issue fixes the class (one primitive, defaults at the call site, D-1b), so it is not a divergence.formatSignalLine: defense: LockManager.signalOther should guard against signaling self/parent PID #637 only. The tri-state follows the existingresolveBaseRef/hasCommitsAheadOfBasestyle of naming the failure branch explicitly.=== "dirty".git status --porcelain:worktree-manager.ts:368,:467andrun-orchestrator.ts:102collapse to 1; the test hand copy atchain-resume.integration.test.ts:105becomes a consumer.worktreePreserveReason→shouldPreserveWorktree/cleanupWorktreeOnShutdown(log line);checkWorktreeFreshness→ensureWorktree:1113,run-compat.ts; the orchestrator resolver →chain-resume.ts:190.formatSignalLineproducers:locks.ts:19andrun-orchestrator.ts:49collapse to 1. Consumers:locks.ts:462,run-orchestrator.ts:1071, and the text assertion inlocks-cli.integration.test.ts:221.ADR: not needed. The one design choice (tri-state, defaults at call sites) is D-1b, already decided in the issue; the rejected alternatives above are recorded for the PR body.
Feature Quality Planning
All standard checks pass. Notable items:
/nonexistenttest only assertsnot.toBeNull(), deleting theunknownbranch still passes ("commits ahead of base"). Assertnot.toBe("uncommitted changes")andtoBe("worktree status unreadable"), or the mutation doesn't prove anything.isWorktreeDirtyand both localformatSignalLines may orphan theSignalOtherResulttype imports. ExportWorktreeStatusonly if something imports it, or keep it unexported (knip).timeout, after a WIP commit (runner context).failedTestmust start with the file path (src/lib/workflow/worktree-manager.test.ts > worktreeStatus > a non-existent path is unknown).Derived ACs
run.test.ts > checkWorktreeFreshness (#305 AC-3)andworktree-manager.test.ts > #1222 AC-2stay green, unchangedworktreeStatusmaps a spawnerror(e.g. ENOENT) tounknown, not a throwOpen Questions
Evidence:to-t "status unknown|worktree dir is gone"(or raises the bar to "≥ 3 passed"), and exec names the two new tests to match. Impact if left as is: QA can count one new test plusisAutomatedPRBodyas "≥ 2".stale-pid-untrustedtext wins? Recommendation: the longerlocks.tstext ("…recycled onto an unrelated process"); it gives more information, and no test pins either version. Impact: the orchestrator's log line gets longer.unknown. Recommendation:"worktree status unreadable"→ log:Worktree for #N preserved (worktree status unreadable): <path>. Impact: cosmetic, but it is the user-facing fix, so the changelog line quotes it.Recommended Workflow
Phases: exec → qa
Quality Loop: enabled
Reasoning:
refactorlabel, 5 ACs, plus behaviour-preservation risk in shutdown cleanup and chain resume. The AC test files are spelled out precisely, so testgen would add little.Label Review
Current:
refactor,graph-2026-10-consolidationRecommended: add
plannedQuality Loop: auto-enabled by the
refactorlabel.admarble commentedon Oct 19, 2026
QA Verdict: NEEDS_VERIFICATION
AC coverage: 5/5 met
Gaps:
Needs human review:
admarble commentedon Oct 19, 2026
Execution Verification (runner, 2026-10-19), PR #1563 @ 770c6b8
QA returned NEEDS_VERIFICATION, with CI as the only gap. The runner re-ran AC-1..AC-5 verbatim:
1nonelint:healthshows no rise (unusedExportscan fall 341 → 339).AC-2 mutation repeated: mapping a non-zero
git statusexit tocleanfailsa non-existent path is unknownplus 3 sibling cases. Restored.QA's dropped finding (the
SignalOtherResultre-export now has no importer) is advisory. knip counts it, and the count fell overall.chore(#1475): merge main; baseline records unusedExports 339