* test(#3942): failing-first suite for the emitted-drift ack commit trailer Binds 37 input classes from the phase test matrix to the behavior ADR-3942 specifies, before any of it exists. Stubs return benign empty values rather than throwing, deliberately: several rows assert that something DOES throw (cap overflow, uncomputable commit range), and a throwing stub would turn those green for the wrong reason and destroy the red. The two rows that carry the design's load: - merge-base semantics. The range is $(git merge-base base HEAD)..HEAD, not base..HEAD, because changedPaths comes from `git diff base...HEAD` (three dot). Two-dot would let the ack set and the change set disagree about which commits are this PR's. The fixture forks a topic branch, puts a trailer on each side, and asserts only the topic-side trailer is in range. - fail-closed on an uncomputable range. With fragments a depth-1 checkout passes VACUOUSLY, every fragment reading as brand-new. With trailers the range cannot be computed at all, and returning an empty set would silently disarm the gate, so it must throw. The fixture builds a genuine shallow clone rather than simulating one. Also covers the self-inflicted case: this change's own documentation quotes the trailer syntax, so an example landing at the end of a commit message would arm a live acknowledgment keyed on the literal placeholder text. Keys carrying angle brackets or whitespace are rejected. Authored per the phase artifacts 40-design.md and 50-test-matrix.md. Not yet run on the remote runner — this commit exists to be tested. Refs #3942 * chore(#3942): move the emitted-drift ack to a commit trailer Implements ADR-3942, superseding ADR-2719 section 3 and its #2789 amendment. Sections 1, 2 and 4-7 are retained: the conservation law is unchanged, only the storage of its escape hatch moved off the working tree. An acknowledgment explains one PR's ripple, and the moment that PR merges the ripple is in the base, so it can never clear anything again. It was stored in permanent shared state anyway, and every consequence of that mismatch had to be built and then maintained. The chain is #2789 -> #2914 -> #3078 -> #3842 -> #3823 -> #3875, each fix generating the next defect, ending in a scheduled sweeper whose own first PR could not merge itself. Added parseAckTrailers + renderAckTrailer (pure) and readAckTrailers (IO shell), reading Emitted-Drift-Ack-Hash: / Emitted-Drift-Ack-Growth: trailers over the merge-base range. tests/emitted-ack-trailer.test.cjs, 37 cases, written failing-first and confirmed red before any of this existed. Changed diffEmitted takes two structurally distinct key-space maps instead of one shared paths map. That closes a latent defect: the spaces were separated by convention only, so a growth key satisfied a hash lookup by naming coincidence. staleAcks now reports which space a key was declared in. REMEDIATION teaches the trailer, per space, with its example rendered through renderAckTrailer so the taught grammar cannot drift from what the parser accepts. Removed the sweep workflow, the guard-no-ack-on-next job, the standalone linter and its lint:ci entry, the fragment directory and its three spent fragments, the legacy single-file union, and the baseAck/spentAcks mechanism -- spentness is now structural, not computed. Two range properties carry the design and are pinned by tests rather than asserted: the range is merge-base scoped, matching git diff base...HEAD, so an already-merged trailer is out of range by construction; and an uncomputable range throws instead of reading as zero acknowledgments, which is the inverse of the fragment guard's vacuous pass. Three deliberate observable changes, each disclosed in the changeset: the unread runtime field is gone, the legacy file is no longer read, and cross-space excusal no longer works. Ten open PRs carry fragments and will meet a modify/delete conflict. Measured before landing and accepted deliberately; the one-line migration is in the PR body. Verified: lint:ci exit 0. Remote runner to follow on this exact sha. Refs #3942 * fix(#3942): silent trailer collapse, lost coverage, and an unbounded cap Six findings from the orthogonal review round, all fixed in place. BLOCKER -- two trailers of the same name on one commit collapsed silently. readAckTrailers built `separator=1d` where git needs `separator=%x1d`: the `separator=` value inside a %(trailers:...) placeholder is itself a pretty-format string, so the bare hex was emitted as two literal characters and the split on \x1d never matched. Two same-name trailers therefore joined into one value with errors empty -- the first reason absorbing the second entry's key. Silent truncation, the exact class MAX_ACK_TRAILERS throws to prevent. Confirmed with od -c against real git output before and after. The failing-first matrix did not catch it because its "both spaces coexist" row uses Hash plus Growth -- different trailer NAMES -- so the value separator was never exercised. Two regression tests now cover same-name trailers directly. Coverage recovered: normalizeAckReason and INVISIBLE stayed on the live path via parseAckTrailers but lost every test when the old suite was pruned. Back under test against the current surface -- all six invisible codepoints individually, whitespace collapse, trim, CRLF, and two seeded fast-check properties. Dropping any single codepoint now fails. MAX_ACK_TRAILERS counted raw trailers before de-duplication, so one trailer carried forward across rebased commits counted once per commit and could throw on a legitimate branch. Now counts distinct entries; 100 identical repeats dedupe to one. diffEmitted validated baseline, current and changedPaths but not the new ackHash/ackGrowth, so a bad shape raised an unhandled TypeError instead of an error verdict -- the same defect shape this file documents for #2778. Docs: CONTRIBUTING and TESTING-SUITES were rewritten only in their first sections; the later passages still taught fragments, git rm and the deleted guard, contradicting the new text directly above them. Finished. Also extends lint-removed-but-needed to exempt docs/adr and docs/research. That gate fails on any docs mention of a file deleted in the same diff, which makes it impossible to document a deletion in the PR performing it -- an ADR's whole job is naming what it retired. Exemption is narrow and comes with a test proving the gate still fires for a live consumer elsewhere under docs/. A guard that cannot fail is worse than no guard. Maintainer-approved. CONTEXT.md names the retired machinery by role rather than by filename: its generated projection lands in docs/, which that gate does scan. Adds docs/how-to/acknowledge-emitted-drift.md. The required docs set is Reference and Explanation, so the task quadrant can be empty with every gate green -- and this change has a real multi-step journey, including the fragment migration ten open PRs now need. lint:ci exit 0. Refs #3942 * docs(#3942): correct the duplicate-trailer rule in CONTRIBUTING Both axes of the code review independently flagged the same passage, without seeing each other's output. It claimed two declarations of the same key are always "a hard, loudly-reported error, not a silent last-wins". That is only half true, and the missing half is the one contributors hit: identical declarations -- same key, same reason -- dedupe silently, because a trailer legitimately survives a rebase and reappears on every rebased commit. Failing there would red a branch for doing nothing wrong, which is exactly why the dedup exists. Only a same-key/different-reason pair errors, and that one is a genuine ambiguity about which explanation holds. As written, the paragraph told a contributor that a rebase-carried trailer breaks the gate -- the opposite of the behavior. CONTEXT.md's parallel entry already stated it correctly; this brings CONTRIBUTING into line. Doc-only, root-level markdown. Refs #3942 * chore(#3942): backfill changeset PR number to 3954 --------- Co-authored-by: sim <sim@local>
This commit is contained in:
@@ -45,45 +45,10 @@ const {
|
||||
extraEmitRootsFor,
|
||||
PKG_VERSION,
|
||||
} = require('./install-shared.cjs');
|
||||
const { mergeAckSources, MAX_ACK_FRAGMENTS } = require('./emitted-diff.cjs');
|
||||
|
||||
/**
|
||||
* Fail loudly when a fragment listing exceeds `MAX_ACK_FRAGMENTS`, naming the
|
||||
* directory, the cap, and the actual count. Never truncate: a silently-truncated
|
||||
* listing would silently drop acknowledgments, which is exactly the class of silent
|
||||
* failure the ack seam exists to prevent (see `MAX_ACK_FRAGMENTS`'s doc comment in
|
||||
* `emitted-diff.cjs`).
|
||||
*/
|
||||
function assertFragmentCountWithinCap(dirLabel, names) {
|
||||
if (names.length > MAX_ACK_FRAGMENTS) {
|
||||
throw new Error(
|
||||
`emitted-attribution: ${dirLabel} contains ${names.length} ack fragments, `
|
||||
+ `exceeding the cap of ${MAX_ACK_FRAGMENTS}. Refusing to read only some of them — a `
|
||||
+ 'truncated read would silently drop acknowledgments. Prune spent fragments from '
|
||||
+ 'this directory.',
|
||||
);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
const { ACK_TRAILER_HASH, ACK_TRAILER_GROWTH, parseAckTrailers } = require('./emitted-diff.cjs');
|
||||
const { runGit, OUTCOME } = require('./process-seam.cjs');
|
||||
|
||||
const REPO_ROOT = path.join(__dirname, '..', '..');
|
||||
/**
|
||||
* Repo-relative and POSIX-separated on every platform: this form is what `git show
|
||||
* <ref>:<path>` requires, and git speaks only forward slashes regardless of host OS.
|
||||
* `ACK_PATH` derives from it so the two can never name different files.
|
||||
*
|
||||
* LEGACY single-file path (#2778), still honored and unioned with `ACK_DIR_REPO_PATH`
|
||||
* below (#2914) — open PRs authored before the fragment split still carry this file.
|
||||
*/
|
||||
const ACK_REPO_PATH = 'tests/emitted-drift-ack.json';
|
||||
const ACK_PATH = path.join(REPO_ROOT, ...ACK_REPO_PATH.split('/'));
|
||||
/**
|
||||
* Per-PR fragment directory (#2914). Every fragment is independently named, so two PRs
|
||||
* that each need an ack can never collide on this path the way they always did on the
|
||||
* single legacy file above.
|
||||
*/
|
||||
const ACK_DIR_REPO_PATH = 'tests/emitted-drift-acks';
|
||||
const ACK_DIR = path.join(REPO_ROOT, ...ACK_DIR_REPO_PATH.split('/'));
|
||||
const FIXTURE_SUBDIR = 'tests/fixtures/golden-install-parity';
|
||||
|
||||
/**
|
||||
@@ -329,190 +294,6 @@ function resolveBaseSha(base = 'origin/next') {
|
||||
return git(['rev-parse', base]).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The acknowledgment document AS IT EXISTS AT `base` — the base side of the ack
|
||||
* lifecycle (#2789). An entry already present there is SPENT: its ripple is absorbed
|
||||
* into the base, so it may no longer clear a delta and is never reported stale.
|
||||
*
|
||||
* ── Why "inherit nothing" is NOT a safe default ──────────────────────────────
|
||||
* Absent at that ref is the healthy steady state and returns `null`. Every OTHER failure
|
||||
* THROWS, and the distinction is load-bearing in the direction that is easy to get
|
||||
* backwards. Returning `null` on a read error looks armed — nothing is inherited, so
|
||||
* every entry stays live — but a LIVE entry's defining power is that it CONSUMES a
|
||||
* delta. So `null` is armed on the staleness axis and DISARMED on the consumption axis,
|
||||
* which is the axis a gate over shipped artifacts actually cares about: a genuinely new,
|
||||
* unexplained ripple on a path carrying an already-merged ack would come back `acked`
|
||||
* instead of `unattributable`. That is silently the whole pre-#2789 behavior, including
|
||||
* the pre-clearing hazard this change exists to close.
|
||||
*
|
||||
* So this follows the same law as `resolveChangedPaths` above — a failed git read is an
|
||||
* ERROR, not an empty set — and matches the head-side `readAckFile`, which already
|
||||
* throws on a document that exists but will not parse. Being more forgiving about the
|
||||
* base copy of the same file would be strictly worse: it is the copy we cannot see in
|
||||
* the diff.
|
||||
*
|
||||
* `git show` alone cannot make the distinction — a bogus ref and an absent path produce
|
||||
* the same "does not exist in" message — so absence is established with `ls-tree`, which
|
||||
* exits 0 with empty output when the path is simply not there and non-zero on a real
|
||||
* fault.
|
||||
*
|
||||
* `repoPath` defaults to the legacy single file, but is generalized (#2914) so the same
|
||||
* read-at-ref logic serves any one fragment under `ACK_DIR_REPO_PATH` too — there is
|
||||
* exactly one implementation of "read this ack path at that ref", reused per source
|
||||
* rather than re-typed per fragment.
|
||||
*/
|
||||
function readAckFileAtRef(base, { cwd = REPO_ROOT, run = git, repoPath = ACK_REPO_PATH } = {}) {
|
||||
// `execFileSync`'s array form stops SHELL metacharacters but not git's own option
|
||||
// parsing: a ref beginning with `-` is read as an option token, and `git show` honors
|
||||
// diff options including `--output=<file>`, which writes. Today every caller passes a
|
||||
// resolved 40-hex sha, but this function is exported and validated nothing itself —
|
||||
// the guard belonged with the argument, not with the one caller that happens to be safe.
|
||||
if (typeof base !== 'string' || base === '' || base.startsWith('-')) {
|
||||
throw new Error(
|
||||
`emitted-attribution: refusing to read the ack at ${JSON.stringify(base)} — a base ref `
|
||||
+ 'must be a non-empty string that does not begin with "-", which git would parse as an option.',
|
||||
);
|
||||
}
|
||||
|
||||
let listing;
|
||||
try {
|
||||
listing = run(['ls-tree', '--name-only', base, '--', repoPath], { cwd });
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`emitted-attribution: could not list the ack at "${base}": ${err.message}. This is a `
|
||||
+ 'hard error on purpose — treating an unreadable base as "nothing inherited" would '
|
||||
+ 'leave every ack able to consume a delta, which is the pre-#2789 gate.',
|
||||
);
|
||||
}
|
||||
if (listing.trim() === '') return null; // genuinely absent at that ref — the steady state
|
||||
|
||||
let raw;
|
||||
try {
|
||||
raw = run(['show', `${base}:${repoPath}`], { cwd });
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`emitted-attribution: ${repoPath} exists at "${base}" but could not be read: ${err.message}`,
|
||||
);
|
||||
}
|
||||
if (raw.trim() === '') {
|
||||
throw new Error(`emitted-attribution: ${repoPath} is present at "${base}" but empty`);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`emitted-attribution: ${repoPath} at "${base}" is not valid JSON: ${err.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment filenames present under `ACK_DIR_REPO_PATH` AT `base`, sorted.
|
||||
*
|
||||
* Mirrors `readAckFileAtRef`'s absence handling: `ls-tree` on a directory that does not
|
||||
* exist at that ref exits 0 with empty output, which this reads as "no fragments there"
|
||||
* — the healthy steady state, not a fault. A genuine git failure (bad ref, corrupt
|
||||
* object) still throws, for the same reason `readAckFileAtRef` throws on one: silently
|
||||
* reading "could not list" as "nothing there" would leave every fragment ack able to
|
||||
* consume a delta it should not.
|
||||
*/
|
||||
function listAckFragmentFilesAtRef(base, { cwd = REPO_ROOT, run = git } = {}) {
|
||||
let out;
|
||||
try {
|
||||
out = run(['ls-tree', '--name-only', base, '--', `${ACK_DIR_REPO_PATH}/`], { cwd });
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`emitted-attribution: could not list ${ACK_DIR_REPO_PATH}/ at "${base}": ${err.message}.`,
|
||||
);
|
||||
}
|
||||
const names = out
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.filter((p) => p.endsWith('.json'))
|
||||
.map((p) => p.slice(p.lastIndexOf('/') + 1))
|
||||
.sort();
|
||||
return assertFragmentCountWithinCap(`${ACK_DIR_REPO_PATH}/ at "${base}"`, names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment filenames present under `ACK_DIR` on THIS tree (the working copy), sorted.
|
||||
* Absent directory == zero fragments, the healthy steady state — not a fault.
|
||||
*/
|
||||
function listAckFragmentFiles(dir = ACK_DIR) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const names = fs.readdirSync(dir)
|
||||
.filter((name) => name.endsWith('.json'))
|
||||
.sort();
|
||||
return assertFragmentCountWithinCap(dir, names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read + union every ack source on THIS tree (#2914): the legacy single file (if
|
||||
* present) plus every fragment under `ACK_DIR`. Reuses `readAckFile` per physical file
|
||||
* (same absent/empty/unparseable rules for a fragment as for the legacy file — one
|
||||
* definition, not a second one per source) and `mergeAckSources` (tests/helpers/
|
||||
* emitted-diff.cjs) for the union + duplicate-key detection.
|
||||
*
|
||||
* Returns `{ doc: null, errors: [] }` only when NEITHER the legacy file nor any
|
||||
* fragment exists — the healthy steady state matching `readAckFile`'s own `null`
|
||||
* contract, so callers can keep testing `ack === null` to decide whether the base side
|
||||
* needs consulting at all (avoiding the deadlock `readAckFileAtRef`'s doc comment
|
||||
* describes for a corrupt base).
|
||||
*
|
||||
* @returns {{ doc: {version: number, paths: object} | null, errors: string[] }}
|
||||
*/
|
||||
function readAckSources({ legacyPath = ACK_PATH, fragmentsDir = ACK_DIR } = {}) {
|
||||
const docs = [];
|
||||
if (fs.existsSync(legacyPath)) {
|
||||
docs.push({ source: ACK_REPO_PATH, doc: readAckFile(legacyPath) });
|
||||
}
|
||||
for (const name of listAckFragmentFiles(fragmentsDir)) {
|
||||
docs.push({
|
||||
source: `${ACK_DIR_REPO_PATH}/${name}`,
|
||||
doc: readAckFile(path.join(fragmentsDir, name)),
|
||||
});
|
||||
}
|
||||
if (docs.length === 0) return { doc: null, errors: [] };
|
||||
const { merged, errors } = mergeAckSources(docs);
|
||||
return { doc: merged, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read + union every ack source AT `base` (#2914): the legacy single file plus every
|
||||
* fragment, as they existed at that ref. Mirrors `readAckSources` above, one ref-read
|
||||
* per physical source via `readAckFileAtRef`'s now-generalized `repoPath` option.
|
||||
*
|
||||
* Base-side merge/schema errors are DELIBERATELY DISCARDED, matching this module's
|
||||
* existing precedent for the base side (see `diffEmitted`'s caller below: "Base-side
|
||||
* SCHEMA errors are deliberately discarded... a document we cannot read simply inherits
|
||||
* nothing — which is the ARMED reading"). A cross-fragment collision found only at the
|
||||
* base is `next`'s own health, not this diff's to answer for; `mergeAckSources`'s
|
||||
* first-source-wins fallback for a duplicate key is still the STRICT reading here (an
|
||||
* entry can only be "spent" against the ONE reason kept, never either of two), so
|
||||
* discarding the error text costs no protection while avoiding a lint-clean PR being
|
||||
* blocked by a historical duplicate it did not introduce and cannot fix by itself.
|
||||
*
|
||||
* A genuine READ failure (corrupt JSON, unreadable object) on any single source still
|
||||
* throws, exactly as `readAckFileAtRef` already does — only the schema/collision
|
||||
* bookkeeping is discarded, never a fault.
|
||||
*
|
||||
* @returns {{ doc: {version: number, paths: object} | null }}
|
||||
*/
|
||||
function readAckSourcesAtRef(base, { cwd = REPO_ROOT, run = git } = {}) {
|
||||
const docs = [];
|
||||
const legacyDoc = readAckFileAtRef(base, { cwd, run });
|
||||
if (legacyDoc !== null) docs.push({ source: ACK_REPO_PATH, doc: legacyDoc });
|
||||
for (const name of listAckFragmentFilesAtRef(base, { cwd, run })) {
|
||||
const relPath = `${ACK_DIR_REPO_PATH}/${name}`;
|
||||
const doc = readAckFileAtRef(base, { cwd, run, repoPath: relPath });
|
||||
if (doc !== null) docs.push({ source: relPath, doc });
|
||||
}
|
||||
if (docs.length === 0) return { doc: null };
|
||||
const { merged } = mergeAckSources(docs);
|
||||
return { doc: merged };
|
||||
}
|
||||
|
||||
/**
|
||||
* Base-ref candidates, most-specific first.
|
||||
*
|
||||
@@ -935,35 +716,115 @@ function currentSizes({ repoRoot = REPO_ROOT } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read `tests/emitted-drift-ack.json`.
|
||||
* Absent is legal and means "no acks" — its PRESENCE is the alarm (ADR §3).
|
||||
* A present-but-unreadable or unparseable file THROWS: silently treating it as absent
|
||||
* would disarm the gate in the one case where someone is actively using it.
|
||||
* Bounded git invocation for the #3942 commit-trailer ack reader, built on the
|
||||
* never-throws process seam (`runGit`) rather than `git()` above: `readAckTrailers` must
|
||||
* honor a PER-CALL `timeoutMs` (row 24's hostile-timeout row), and `git()` pins
|
||||
* `GIT_TIMEOUT_MS` at import time with no per-call override. Throws on anything but a
|
||||
* clean exit — same "a git failure is a hard error, never an empty result" law as
|
||||
* `resolveChangedPaths` above.
|
||||
*/
|
||||
function readAckFile(ackPath = ACK_PATH) {
|
||||
if (!fs.existsSync(ackPath)) return null;
|
||||
const raw = fs.readFileSync(ackPath, 'utf8');
|
||||
if (raw.trim() === '') {
|
||||
throw new Error(`emitted-attribution: ${path.basename(ackPath)} is present but empty`);
|
||||
function ackTrailerGit(args, { cwd = REPO_ROOT, timeoutMs = GIT_TIMEOUT_MS } = {}) {
|
||||
const result = runGit([...safeDirArgs(cwd), ...args], { cwd, timeoutMs });
|
||||
if (result.outcome === OUTCOME.EXITED && result.exitCode === 0) {
|
||||
return result.stdout;
|
||||
}
|
||||
throw new Error(
|
||||
`emitted-ack-trailer: \`git ${args.join(' ')}\` failed — outcome=${result.outcome} `
|
||||
+ `exitCode=${result.exitCode} stderr=${(result.stderr || '').trim()}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 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
|
||||
// a different `%(trailers:...)` extraction in this same repo).
|
||||
const ACK_TRAILER_RECORD_SEP = '\x1e'; // between commits
|
||||
const ACK_TRAILER_FIELD_SEP = '\x1f'; // between the hash-space list and growth-space list
|
||||
const ACK_TRAILER_VALUE_SEP = '\x1d'; // between multiple values of the SAME trailer key
|
||||
|
||||
/**
|
||||
* Read #3942 commit-trailer acknowledgments over `<mergeBase>..<headRef>`.
|
||||
*
|
||||
* ── Why the merge-base is resolved here, not taken as `baseRef` verbatim ──────
|
||||
* `changedPaths` (`resolveChangedPaths` above) is three-dot (merge-base) by construction,
|
||||
* and 40-design.md's Correction 2 requires the trailer range to agree — otherwise a
|
||||
* trailer could excuse a delta structurally outside the diff. Reading
|
||||
* `<mergeBase>..<headRef>` (never `<baseRef>..<headRef>`) is what makes a trailer on the
|
||||
* OTHER side of a fork correctly out of range (row 7/8 — structural spentness).
|
||||
*
|
||||
* ── Why an uncomputable range THROWS, never returns empty ─────────────────────
|
||||
* A shallow clone (or any ref sharing no history with `headRef`) makes the merge-base
|
||||
* uncomputable. Returning an empty result here would read as "no acks needed" — a false
|
||||
* GREEN that silently disarms the gate. This is 40-design.md's Correction 1 (row 15/22):
|
||||
* every failure path below throws, naming "range"/"merge-base"/"shallow".
|
||||
*
|
||||
* Trailer values are read with git's OWN trailer parser
|
||||
* (`%(trailers:key=...,valueonly)`), never a regex over the message body, so a mid-body
|
||||
* mention of the trailer syntax (row 32 — this PR's own docs teach the grammar) is
|
||||
* correctly inert. `\r` is stripped from every value before parsing (row 27 — a CRLF
|
||||
* commit message must parse identically to LF).
|
||||
*
|
||||
* @param {{baseRef: string, headRef?: string, cwd?: string, timeoutMs?: number}} opts
|
||||
* @returns {{hash: Map<string, {reason: string}>, growth: Map<string, {reason: string}>, errors: string[]}}
|
||||
*/
|
||||
function readAckTrailers({ baseRef, headRef = 'HEAD', cwd = REPO_ROOT, timeoutMs = GIT_TIMEOUT_MS } = {}) {
|
||||
let mergeBaseOut;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
mergeBaseOut = ackTrailerGit(['merge-base', baseRef, headRef], { cwd, timeoutMs });
|
||||
} catch (err) {
|
||||
throw new Error(`emitted-attribution: ${path.basename(ackPath)} is not valid JSON: ${err.message}`);
|
||||
throw new Error(
|
||||
`emitted-ack-trailer: could not compute a merge-base range for "${baseRef}..${headRef}" `
|
||||
+ '(a bad ref, a shallow clone with no common ancestor, or another git failure): '
|
||||
+ err.message,
|
||||
);
|
||||
}
|
||||
const mergeBase = mergeBaseOut.trim();
|
||||
if (!/^[0-9a-f]{40}$/.test(mergeBase)) {
|
||||
throw new Error(
|
||||
`emitted-ack-trailer: git merge-base for "${baseRef}..${headRef}" returned no usable `
|
||||
+ `commit (${JSON.stringify(mergeBase)}) — the range is structurally uncomputable `
|
||||
+ '(possibly a shallow clone with no common ancestor).',
|
||||
);
|
||||
}
|
||||
|
||||
// `separator=` inside a `%(trailers:...)` placeholder is itself a PRETTY-FORMAT
|
||||
// string, not a literal — git substitutes `%x<hex>` escapes within it (same as it
|
||||
// does for the top-level `--format` string). The hex code alone (no `%x` prefix) is
|
||||
// therefore emitted as its own two literal characters, never the control byte, and
|
||||
// the `.split(ACK_TRAILER_VALUE_SEP)` below then never finds a real separator: two
|
||||
// trailers of the SAME key on one commit collapse into a single joined value instead
|
||||
// of splitting into separate entries (silent data loss — the exact failure class
|
||||
// `MAX_ACK_TRAILERS` exists to prevent). Fixed by emitting the `%x` escape.
|
||||
const ackValueSepHex = `%x${ACK_TRAILER_VALUE_SEP.codePointAt(0).toString(16).padStart(2, '0')}`;
|
||||
const format =
|
||||
`${ACK_TRAILER_RECORD_SEP}%(trailers:key=${ACK_TRAILER_HASH},valueonly,separator=${ackValueSepHex})`
|
||||
+ `${ACK_TRAILER_FIELD_SEP}%(trailers:key=${ACK_TRAILER_GROWTH},valueonly,separator=${ackValueSepHex})`;
|
||||
|
||||
let raw;
|
||||
try {
|
||||
raw = ackTrailerGit(['log', `${mergeBase}..${headRef}`, `--format=${format}`], { cwd, timeoutMs });
|
||||
} catch (err) {
|
||||
throw new Error(`emitted-ack-trailer: could not read commit trailers over the range: ${err.message}`);
|
||||
}
|
||||
|
||||
const normalized = raw.replace(/\r/g, '');
|
||||
const hashValues = [];
|
||||
const growthValues = [];
|
||||
// index 0 is the (empty) text before the FIRST record separator — every real record
|
||||
// starts with one, by construction of the `--format` string above.
|
||||
const records = normalized.split(ACK_TRAILER_RECORD_SEP).slice(1);
|
||||
for (const record of records) {
|
||||
const [hashField = '', growthFieldRaw = ''] = record.split(ACK_TRAILER_FIELD_SEP);
|
||||
const growthField = growthFieldRaw.replace(/\n+$/, ''); // git's own between-commit newline
|
||||
for (const v of hashField.split(ACK_TRAILER_VALUE_SEP)) if (v !== '') hashValues.push(v);
|
||||
for (const v of growthField.split(ACK_TRAILER_VALUE_SEP)) if (v !== '') growthValues.push(v);
|
||||
}
|
||||
|
||||
return parseAckTrailers({ hash: hashValues, growth: growthValues });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
REPO_ROOT,
|
||||
ACK_PATH,
|
||||
ACK_REPO_PATH,
|
||||
ACK_DIR,
|
||||
ACK_DIR_REPO_PATH,
|
||||
readAckFileAtRef,
|
||||
listAckFragmentFiles,
|
||||
listAckFragmentFilesAtRef,
|
||||
readAckSources,
|
||||
readAckSourcesAtRef,
|
||||
FIXTURE_SUBDIR,
|
||||
MANIFEST_FAMILIES,
|
||||
MINIMUM_MANIFEST_FAMILIES,
|
||||
@@ -985,7 +846,7 @@ module.exports = {
|
||||
measuredPackageVersion,
|
||||
currentManifests,
|
||||
currentSizes,
|
||||
readAckFile,
|
||||
readAckTrailers,
|
||||
WORKTREE_TIMEOUT_MS,
|
||||
BUILD_LIB_TIMEOUT_MS,
|
||||
BUILD_TIMEOUT_MS,
|
||||
|
||||
Reference in New Issue
Block a user