Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 859de84

Browse files
claude[bot]claude
andauthored
feat(devx): pin the ported guard-main-checkout self-test, and stop --resync rewriting governed files (#7954)
`scripts/upstream-port-pin.json` covered only `scripts/`, so the verbatim cross-repo ports under `.claude/hooks/**` — this repo's densest concentration of copies from the same upstream, and the one directory whose drift history is four separate human catches (#5459, #5712, #5789, #6042) — had no drift gate at all. Two changes, in the order they have to happen: 1. `--resync` now REFUSES to rewrite a ported path on the governed surface unless `--rewrite-governed-file` is passed, naming the path, the surface it matched and the flag. The governed set is read from `check-governed-queue-guard.mjs` rather than re-listed. The CHECK path is untouched: a drifted governed port reds with no flag and no exemption. 2. `.claude/hooks/guard-main-checkout.selftest.sh` is registered against the upstream blob the pin already names, with 14 declared divergences and a one-sentence `why` each. The wiring test's `pinned ⊆ patrol.paths` assertion silently encoded "the ledger only pins the sweeper's unit". It is re-scoped to the patrol's own unit, and the claim that matters for entries outside it is asserted directly: no pinned file falls inside `lint.yml`'s ignore set, so the PR that drifts one is never the PR on which the gate does not run. Claude-Session: https://claude.ai/code/session_013uAaxiwgYDybsTNV9xwa1M Co-authored-by: Claude <noreply@anthropic.com>
1 parent d4864f3 commit 859de84

3 files changed

Lines changed: 273 additions & 7 deletions

File tree

‎scripts/__tests__/upstream-port-parity-wiring.test.ts‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,78 @@ describe('check-upstream-port-parity is wired, not merely present', () => {
8686
expect(pinned).toContain('scripts/invoked-as.mjs');
8787
});
8888

89-
it('the pinned files are the ones the patrol workflow watches', () => {
90-
// Both directions of the same claim: a file added to the patrol's paths
91-
// filter but not to the pin drifts unwatched, and a file in the pin that
92-
// the patrol no longer uses is a stale obligation.
89+
it("the patrol's own ported unit is pinned, in both directions", () => {
90+
// ⚠️ Re-scoped by objectui#7263, which registered the first entry OUTSIDE
91+
// `scripts/`. This assertion used to read `pinned ⊆ watched` — every pinned
92+
// file must appear in the patrol's paths filter — which silently encoded
93+
// "the ledger only ever pins the sweeper's unit". That was true of the two
94+
// entries that existed and is not a property of the ledger: the patrol runs
95+
// ONE ported program, and a hook self-test has no business in its filter.
96+
//
97+
// Both directions are kept, each scoped to the thing it is actually about:
98+
// a ported file the patrol watches but nothing pins drifts unwatched, and a
99+
// pinned file from the patrol's own unit that the patrol dropped is a stale
100+
// obligation. The reach of the pin BEYOND that unit is the next test's job.
93101
const patrol = parseYaml(
94102
fs.readFileSync(path.join(ROOT, '.github/workflows/half-state-patrol.yml'), 'utf8'),
95103
);
96104
const watched: string[] = patrol.on.pull_request.paths;
97105
const pin = JSON.parse(fs.readFileSync(path.join(ROOT, PIN), 'utf8'));
98106
const pinned: string[] = pin.files.map((f: { ported: string }) => f.ported);
99-
for (const p of pinned) expect(watched).toContain(p);
107+
// forward: everything the patrol watches, other than the workflow file that
108+
// declares the watch, is a ported program and must be pinned.
109+
for (const p of watched.filter((w) => !w.startsWith('.github/'))) expect(pinned).toContain(p);
110+
// back: the patrol's own unit, identified by where the sweeper lives, must
111+
// still be in that filter.
112+
for (const p of pinned.filter((f) => f.startsWith('scripts/pm/'))) expect(watched).toContain(p);
113+
});
114+
115+
it('every pinned file is one the gate actually runs on when it drifts', () => {
116+
// The wiring claim that had to exist once the ledger reached past
117+
// `scripts/` (objectui#7263). `lint.yml` runs this gate, and its `relevant`
118+
// step skips every step below it when a pull request touches ONLY the paths
119+
// it ignores. A ported file inside that ignore set would be pinned and
120+
// unwatched at the same time: the PR that drifts it is exactly the PR on
121+
// which the gate does not run, and the drift lands green — the failure this
122+
// whole mechanism exists to make impossible, one level up.
123+
const lintYml = fs.readFileSync(path.join(ROOT, '.github/workflows/lint.yml'), 'utf8');
124+
const relevant = lintYml.slice(lintYml.indexOf('id: relevant'));
125+
const ignored = [...relevant.matchAll(/':\(exclude,glob\)([^']+)'/g)].map((m) => m[1]);
126+
// Tokenised, not chained replaces: a chain rewrites the `*` it has already
127+
// emitted into a substitution, and the resulting pattern matches nothing —
128+
// an assertion that passes because it recognises nothing, which is the
129+
// shape this whole file is about.
130+
const matches = (glob: string, file: string) =>
131+
new RegExp(
132+
`^${glob
133+
.split(/(\*\*\/|\*\*|\*|\?)/)
134+
.map((tok) =>
135+
tok === '**/'
136+
? '(?:.*/)?'
137+
: tok === '**'
138+
? '.*'
139+
: tok === '*'
140+
? '[^/]*'
141+
: tok === '?'
142+
? '[^/]'
143+
: tok.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
144+
)
145+
.join('')}$`,
146+
).test(file);
147+
148+
// The control leg: every glob in that list must actually recognise a file
149+
// it is there to ignore. Without this the loop below is green on a matcher
150+
// that never matches.
151+
expect(ignored).toEqual(expect.arrayContaining(['**/*.md', 'content/**', 'docs/**', '.changeset/**']));
152+
expect(ignored.filter((g) => matches(g, 'docs/adr/0001-example.md'))).toEqual(['**/*.md', 'docs/**']);
153+
expect(ignored.filter((g) => matches(g, 'content/docs/guide/a.md'))).toEqual(['**/*.md', 'content/**']);
154+
expect(ignored.filter((g) => matches(g, '.changeset/lucky-pans-smile.md'))).toEqual(['**/*.md', '.changeset/**']);
155+
156+
const pin = JSON.parse(fs.readFileSync(path.join(ROOT, PIN), 'utf8'));
157+
const pinned: string[] = pin.files.map((f: { ported: string }) => f.ported);
158+
for (const file of pinned) {
159+
expect({ file, ignoredBy: ignored.filter((g) => matches(g, file)) }).toEqual({ file, ignoredBy: [] });
160+
}
100161
});
101162

102163
it('its self-test passes — the half that makes a green comparison mean something', () => {

‎scripts/check-upstream-port-parity.mjs‎

Lines changed: 116 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
* node scripts/check-upstream-port-parity.mjs --self-test # verify the checker itself
1010
* node scripts/check-upstream-port-parity.mjs --resync <upstream-file> --ref <sha>
1111
* # the deliberate re-sync act
12+
* …the same, plus --rewrite-governed-file # …when the ported file is
13+
* # GOVERNED SURFACE and you are
14+
* # the human merging it
1215
*
1316
* ## What this gate is for
1417
*
@@ -87,6 +90,27 @@
8790
* (zero occurrences), but a divergence that still applies and no longer makes
8891
* sense is only visible to those tests.
8992
*
93+
* ## `--resync` REFUSES to rewrite governed surface unless told, by name
94+
*
95+
* The ledger REGISTERS a file; `--resync` REWRITES one. Those are different
96+
* powers and only the second one is dangerous here. `.claude/**`, `skills/**`,
97+
* `docs/adr/**`, `AGENTS.md` and `CLAUDE.md` are this repository's governed
98+
* surface — the operating rules every later session reads — and they carry a
99+
* human-merge rule precisely because no green check can say whether a rule
100+
* SHOULD be the rule. A tool that silently rewrites one of them in place, from
101+
* another repository's bytes, is a governed-surface edit nobody chose.
102+
*
103+
* So the write path asks `check-governed-queue-guard.mjs` — the repository's own
104+
* definition of that surface, reused rather than re-listed, so the two can never
105+
* disagree — and refuses, naming the path, its surface and the flag that
106+
* proceeds anyway. `--rewrite-governed-file` is spelled long on purpose: it is
107+
* for the human doing the merge, and it reads as what it does at the call site.
108+
*
109+
* ⛔ The CHECK path is NOT governed by any of this. A drifted governed port reds
110+
* exactly like any other, with no flag and no exemption — the refusal is about
111+
* WRITING, and a gate that went quiet on the surface with the worst drift
112+
* history would be the whole card inverted.
113+
*
90114
* ## The divergences are a checklist, not a licence
91115
*
92116
* Every entry carries a `why`. An adaptation nobody can justify in one sentence
@@ -104,6 +128,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
104128
import path from 'node:path';
105129
import process from 'node:process';
106130
import { fileURLToPath } from 'node:url';
131+
import { GOVERNED_SURFACES, governedPathsIn } from './check-governed-queue-guard.mjs';
107132
import { isEntrypoint } from './invoked-as.mjs';
108133

109134
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -297,6 +322,54 @@ function resyncCommand(pin, entry) {
297322
);
298323
}
299324

325+
/**
326+
* The flag that lets `--resync` write a GOVERNED file. Long on purpose: it is
327+
* typed by the human doing the merge, and it has to read as what it does.
328+
*/
329+
export const RESYNC_GOVERNED_FLAG = '--rewrite-governed-file';
330+
331+
/**
332+
* May `--resync` write this ported path? Pure, so the self-test drives the real
333+
* decision rather than a restatement of it, and so the answer costs nothing.
334+
*
335+
* The governed set is not restated here: `governedPathsIn` is the repository's
336+
* own definition (`scripts/check-governed-queue-guard.mjs`), and a second copy
337+
* of it would be one more thing to keep honest — the disease this whole file is
338+
* about, one level up.
339+
*
340+
* @returns {{ write: boolean, governed: boolean, surface: object|null, reasons: string[] }}
341+
*/
342+
export function resyncWriteVerdict(portedPath, { allowGoverned = false } = {}) {
343+
const [surface = null] = governedPathsIn([portedPath]);
344+
if (!surface) return { write: true, governed: false, surface: null, reasons: [] };
345+
if (allowGoverned) {
346+
return {
347+
write: true,
348+
governed: true,
349+
surface,
350+
reasons: [
351+
`${portedPath} is GOVERNED SURFACE (${surface.glob} — ${surface.what}) and ` +
352+
`${RESYNC_GOVERNED_FLAG} was passed: rewriting it in place.`,
353+
],
354+
};
355+
}
356+
return {
357+
write: false,
358+
governed: true,
359+
surface,
360+
reasons: [
361+
`⛔ refusing to rewrite ${portedPath}: it is GOVERNED SURFACE ` +
362+
`(${surface.glob} — ${surface.what}), which this repository merges by human review.`,
363+
`A re-sync would replace it with another repository's bytes, which is a governed-surface`,
364+
`edit nobody chose. The pin is unchanged and nothing was written.`,
365+
` • To see what a re-sync WOULD do, diff the upstream file against this one by hand.`,
366+
` • To do it anyway — as the human doing that merge — pass ${RESYNC_GOVERNED_FLAG}.`,
367+
` • Registering this file in the pin is NOT affected: checking is not writing, and a`,
368+
` drifted governed port reds this gate with no flag and no exemption.`,
369+
],
370+
};
371+
}
372+
300373
function main(root = ROOT) {
301374
let pin;
302375
try {
@@ -422,6 +495,11 @@ function resync(argv, root = ROOT) {
422495
);
423496
return 1;
424497
}
498+
const write = resyncWriteVerdict(entry.ported, {
499+
allowGoverned: argv.includes(RESYNC_GOVERNED_FLAG),
500+
});
501+
for (const r of write.reasons) (write.write ? console.log : console.error)(r);
502+
if (!write.write) return 2;
425503
writeFileSync(path.join(root, entry.ported), text, 'utf8');
426504
entry.upstreamSha256 = digest(upstreamText);
427505
pin.upstream.ref = ref;
@@ -530,7 +608,42 @@ function selfTest() {
530608
t('a divergence whose upstream anchor vanished fails the re-sync loudly', lost.problems.length === 1);
531609
t('…naming the divergence that no longer applies', lost.problems.join(' ').includes('`extra-guard`'));
532610

533-
// ── row 5: a malformed pin is REFUSED, never read as clean ─────────────────
611+
// ── row 5: --resync REFUSES to rewrite governed surface ────────────────────
612+
// The write path only. Every row drives `resyncWriteVerdict`, which is the
613+
// decision `resync()` makes, so a green row means the refusal is reachable
614+
// rather than merely written down.
615+
const GOV = '.claude/hooks/guard-main-checkout.selftest.sh';
616+
const refused = resyncWriteVerdict(GOV);
617+
t('a governed ported path is REFUSED by --resync', refused.write === false);
618+
t('…and the refusal names the path', refused.reasons.join(' ').includes(GOV));
619+
t('…and names the flag that proceeds anyway', refused.reasons.join(' ').includes(RESYNC_GOVERNED_FLAG));
620+
t('…and names the surface it matched, not just "governed"', refused.reasons.join(' ').includes('.claude/**'));
621+
// The refusal must not read as "this file cannot be pinned": registering is
622+
// the whole point of the card that added this, and checking is not writing.
623+
t('…and says registering/checking is unaffected', refused.reasons.join(' ').includes('drifted governed port reds this gate'));
624+
const allowed = resyncWriteVerdict(GOV, { allowGoverned: true });
625+
t('…and the named flag lets it proceed', allowed.write === true && allowed.governed === true);
626+
t('…saying out loud that it is rewriting a governed file', allowed.reasons.join(' ').includes('GOVERNED SURFACE'));
627+
// Every surface the REGISTER declares, derived from it rather than re-listed:
628+
// a second copy of that list here would drift from the guard's own.
629+
t(
630+
'every surface in GOVERNED_SURFACES refuses, and the list is not copied here',
631+
GOVERNED_SURFACES.every((sf) => resyncWriteVerdict(sf.exact ?? `${sf.prefix}specimen.txt`).write === false),
632+
);
633+
// The other direction, which is the one that would make the gate useless in
634+
// the ordinary case: a plain script is written exactly as before.
635+
const plain = resyncWriteVerdict('scripts/pm/check-half-states.mjs');
636+
t('a NON-governed ported path is unchanged: it writes, and says nothing', plain.write === true && plain.governed === false && plain.reasons.length === 0);
637+
t('…and the flag does not change it either', JSON.stringify(resyncWriteVerdict('scripts/pm/check-half-states.mjs', { allowGoverned: true })) === JSON.stringify(plain));
638+
// ⛔ The CHECK path is not governed by any of this. Drift in a governed port
639+
// reds with no flag and no exemption — the refusal is about WRITING, and a
640+
// gate that went quiet on the surface with the worst drift history would be
641+
// this whole mechanism inverted.
642+
const govEntry = { ...ENTRY, ported: GOV };
643+
t('checking a governed ported file is NOT gated: parity still holds', verifyFile(govEntry, PORTED).ok);
644+
t('…and drift in one still REDS, with no flag involved', !verifyFile(govEntry, driftedOutside).ok);
645+
646+
// ── row 6: a malformed pin is REFUSED, never read as clean ─────────────────
534647
const good = { upstream: { repo: 'o/r', ref: 'a'.repeat(40) }, files: [ENTRY] };
535648
t('the fixture pin is well-formed', validatePin(good).length === 0);
536649
const broken = [
@@ -582,7 +695,8 @@ function selfTest() {
582695
`✓ check-upstream-port-parity self-test: ${cases.length} cases pass — parity holds on an undrifted copy, ` +
583696
'drift outside the declared regions reds as a digest mismatch, drift inside one names its divergence, ' +
584697
'an ambiguous anchor is refused rather than applied, the pin-bump procedure round-trips (and a vanished ' +
585-
'anchor fails it loudly), and every malformed-pin shape is refused instead of read as clean.',
698+
'anchor fails it loudly), `--resync` refuses to rewrite governed surface unless the named flag is passed ' +
699+
'while the CHECK path stays ungated, and every malformed-pin shape is refused instead of read as clean.',
586700
);
587701
return 0;
588702
}

0 commit comments

Comments
 (0)