Skip to content

refactor(workflow,locks): worktreeStatus tri-state replaces both isWorktreeDirty copies; one formatSignalLine #1475

Closed

Description

@admarble

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

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" in worktree-manager.ts is the only predicate spawn of git status --porcelain in src/lib/workflow; the three porcelain parsers (worktree-manager.ts checkpoint -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.lock held still reads clean/dirty, exit 0; the three failure cases read unknown); mutation-verified: mapping a non-zero exit to clean makes src/lib/workflow/worktree-manager.test.ts > worktreeStatus > a non-existent path is unknown fail.
  • AC-3: Each caller keeps its documented default (D-1b): worktreePreserveReason preserves on unknown with a reason that is not "uncommitted changes"; the chain-resume resolver treats unknown as 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"; a ready_for_merge link whose worktree dir is removed but branch intact resumes without failFast, using the real primitive instead of the hand copy).
  • AC-4: One formatSignalLine(issue, pid, result, { indent }) produces the locks lines 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

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/ or templates/skills/ (I-1).

Activity

  1. added
    refactor
    graph-2026-10-consolidation
    on Oct 16, 2026
  2. added a commit that references this issue on Oct 16, 2026
  3. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    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):

    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 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/.

  4. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (5 ACs, 3 directories)

    AC Quality Check

    I ran each Evidence: command against main (755d475). None of them passes today, but AC-3 is weaker than it looks:

    AC Result on main Note
    AC-1 3 (worktree-manager.ts:368, :467, run-orchestrator.ts:102) ✅ Fails today. The issue's line numbers (:303, :402) are out of date; the count is still right. The -z checkpoint parser at :1685 correctly does not match.
    AC-2 0 passed, 77 skipped ✅ Fails today.
    AC-3 1 passed, 82 skipped ⚠️ Partly vacuous. -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.
    AC-4 file does not exist ✅ Fails today.
    AC-5 isWorktreeDirty,formatSignalLine, exit 1 ✅ Fails today. Each group has exactly two locations: the two function declarations.

    All ACs are single-line, have Evidence: clauses, and a ## Non-Goals section exists.


    Scope Assessment

    Non-Goals: callers' unknown defaults and the chain-resume contract stay as they are; the three porcelain parsers are not touched; nothing under plugin/, .claude/skills/ or templates/skills/.

    Metric Value Status
    Feature count 2 (tri-state primitive, shared signal line) ✅
    AC items 5 ✅
    Directory spread 3 (src/lib/workflow, src/lib/locks, src/commands) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: worktreeStatus is the only predicate spawn of git status --porcelain in src/lib/workflow

    Verification: Integration Test (the rg count) plus review.
    Scenario: Given the three call sites → When all three route through worktreeStatus → Then the rg count is 1, and the -z and --untracked-files=all parsers and qa-stagnation.ts show no diff.
    Assumptions: checkWorktreeFreshness (:368) is in scope even though it isn't named isWorktreeDirty, 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 → When worktreeStatus runs → Then it returns clean / dirty / (clean or dirty) / unknown / unknown / unknown.
    Assumptions (checked locally, git 2.x): with index.lock held, git status --porcelain exits 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 under mkdtemp(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 abort non-null and the path /nonexistent → When worktreePreserveReason runs → Then the result is non-null and is not "uncommitted changes".
    Scenario B: Given a ready_for_merge link whose worktree dir is rm -rf'd but whose branch is intact → When computeChainResumePlan runs with the real primitive → Then there is no failFast, and resumeBase is the branch.
    Assumptions: On unknown, worktreePreserveReason must return its own reason before hasCommitsAheadOfBase runs. That check also fails toward true on 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 with indent: " " → 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 / formatSignalLine

    Verification: Integration Test (real accretion-audit CLI)
    Assumptions (checked): the detector groups only named function declarations in 2+ files. The interface method chain-resume.ts:81 and the object-literal properties (isWorktreeDirty: (p) => …) don't count. So the orchestrator's resolver must use an inline arrow, not a renamed local function isWorktreeDirty.


    Implementation Plan

    Phase 1: Tri-state primitive (src/lib/workflow/worktree-manager.ts)

    1. Add export type WorktreeStatus = "clean" | "dirty" | "unknown" and export function worktreeStatus(worktreePath): WorktreeStatus. It spawns git -C <path> status --porcelain with stdio: "pipe" and no encoding, matching this module's .toString() idiom (the run.test.ts mocks return Buffers). It returns unknown on result.error or status !== 0, and dirty when 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, and abort's doc comment cites the wrong issue #935 vs feat: resume a partially-completed chain from its last good link #760).
    2. Delete the exported isWorktreeDirty (:464). Its only consumer is worktreePreserveReason; leaving it would trip knip.
    3. 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.
    4. checkWorktreeFreshness: result.hasUncommittedChanges = worktreeStatus(worktreePath) === "dirty"; at the same position, so the ordered mockReturnValueOnce queue in run.test.ts:1837+ keeps its order (fetch → status → merge-base …). Its default (false on failure) is unchanged.

    Phase 2: Orchestrator + chain-resume test

    1. run-orchestrator.ts: delete the local isWorktreeDirty (:90-112, doc comment included). Import worktreeStatus into the existing ./worktree-manager.js import block (:31-39). In the resolver (:919): isWorktreeDirty: (worktreePath) => worktreeStatus(worktreePath) === "dirty", plus a one-line comment: unknown is 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).
    2. chain-resume.integration.test.ts:105-112: replace the hand copy with the same arrow over the imported worktreeStatus. Add the AC-3 Scenario B case: rmSync(link1Worktree) with the branch kept, then expect no failFast and resumeBase === link1Branch. Name it so it matches AC-3's filter (e.g. "…worktree dir is gone…").

    Phase 3: Signal line (src/lib/locks/)

    1. New src/lib/locks/signal-line.ts: export function formatSignalLine(issue, pid, result: SignalOtherResult, options?: { indent?: string }): string. It holds one switch and prefixes options?.indent ?? "". stale-pid-untrusted uses the longer locks.ts text ("…recycled onto an unrelated process"); see Open Question 2. Re-export it from src/lib/locks/index.ts.
    2. commands/locks.ts: delete the local function and import from ../lib/locks/index.js (it already imports SignalOtherResult there; drop that type import if nothing else uses it, or lint fails). run-orchestrator.ts:1071: call formatSignalLine(issueNumber, previous.pid, result, { indent: " " }), and drop the now-unused SignalOtherResult type import if nothing else uses it.
    3. New src/lib/locks/signal-line.test.ts: (a) every SignalReason yields a non-empty line containing #<issue>, and pid where applicable; (b) indent: " " output === " " + the unindented output for every reason.

    Phase 4: Tests + changelog

    1. worktree-manager.test.ts: new describe("worktreeStatus", …) (real git, realpathSync(mkdtempSync(tmpdir())) like the #1222 block at :608) with six cases: clean, dirty, index.lock held, "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>"))). Add worktreePreserveReason(abort, "/nonexistent") → non-null and !== "uncommitted changes", named to match AC-3's filter.
    2. Mutation-verify AC-2 (commit first): change status !== 0 → "unknown" to → "clean", confirm worktree-manager.test.ts > worktreeStatus > a non-existent path is unknown fails, restore, and record the SEQUANT_MUTATION marker in the PR body. Do the same for AC-3: delete the unknown reason line, and the /nonexistent test 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).
    3. CHANGELOG.md [Unreleased] → existing ### Changed: one line. The shutdown log now says "worktree status unreadable" instead of "uncommitted changes" when git status fails.

    Dependencies: #1473 is closed and merged at 755d475, the current main; it was the commands/locks.ts serialization 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

    1. Where does this logic belong? The primitive belongs in worktree-manager.ts, the module that owns worktree git calls; run-orchestrator already imports from it, and chain-resume.ts stays git-free behind its boolean resolver interface. formatSignalLine belongs in src/lib/locks/ beside SignalOtherResult, the type it switches on.
    2. What's the simplest correct approach? One spawn and three states, with each caller turning unknown into its own documented default in one expression. Rejected: a boolean with a failDefault parameter. 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: changing CompletedLinkResolver to tri-state (a Non-Goal, and it breaks the unit stubs).
    3. What existing pattern does this follow, and how often has it been re-patched? 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, and abort'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 existing resolveBaseRef/hasCommitsAheadOfBase style of naming the failure branch explicitly.
    4. What would a senior reviewer challenge?
      • "Why not fix the freshness check's default too?" Out of scope. It keeps false-on-failure, which is now visible as === "dirty".
      • "Preserved (worktree status unreadable)" for a path that no longer exists still says "preserved". True. The default is preserve (a Non-Goal to change), but the reason is no longer a lie. See Open Question 3.
      • "Is the unknown check redundant with ahead-of-base?" No. Without it, the reason reads "commits ahead of base", which is a different lie.
    5. Every producer and consumer.
      • Producers of the predicate git status --porcelain: worktree-manager.ts:368, :467 and run-orchestrator.ts:102 collapse to 1; the test hand copy at chain-resume.integration.test.ts:105 becomes a consumer.
      • Consumers: worktreePreserveReason → shouldPreserveWorktree / cleanupWorktreeOnShutdown (log line); checkWorktreeFreshness → ensureWorktree:1113, run-compat.ts; the orchestrator resolver → chain-resume.ts:190.
      • formatSignalLine producers: locks.ts:19 and run-orchestrator.ts:49 collapse to 1. Consumers: locks.ts:462, run-orchestrator.ts:1071, and the text assertion in locks-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:

    • Risk: the AC-3 mutation passes silently. If the /nonexistent test only asserts not.toBeNull(), deleting the unknown branch still passes ("commits ahead of base"). Assert not.toBe("uncommitted changes") and toBe("worktree status unreadable"), or the mutation doesn't prove anything.
    • Lint/knip: removing isWorktreeDirty and both local formatSignalLines may orphan the SignalOtherResult type imports. Export WorktreeStatus only if something imports it, or keep it unexported (knip).
    • Health baseline: expect it to go down (two duplicate groups removed). Regenerate only if a metric dropped.
    • Suite: run the targeted vitest files for the ACs. The full suite runs at most once, in the foreground, under timeout, after a WIP commit (runner context).
    • Mutation markers: failedTest must start with the file path (src/lib/workflow/worktree-manager.test.ts > worktreeStatus > a non-existent path is unknown).

    Derived ACs

    Source Derived AC Priority
    Behaviour preservation run.test.ts > checkWorktreeFreshness (#305 AC-3) and worktree-manager.test.ts > #1222 AC-2 stay green, unchanged High
    Error handling worktreeStatus maps a spawn error (e.g. ENOENT) to unknown, not a throw Medium

    Open Questions

    1. AC-3's filter already matches an unrelated test. Recommendation: the owner edits the AC-3 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 plus isAutomatedPRBody as "≥ 2".
    2. Which stale-pid-untrusted text wins? Recommendation: the longer locks.ts text ("…recycled onto an unrelated process"); it gives more information, and no test pins either version. Impact: the orchestrator's log line gets longer.
    3. Reason wording for 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: refactor label, 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-consolidation
    Recommended: add planned
    Quality Loop: auto-enabled by the refactor label.

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

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

    AC coverage: 5/5 met

    Gaps:

    • SignalOtherResult re-export lost its last importer through the index — dropped: advisory-only knip finding; the same index already re-exports many unused types

    Needs human review:

    • Required CI test check still pending at QA time
  7. admarble commented on Oct 19, 2026

    @admarble
    ContributorAuthor

    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:

    • AC-1: 1
    • AC-2: 8 passed
    • AC-3: 6 passed
    • AC-4: 4 passed
    • AC-5: none
    • Lint green; lint:health shows no rise (unusedExports can fall 341 → 339).

    AC-2 mutation repeated: mapping a non-zero git status exit to clean fails a non-existent path is unknown plus 3 sibling cases. Restored.

    QA's dropped finding (the SignalOtherResult re-export now has no importer) is advisory. knip counts it, and the count fell overall.

  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-consolidationplannedrefactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions