fix(#4454): surface skipped explicit --files paths instead of silent success (#4538)

* fix(#4454): surface skipped explicit --files paths instead of silent success

cmdCommit's staging loop deliberately skips a --files path that no longer
exists on disk when the caller passed --files explicitly (#2014 guards
against staging an unwanted deletion for a temporarily-absent file), but
recorded nothing about the skip. The final result reported unqualified
committed: true, so a caller had no way to distinguish "everything in
--files landed" from "some paths were silently excluded because they
didn't exist" -- a real file deletion meant to be committed (e.g.
phase.complete removing .planning/milestone.lock) would silently never
land, with git status still showing it unstaged after a "successful"
commit.

Tracks skipped paths in a skippedFiles array and surfaces them as
skipped_files (matching this result family's existing snake_case
precedent, timed_out) in the success result AND the nothing_to_commit
result (reachable when every named path was missing), included only
when non-empty so the common case's payload shape is unchanged. Also
extended to the SECOND nothing_to_commit result (reached when git
itself reports "nothing to commit" after the nothingToCommit guard was
false -- the residual partial-skip + partialCommitRefused window the
surrounding comments already document) for the same consistency. The
#2014 staging/deletion guard itself is untouched -- purely a visibility
fix, exactly as the issue requested.

Regression tests cover: existing-plus-missing file (the issue's own
repro shape, with the missing path genuinely tracked-then-deleted so
the #2014 assertion is meaningful, not vacuous against an
never-tracked path); only-existing files (no skipped_files key at
all); only-missing files (nothing_to_commit with skipped_files);
default mode unaffected; and multiple missing files reported in order.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: recover ack trailers buried by squash-merge concatenation

Discovered while verifying an unrelated PR (#4454): tests/emitted-attribution.test.cjs
failed citing pr-branch.md's growth as unacknowledged, even though PR #4537
(#4447) had genuinely acked it via an Emitted-Drift-Ack-Growth commit trailer.

Root cause: git's %(trailers:...) placeholder (used by readAckTrailers) only
recognizes a trailer block that is the TRUE TERMINAL block of a commit
message. GitHub's squash-merge commit body concatenates every constituent
commit's subject+body in order, then unconditionally appends its own
`---------` separator and Co-authored-by trailers. Confirmed directly
against a real squash commit: %(trailers) returns ONLY GitHub's own two
Co-authored-by lines -- not even the LAST original commit's own trailer
survives, since GitHub's appended suffix breaks the backward scan before
it ever reaches past `---------` to any original commit's content, last
or not. An ack trailer added on any non-final commit of a PR (the common
case -- more commits routinely land after an ack, e.g. a lint fix or a
changeset) is therefore silently invisible forever to any future
comparison against a base predating that squash.

Fix: readAckTrailers now runs a second pass (extractSquashBuriedTrailers)
alongside the existing whole-message read. For each commit in range, if
its raw body contains GitHub's squash-suffix signal, the pre-suffix text
(everything before the LAST such signal -- an earlier bullet's own body
may legitimately contain a markdown horizontal rule that looks the same,
so anchoring on the first occurrence would truncate too early and miss a
later bullet's real ack) is split on squash-bullet (`* <subject>`)
boundaries, and each chunk is independently trailer-parsed via
`git interpret-trailers --parse` -- the same underlying algorithm as
%(trailers:...), but runnable against arbitrary text rather than only a
real commit object. This finds a trailer buried in ANY bullet, not just
the last one.

Scoped tightly to avoid reintroducing the false-positive class
%(trailers:...) was originally chosen to prevent (a mid-body MENTION of
trailer syntax must stay inert): the sub-chunk pass activates only on
commits matching the squash-suffix signal, so an ordinary commit whose
body happens to contain markdown bullets is completely unaffected, and
each chunk still goes through git's own strict per-chunk terminal-block
detection.

Verified end-to-end against a real squash commit (recovers the buried
trailer) and four adversarial fixtures now pinned as regression tests:
ordinary bullet prose with no squash suffix (stays empty); a
squash-shaped commit where one bullet's body merely mentions trailer
syntax mid-paragraph (stays inert, the "row 32" false-positive class,
now verified at per-chunk granularity); and an earlier bullet's own
markdown horizontal rule not truncating the scan before a later bullet's
real ack (the last-match-not-first-match case an isolated review pass
caught during this same fix).

This overrides one-concern-per-PR per CLAUDE.md's Defects & Warnings
policy -- a genuine defect discovered mid-work is fixed inline, not
deferred to a separate issue (spawn_task for this was correctly blocked
by the no-defer guard).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(#4454): backfill changeset PR number

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-09-08 02:01:12 -04:00
committed by GitHub
parent 78013b3b74
commit b8c70a33c0
5 changed files with 438 additions and 5 deletions

View File

@@ -47,6 +47,7 @@ const {
} = require('./install-shared.cjs');
const { ACK_TRAILER_HASH, ACK_TRAILER_GROWTH, parseAckTrailers } = require('./emitted-diff.cjs');
const { runGit, OUTCOME } = require('./process-seam.cjs');
const { escapeRegex } = require('../../gsd-core/bin/lib/pattern.cjs');
const REPO_ROOT = path.join(__dirname, '..', '..');
const FIXTURE_SUBDIR = 'tests/fixtures/golden-install-parity';
@@ -723,8 +724,10 @@ function currentSizes({ repoRoot = REPO_ROOT } = {}) {
* clean exit — same "a git failure is a hard error, never an empty result" law as
* `resolveChangedPaths` above.
*/
function ackTrailerGit(args, { cwd = REPO_ROOT, timeoutMs = GIT_TIMEOUT_MS } = {}) {
const result = runGit([...safeDirArgs(cwd), ...args], { cwd, timeoutMs });
function ackTrailerGit(args, { cwd = REPO_ROOT, timeoutMs = GIT_TIMEOUT_MS, input } = {}) {
const spawnOpts = { cwd, timeoutMs };
if (input !== undefined) spawnOpts.input = input;
const result = runGit([...safeDirArgs(cwd), ...args], spawnOpts);
if (result.outcome === OUTCOME.EXITED && result.exitCode === 0) {
return result.stdout;
}
@@ -734,6 +737,111 @@ function ackTrailerGit(args, { cwd = REPO_ROOT, timeoutMs = GIT_TIMEOUT_MS } = {
);
}
// #4454 follow-on — SQUASH-MERGE BURIAL. `%(trailers:...)` (used by readAckTrailers
// below) only recognises a trailer block that is the TRUE TERMINAL block of a commit
// message: consecutive `Token: value` lines running to the very end, nothing after.
// GitHub's squash-merge commit body is every constituent commit's subject+body
// concatenated in order, followed by its OWN appended `---------` separator and
// `Co-authored-by:` trailers. Two independent commits landing after the one carrying
// an ack trailer — including GitHub's own appended suffix, which follows EVERY squash
// commit unconditionally — silently bury it: git's parser (correctly, by its own
// contract) stops at the first non-conforming line scanning backward, so it never even
// reaches past `---------` to see the real content underneath, let alone further back
// to an earlier bullet. Confirmed directly against a real squash commit (gsd-core
// 78013b3b74): `%(trailers)` there returns ONLY GitHub's own two `Co-authored-by:`
// lines — not even the last original commit's own trailer survives, only GitHub's
// appended one.
//
// FIX: independently trailer-parse each squash-BULLET sub-chunk of the raw message,
// using `git interpret-trailers --parse` (the same underlying algorithm as
// `%(trailers:...)`, but runnable against arbitrary TEXT via stdin rather than only a
// real commit object) — so each original commit's own terminal trailer block is found
// on its own terms, independent of what got concatenated after it.
//
// SCOPED TIGHTLY to avoid reintroducing the false-positive class `%(trailers:...)` was
// chosen to prevent (row 32 — prose that merely MENTIONS trailer syntax must stay
// inert): this sub-chunk pass activates ONLY when the raw body contains GitHub's own
// distinctive squash suffix marker (a blank line, 9+ hyphens alone on a line, another
// blank line) — an ordinary, non-squash commit whose body happens to contain markdown
// bullets never matches this and is completely unaffected. Within an activated commit,
// each bullet chunk still goes through git's own STRICT per-chunk terminal-block
// algorithm (via `interpret-trailers`), so a mid-chunk MENTION of trailer syntax
// (not at that chunk's own true end) is exactly as inert as it always was — the
// protection is now granular per original commit instead of per whole squashed message,
// never removed.
// Review finding (2026-09-08): a bare `.match()` against this pattern returns the
// FIRST occurrence scanning left-to-right, but GitHub's own appended suffix is always
// the TRUE TAIL of the message — an earlier bullet's own body legitimately using a
// markdown horizontal rule (also `---------`-shaped) before the bullet that actually
// carries the ack would truncate `beforeSuffix` too early, silently excluding the real
// ack bullet from the split/parse scan below and reintroducing the exact bug this
// function exists to fix. `findLastGithubSquashSuffixIndex` below finds the LAST match
// instead, via a global-flag scan (an anchor-and-backtrack trick with a leading
// `[\s\S]*` was tried and rejected: it forces the match's OWN `.index` to 0, which
// breaks the `rawBody.slice(0, match.index)` usage pattern this function needs).
const GITHUB_SQUASH_SUFFIX_RE = /\n\n-{9,}\n\n/g;
const SQUASH_BULLET_SPLIT_RE = /\n\n(?=\* )/;
/** Index of the START of the LAST GitHub-squash-suffix occurrence in `text`, or -1. */
function findLastGithubSquashSuffixIndex(text) {
GITHUB_SQUASH_SUFFIX_RE.lastIndex = 0;
let last = -1;
let m;
while ((m = GITHUB_SQUASH_SUFFIX_RE.exec(text)) !== null) {
last = m.index;
// A zero-length match cannot happen for this pattern (it requires literal
// characters), but guard against an infinite loop defensively regardless.
if (m[0].length === 0) GITHUB_SQUASH_SUFFIX_RE.lastIndex += 1;
}
return last;
}
const ACK_TRAILER_LINE_RE = new RegExp(
`^(${escapeRegex(ACK_TRAILER_HASH)}|${escapeRegex(ACK_TRAILER_GROWTH)}):\\s*(.*)$`,
);
/**
* Recover ack trailers buried mid-message by squash-merge concatenation. Returns
* `{ hash: string[], growth: string[] }` of any ADDITIONAL values found beyond what the
* whole-message `%(trailers:...)` pass in `readAckTrailers` already sees — callers
* merge both into the same value lists before the final `parseAckTrailers` call, so
* this never needs its own dedup or its own result-shape handling.
*
* A commit whose body does not contain GitHub's squash suffix signal is not a squash
* commit by this heuristic and is returned untouched (empty arrays) — this is the sole
* gate against widening false-positive risk to ordinary commits.
*/
function extractSquashBuriedTrailers(rawBody, { cwd, timeoutMs }) {
const suffixIndex = findLastGithubSquashSuffixIndex(rawBody);
if (suffixIndex === -1) return { hash: [], growth: [] };
const beforeSuffix = rawBody.slice(0, suffixIndex);
const chunks = beforeSuffix.split(SQUASH_BULLET_SPLIT_RE);
const hash = [];
const growth = [];
for (const chunk of chunks) {
// A chunk with no blank-line-separated body (a bare `* subject` bullet, or the
// pre-first-bullet PR-title preamble) cannot carry a trailer block at all —
// skipping it is an optimisation, not a correctness requirement (interpret-trailers
// would just return nothing for it).
if (!chunk.trim()) continue;
let parsed;
try {
parsed = ackTrailerGit(['interpret-trailers', '--parse'], { cwd, timeoutMs, input: chunk });
} catch {
// A single malformed/unparseable chunk must not abort the whole scan — the
// existing whole-message pass and every OTHER chunk still stand. Fail this
// chunk closed (recover nothing from it), never the whole function.
continue;
}
for (const line of parsed.split('\n')) {
const m = ACK_TRAILER_LINE_RE.exec(line);
if (!m) continue;
if (m[1] === ACK_TRAILER_HASH) hash.push(m[2]);
else growth.push(m[2]);
}
}
return { hash, growth };
}
// Record/field/value separators for the `git log --format` trailer extraction below.
// ASCII control characters (RS/US/GS) so they can never collide with real trailer
// content, following the precedent at gsd-core/workflows/ship.md:312 (`%x1f`/`%x1e` for
@@ -820,6 +928,30 @@ function readAckTrailers({ baseRef, headRef = 'HEAD', cwd = REPO_ROOT, timeoutMs
for (const v of growthField.split(ACK_TRAILER_VALUE_SEP)) if (v !== '') growthValues.push(v);
}
// #4454 follow-on: recover any ack trailer the whole-message pass above cannot see
// because a squash-merge concatenated other commits' bodies after it (see
// extractSquashBuriedTrailers's doc comment for the full mechanism and the
// false-positive scoping that keeps this from widening risk on ordinary commits).
// A SEPARATE `%B` read (rather than reusing the format above) because the raw body
// is needed verbatim, including the exact blank-line/hyphen/bullet structure the
// squash-suffix and bullet-boundary regexes key on — `%(trailers:...)` already
// discards everything but the trailers themselves and cannot supply this.
let rawBodies;
try {
rawBodies = ackTrailerGit(
['log', `${mergeBase}..${headRef}`, `--format=${ACK_TRAILER_RECORD_SEP}%B`],
{ cwd, timeoutMs },
);
} catch (err) {
throw new Error(`emitted-ack-trailer: could not read commit bodies over the range: ${err.message}`);
}
const bodyRecords = rawBodies.replace(/\r/g, '').split(ACK_TRAILER_RECORD_SEP).slice(1);
for (const body of bodyRecords) {
const recovered = extractSquashBuriedTrailers(body, { cwd, timeoutMs });
hashValues.push(...recovered.hash);
growthValues.push(...recovered.growth);
}
return parseAckTrailers({ hash: hashValues, growth: growthValues });
}