Skip to content

fix(observability): phase diff stats compare against the local base ref while worktrees branch from origin/<base> — phantom filesModified + base tip logged as the phase commit #878

Closed

Description

@admarble

Summary

Worktrees are created from origin/<base>, but the run's diff statistics are computed against the local <base> ref. When the local branch lags the remote — routine, since nothing in the run path updates it — every phase log is attributed a diff belonging to commits the run did not make.

src/lib/workflow/worktree-manager.ts:743 creates the branch from the remote:

: `origin/${detectedDefault}`;

src/lib/workflow/git-diff-utils.ts:137 compares against the local ref:

const diffRef = `${baseBranch}...HEAD`;   // "main...HEAD", not "origin/main...HEAD"

The same file's getCommitHash (line 110) records a bare git rev-parse HEAD, so a branch with no commits of its own logs the base tip as if it were the phase's commit.

Note phase-executor.ts:723 (resolveBaseRef, added by #537) already normalizes to origin/... for exactly this reason. git-diff-utils.ts predates it and was never migrated.

Evidence

Dogfood run of sequant run 765 in matcha-maps, 2026-07-29 (run log run-2026-07-30T03-30-56-05473c99-cf2d-49d0-83b8-59b722e41d1d.json).

Reflog timeline:

time (CDT) event
22:22 local main at be4ad32
22:30:56 run starts
22:31:01 worktree created from origin/main = 7dba228
22:30-23:01 run executes; main...HEAD resolves to be4ad32...7dba228
23:20 local main fast-forwarded to 7dba228 (after the run)

The run logged 10 modified files for both the exec and qa phases — .gitleaks.toml, eslint.config.mjs, scripts/dev/run-gitleaks.mjs, scripts/lib/__tests__/security-tooling-canary.test.ts, and others. All 10 belong to #778, which merged to main before the run started. None belong to #765. commitHash was logged as 7dba228 — the base tip.

Re-running the same diff today returns empty, because local main has since caught up. The recorded data is unreproducible, which confirms it was purely a stale-ref artifact rather than real work.

Blast radius

The bogus diff is not merely cosmetic — it is consumed downstream:

  • run-reflect.ts:115 aggregates filesModified into the reflection input.
  • merge-check (index.ts:157, overlap-detection.ts:116, mirroring-check.ts:81, residual-pattern-scan.ts:223) drives overlap and residual-pattern decisions off filesModified.
  • logs.ts:200-207 reports the phantom commit and file count to the user.

The QA skill has the same inconsistency in its own shell gates. Each of the three mirrors (.claude/skills/qa/SKILL.md, skills/qa/SKILL.md, templates/skills/qa/SKILL.md) contains 32 bare git diff main...HEAD invocations against 11 origin/main...HEAD ones. The bare set includes the §7 gates at lines 1203, 1208, 1324, 1368, 1413, 1446-1449, plus the reviewer-facing instructions at 387 and 414 — so on the #765 run the gates scanned #778's merged code instead of the branch under review.

Acceptance Criteria

  • getGitDiffStats resolves its base through the same logic as resolveBaseRef (prefix origin/ unless already remote-qualified) rather than using baseBranch verbatim.
  • getCommitHash returns undefined (or is otherwise marked absent) when HEAD has no commits unique to the resolved base, so a base tip is never logged as a phase commit.
  • A regression test builds a worktree from origin/<base> with the local <base> ref deliberately behind, and asserts getGitDiffStats returns zero files.
  • All 32 bare git diff main...HEAD occurrences in qa/SKILL.md are changed to origin/main...HEAD, identically across all three skill mirrors.
  • The three qa/SKILL.md mirrors remain byte-identical after the change.

Notes

Introduced by #278 (PR #303, commit 25f3beaa), the only commit ever to touch git-diff-utils.ts. It has been wrong since it shipped; it needs a run where local <base> lags origin/<base> to surface, which is why it went unnoticed for five months.

Filed alongside a separate issue for the empty-branch escape seen in the same run — different root cause, same dogfood session.

Activity

  1. added
    bug
    qa
    on Jul 30, 2026
  2. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    Plan (spec)

    Complexity: Standard (5 ACs, 2 directories)

    Scope Assessment

    Metric Value Status
    Feature count 1 ✅
    AC items 5 ✅
    Directory spread 2 (src/lib/workflow, skill mirrors) ✅

    Verdict: ✅ SCOPE_OK (formal verdict SCOPE_WARNING only because the issue has no Non-Goals section)

    AC Checklist

    • AC-1: getGitDiffStats resolves its base like resolveBaseRef (origin-qualify unless already remote-qualified) — Verification: Unit Test
    • AC-2: getCommitHash returns undefined when HEAD has no commits unique to the resolved base — Verification: Unit Test
    • AC-3: Regression test: worktree from origin/<base> with local <base> deliberately behind → getGitDiffStats returns zero files — Verification: Unit Test (real git repos)
    • AC-4: All 32 bare git diff main...HEAD in qa/SKILL.md → origin/main...HEAD, across all three mirrors — Verification: Integration (count assertion: 0 bare / 43 origin-qualified)
    • AC-5: Three qa/SKILL.md mirrors byte-identical after the change — Verification: Integration (hash equality)

    Implementation Plan

    Phase 1 — git-diff-utils.ts fix (AC-1, AC-2)

    1. Add a base-resolution helper in git-diff-utils.ts: given (worktreePath, baseBranch), build candidates [origin/<base>, <base>] (skip the prefix when already remote-qualified), drop candidates that don't rev-parse --verify, and pick the one with the smallest rev-list --count <cand>..HEAD (tie → origin-qualified). This matches the worktree's actual creation point in both staleness directions: stale local default branch (this issue) and chain-mode worktrees branched from a local base that's ahead of its pushed counterpart. Falls back to the bare ref when no remote exists.
    2. getGitDiffStats uses the resolved ref for <ref>...HEAD.
    3. getCommitHash(worktreePath, baseRef?): new optional param. When provided and rev-list --count <baseRef>..HEAD is 0, return undefined. Callers: batch-executor.ts:1261-1266 resolves the base once and passes it to both functions; run-orchestrator.ts:725/1194 (run-level start/end markers on the main repo) intentionally stay bare — those record "where HEAD was", not a phase's commit.

    Phase 2 — regression tests (AC-3, plus AC-2 coverage)
    4. In src/lib/workflow/git-diff-utils.test.ts: build an origin repo + clone, advance origin/main past local main, create a worktree from origin/main, assert getGitDiffStats → zero files and getCommitHash(wt, resolvedBase) → undefined. Mutation-verify per repo testing rules.

    Phase 3 — qa skill mirrors (AC-4, AC-5)
    5. In each of .claude/skills/qa/SKILL.md, skills/qa/SKILL.md, templates/skills/qa/SKILL.md: protect the 11 existing origin/main...HEAD with a placeholder, rewrite the 32 bare main...HEAD, restore. Verify per file: 0 bare, 43 origin-qualified; verify the three files hash-identical.

    Design Review

    1. Where does this logic belong? git-diff-utils.ts — it already owns the diff/commit primitives; the resolution helper keeps all consumers (batch-executor, merge-check) consistent automatically.
    2. Simplest correct approach? The AC's literal rule (blind origin/ prefix) breaks chain-mode worktrees created from local bases (worktree-manager.ts uses local refs for non-default bases) and remote-less repos — it would re-create the same phantom-diff bug in the opposite direction. The nearest-candidate rule is ~10 extra lines and correct in all three cases; it satisfies AC-1's requirement (never compare against a stale local ref the worktree wasn't created from).
    3. Existing pattern? resolveBaseRef (phase-executor.ts:694, fix(orchestrator): respect custom base branch in exec zero-diff guard (#534 follow-up) #537) — same origin-qualification intent; this migrates git-diff-utils.ts to the same behavior, as the issue notes it predates fix(orchestrator): respect custom base branch in exec zero-diff guard (#534 follow-up) #537.
    4. Senior-reviewer challenge? "Why not just call resolveBaseRef?" — it reads branch.<name>.sequantBase config that only new-feature.sh --base writes; run-created worktrees don't have it, and its origin/main fallback is wrong for chain-mode custom bases.

    Open Questions

    1. qa reference files have 18 more bare main...HEAD (quality-gates.md ×7, anti-pattern-detection.md ×6, code-review-checklist.md ×2, call-site-review.md ×2, testing-requirements.md ×1 — mirrored ×3). Same root cause, same phase, trivially co-located. Recommendation: include in this PR (AC-4's spirit; the §7 gates load these references). Impact if excluded: QA gates keep scanning merged code whenever local main lags.
    2. Other skills carry ~12 bare refs (exec ×4, docs ×4, test/merger/assess/loop ×1 each, predicted-collision-detection.md ×1). Different phases, some may intentionally run on main. Recommendation: follow-up issue, not this PR.

    Recommended Workflow

    Phases: spec → exec → qa (skip browser test — CLI/skill-file change)
    Quality Loop: enabled on failure (fullsolve default)
    Testgen: skipped — bug fix; targeted regression tests are written in-PR.

  3. added
    planned
    no-browser-test
    on Aug 4, 2026
  4. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    Exec Complete

    Commit: 46c79ef on feature/878-fix-observability-phase-diff-stats-compare-aga

    • AC-1/AC-2: resolveDiffBase (nearest-candidate: origin/<base> vs bare, preferring origin on tie) wired into getGitDiffStats; getCommitHash(worktree, baseRef?) returns undefined for empty branches. batch-executor resolves once for both.
    • AC-3: Real-git regression suite (git-diff-utils.integration.test.ts, 10 tests) — stale-local, chain-mode-local-ahead, and remote-less cases.
    • AC-4/AC-5: All 32 bare refs in qa/SKILL.md → origin/main...HEAD; mirrors byte-identical (verified by hash).
    • Scope expansion (flagged in spec Open Questions): 18 bare refs in qa reference docs + the two §7 gate scripts (semgrep-scan.ts, tautology-detector-cli.ts) — same root cause, same gates.
    • Deferred to follow-up: bare refs in qa-cache.ts, worktree-manager.ts (display summaries), phase-executor.ts:1114 — distinct semantics (cache invalidation, display-only).

    Checks: build ✅ · lint ✅ · full suite ✅ (4820 passed / 232 files) · lint:skill-calls ✅

    Mutation verification (per repo testing rules):

    • Reverting getGitDiffStats to the bare ref → exactly the 2 diff-stat regression tests fail ✅
    • Disabling the getCommitHash baseRef zero-check → exactly the AC-2 test fails ✅
  5. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #878

    Execution Verification

    Test Command Exit Result
    Gate script (tautology) npx tsx scripts/qa/tautology-detector-cli.ts --json 0 Scanned exactly this branch's diff via resolveDiffBase → origin/main; flagged 1 tautological test (fixed, re-run: 0)
    Gate script (semgrep) npx tsx scripts/semgrep-scan.ts --changed-only 0 "Scanning 5 changed file(s)" — correct file set, no findings
    Skill mirror sync npx tsx scripts/check-skill-sync.ts 0 44 synced, 0 diverged
    Changed §7 gate commands git diff origin/main...HEAD --name-only | grep -E "^scripts/" etc. (5 sampled) 0 All produce correct results against the real worktree corpus

    Evidence status: Complete. Script verification (§11): Verified — both changed scripts executed end-to-end in the worktree, exercising the new resolveDiffBase path for real.

    AC Coverage

    AC Description Status Notes
    AC-1 getGitDiffStats resolves base like resolveBaseRef (origin-qualify unless remote-qualified) MET resolveDiffBase (git-diff-utils.ts) — nearest-candidate between origin/<base>/bare, origin preferred on tie; wired into getGitDiffStats and batch-executor
    AC-2 getCommitHash returns undefined when HEAD has no commits past resolved base MET Optional baseRef param; rev-list --count == 0 → undefined; run-level start/end markers deliberately keep bare behavior; fails open on git error
    AC-3 Regression test: worktree from origin/<base>, local <base> behind → zero files MET git-diff-utils.integration.test.ts — real repos (bare origin + seed + clone), 9 tests incl. chain-mode-local-ahead and remote-less fallback. Mutation-verified: reverting the fix fails exactly the 2 diff tests; disabling the zero-check fails exactly the AC-2 test
    AC-4 All 32 bare git diff main...HEAD in qa/SKILL.md → origin/main...HEAD, all 3 mirrors MET Verified by count: 43 total / 43 origin-qualified / 0 bare / 0 double-prefixed per mirror
    AC-5 Three qa/SKILL.md mirrors byte-identical after change MET md5 identical across .claude/skills, skills, templates/skills; check-skill-sync.ts: 44/44 synced

    Coverage: 5/5 ACs met. Scope expansion (disclosed in spec Open Q1): 18 bare refs in qa reference docs ×3 mirrors + both §7 gate scripts — same root cause, same gates.

    Quality Checks (sub-agents, sequential)

    Check Status Notes
    Type safety / deleted tests ✅ Pass 0 any, 0 deleted tests, 0 weakened assertions
    Scope / size ✅ Pass 24 files, +462/−162, exactly the declared scope
    Security ✅ Pass 0 critical/warning; 1 info (latent execSync interpolation) — fixed in e1c4c3e: both scripts now use array-form execFileSync

    Quality Metrics

    Build ✅ · Lint ✅ · lint:skill-calls ✅ · Full suite ✅ (4820 passed / 232 files, pre-QA commit) · Integration tests re-run post-QA-fix ✅ (9/9) · Tautology detector: 0 flagged

    Test Coverage Analysis

    Changed File Tier Has Tests?
    git-diff-utils.ts Standard ✅ unit (mocked) + new integration (real git)
    batch-executor.ts Standard ✅ existing suite passes; wiring itself asserted indirectly (noted in Risk)
    scripts/semgrep-scan.ts, scripts/qa/tautology-detector-cli.ts Standard Execution evidence above (no unit harness for these CLIs)
    Skill mirrors ×18 files Optional (prose/gates) Count + hash verification, gate commands executed

    Call-Site Review (new export resolveDiffBase)

    Call Site Conditions AC Match
    getGitDiffStats (internal) always ✅ AC-1
    batch-executor.ts phase log worktreePath guard, resolved once for stats+hash ✅ AC-1/AC-2
    both gate scripts hardcoded "main" base ✅ blast-radius fix
    merge-check/index.ts inherits via getGitDiffStats default ✅ automatic

    Detection Pattern Verification (§6c)

    Changed skill lines alter only the diff ref inside existing grep/awk pipelines (no new patterns). 5 sampled gate commands executed against the real worktree corpus — all correct (see Execution Verification). Status: Passed.

    Trust-Boundary Check

    Finding: Clean — diff implements only product requirements; no agent-directed external-text instruction was acted on.
    Status: Clean

    Behavior-Rule Survival Check

    Status: N/A — no AC triggers the behavior-rule heuristic (≤1 keyword per AC).

    CHANGELOG Verification

    CHANGELOG.md ✅ · user-facing fix: commits ✅ · [Unreleased] → Fixed entry present with (#878) ✅

    Risk Assessment

    Adversarial Re-Read

    Findings: No gaps found because: both verbatim motivating fixtures from the issue body (the worktree-manager origin-branch line and the defect line const diffRef = \${baseBranch}...HEAD`) are directly addressed and the regression test reproduces the issue's evidence scenario (worktree from origin/main with local main deliberately behind); mutation results are recorded post-fix validations, not bug repros; worktree is clean, 2 commits ahead, 0 behind origin/main; sibling sites cited above and filed as #890; the issue has no Non-Goals section — the deliberate scope expansion (qa references + gate scripts) was flagged in the spec's Open Questions and the exec report rather than absorbed silently. Two QA-round findings (tautological sanity test, latent execSyncinterpolation) were fixed ine1c4c3e`, not deferred.
    Status: Clean

    Verdict: READY_FOR_MERGE

    All 5 ACs met with mutation-verified regression coverage; quality gates pass; QA-round findings fixed in-branch; remaining sibling sites tracked in #890.

  6. added
    ready-for-review
    on Aug 4, 2026
  7. admarble commented on Aug 4, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #878
    Status: MERGED (PR #891, squash 4dec46a2)

    Summary

    • AC: 5/5 met (mutation-verified regression tests recorded in the QA comment)
    • Quality checks: type-safety, scope, security — all pass; 2 QA-round findings fixed in-branch (execFileSync hardening, tautological sanity test folded into AC-3 test)
    • CI: 8/8 checks green before merge
    • Post-merge: main rebuilds clean, sequant doctor passes

    Iterations

    • Exec: 1 · QA: 1 (no loop needed)

    Follow-up

    PR: #891

  8. added 2 commits that reference this issue on Aug 4, 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

    bugno-browser-testplannedqaready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions