@chrono-meta/fh-gate 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,64 @@ EXIT_HARNESS_ERROR=10
62
62
  EXIT_ARG_ERROR=11
63
63
  EXIT_DRY_RUN=12
64
64
 
65
+ # ── Flag handling ─────────────────────────────────────────────────────────────
66
+ # 🟥 Added 2026-08-23 after a first-use measurement: there was NO flag handling at
67
+ # all, so `--version` and `--help` fell through to TARGET_FILES and were treated as
68
+ # file paths. The failure was not cosmetic — the script then built a governance
69
+ # prompt around a nonexistent file and sent it to the user's `claude` CLI, which
70
+ # correctly refused it as a prompt-injection attempt. A first-time user running the
71
+ # most obvious command got their own assistant accusing this tool.
72
+ #
73
+ # Unknown flags are an ERROR, never a filename. Silently demoting an unrecognized
74
+ # argument to "a file to review" is the same shape as demoting an unknown mode to a
75
+ # weaker check: the run continues, reports something, and the something is wrong.
76
+ case "${1:-}" in
77
+ --version|-V)
78
+ printf '%s\n' "fh-gate $VERSION"
79
+ exit 0
80
+ ;;
81
+ --help|-h)
82
+ printf '%s\n' "fh-gate $VERSION — FH governance gate"
83
+ printf '%s\n' ""
84
+ printf '%s\n' " Reviews a change through an AI backend and returns a typed verdict, so a"
85
+ printf '%s\n' " machine can act on it. Uses your local 'claude' CLI by default."
86
+ printf '%s\n' ""
87
+ printf '%s\n' "Usage"
88
+ printf '%s\n' " fh-gate review the current git diff (auto-detected)"
89
+ printf '%s\n' " fh-gate \"<files>\" review an explicit space-separated file list"
90
+ printf '%s\n' " fh-gate \"<files>\" <level> level: quick (default) or full"
91
+ printf '%s\n' " fh-gate --version | --help"
92
+ printf '%s\n' ""
93
+ printf '%s\n' "Exit codes"
94
+ printf '%s\n' " 0 PASS no findings"
95
+ printf '%s\n' " 1 PENDING B-grade findings; proceed with awareness"
96
+ printf '%s\n' " 2 BLOCKED A-grade findings; do not merge"
97
+ printf '%s\n' " 3 ESCALATE human decision required"
98
+ printf '%s\n' " 10 harness error — backend unavailable, timeout, unparseable verdict"
99
+ printf '%s\n' " 11 argument error"
100
+ printf '%s\n' " 12 dry run — prompt emitted, NO review performed"
101
+ printf '%s\n' ""
102
+ printf '%s\n' " 10, 11 and 12 sit outside the verdict range on purpose: a check that did"
103
+ printf '%s\n' " not run must never be readable as a pass."
104
+ printf '%s\n' ""
105
+ printf '%s\n' "Environment"
106
+ printf '%s\n' " FH_BACKEND=claude|codex|auto|cross backend (default: claude)"
107
+ printf '%s\n' " FH_MODEL=<model> model override"
108
+ printf '%s\n' " FH_DRY_RUN=1 emit the prompt only; exits 12"
109
+ printf '%s\n' " FH_TIMEOUT=<seconds> backend kill deadline (default: 120)"
110
+ printf '%s\n' " FH_VERBOSE=1 print full backend stderr"
111
+ printf '%s\n' ""
112
+ printf '%s\n' " https://github.com/chrono-meta/forge-harness"
113
+ exit 0
114
+ ;;
115
+ -*)
116
+ printf '%s\n' "ERROR: unrecognized option '${1}'." >&2
117
+ printf '%s\n' " fh-gate takes a FILE LIST, not flags — an unknown option is not a filename." >&2
118
+ printf '%s\n' " Run 'fh-gate --help' for usage." >&2
119
+ exit 11
120
+ ;;
121
+ esac
122
+
65
123
  TARGET_FILES="${FH_TARGET_FILES:-${1:-}}"
66
124
  GATE_LEVEL="${FH_GATE_LEVEL:-${2:-quick}}"
67
125
  FH_CALLER="${FH_CALLER:-${3:-ci}}"
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env bash
2
+ # files_manifest_shipping_check.sh — every path package.json declares in files[] must actually
3
+ # exist on disk AND actually land in the real npm tarball.
4
+ #
5
+ # WHY THIS EXISTS (gap named but not closed elsewhere, found 2026-08-23):
6
+ # `package_coverage_check.sh` walks REFERENCES — a shipped doc names a path, does that path ship —
7
+ # but it never iterates package.json's files[] array itself. `selfcheck.sh` (~:1065) says so in its
8
+ # own comment: "measured 2026-08-09, package_coverage_check.sh returns PASS on a files[] entry whose
9
+ # file does not exist, so a deleted subject would be green on every surface (SKIP here + PASS there
10
+ # + npm silently omitting it)." selfcheck.sh works around this for a HANDFUL of hand-picked subjects
11
+ # (branch_claim.sh, marker axes lanes, sidecar_calibrate.sh, ...), each guarded by its own
12
+ # `if [ ! -f ... ]` block, and its own comment names the remainder as a residual: "the sibling blocks
13
+ # above carry the same hole for their own shipped subjects. Fixing them is a separate change."
14
+ # This script is that separate change, done ONCE for the full 200+-entry list instead of per-subject.
15
+ #
16
+ # TWO FAILURE SHAPES THIS CATCHES, NEITHER CAUGHT ELSEWHERE:
17
+ # (a) a files[] entry whose file was deleted (rename, cleanup, a stale exception) but the
18
+ # declaration was never removed — package_coverage_check.sh reads files[] as a coverage
19
+ # ORACLE, so an entry naming nothing is invisible to it by construction.
20
+ # (b) a files[] entry that exists on disk but does not actually pack — .npmignore precedence,
21
+ # a directory that npm's own default-ignore rules (e.g. nested .git, node_modules) hollow
22
+ # out, or a git-tracked file under a declared DIRECTORY that silently fails to tar. This is
23
+ # the disk-vs-declaration gap the tarball oracle in package_coverage_check.sh was built to
24
+ # close for referenced paths; this script applies the same tarball oracle to files[] itself.
25
+ #
26
+ # SCOPE (deliberately narrow — see cross-family review 2026-08-23): this checks LITERAL paths only.
27
+ # It does NOT resolve npm glob patterns (`dist/*.js`) or normalize a leading `./` beyond a literal
28
+ # strip — an entry containing glob metacharacters is reported as OUT-OF-SCOPE, never as phantom or
29
+ # unpacked, because this script cannot know what a glob resolves to without re-implementing npm's
30
+ # own pattern matcher. Widening to real glob support is a scope increase, not a bug fix; it is
31
+ # deliberately left undone rather than guessed at.
32
+ #
33
+ # Usage: bash scripts/files_manifest_shipping_check.sh # disk-existence only, offline
34
+ # bash scripts/files_manifest_shipping_check.sh --vs-tarball # + real `npm pack` check
35
+ # Exit: 0 = every files[] entry exists on disk (and, with --vs-tarball, ships in the real
36
+ # tarball); 1 = at least one entry is a phantom declaration or an oracle failure.
37
+ set -uo pipefail
38
+
39
+ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
40
+ cd "$REPO_ROOT" || { echo "FAIL: cannot cd to repo root"; exit 1; }
41
+
42
+ # Argument validation FIRST, before anything else can silently downgrade behavior. An unrecognized
43
+ # argument (e.g. a `--vs-tarbll` typo) used to fall through to the declaration-mode default, which
44
+ # on the publish path (the ONLY caller of --vs-tarball, see prepublishOnly) means "I asked for the
45
+ # strict tarball oracle and silently got the weak one instead" — a false PASS on exactly the surface
46
+ # this script exists to guard. Unrecognized input is now a hard error, not a silent mode switch.
47
+ if [ -n "${1:-}" ] && [ "${1:-}" != "--vs-tarball" ]; then
48
+ echo "FAIL files-manifest-shipping: unrecognized argument '${1}' — did you mean --vs-tarball?"
49
+ echo " Refusing to silently fall back to a weaker check mode."
50
+ exit 1
51
+ fi
52
+ MODE="declaration"
53
+ if [ "${1:-}" = "--vs-tarball" ]; then
54
+ MODE="tarball"
55
+ fi
56
+
57
+ if [ ! -f package.json ]; then
58
+ echo "FAIL files-manifest-shipping: no package.json at repo root — declared coverage is"
59
+ echo " UNMEASURED, not clean"
60
+ exit 1
61
+ fi
62
+ command -v node >/dev/null 2>&1 || {
63
+ echo "FAIL files-manifest-shipping: node unavailable — files[] cannot be read"; exit 1; }
64
+
65
+ # Source-tree predicate, same idea package_coverage_check.sh uses: an installed package has no
66
+ # comparable files[] to self-audit against (it IS the audited output, not the declaration).
67
+ #
68
+ # BUT the degrade direction differs BY MODE, and that split is deliberate (cross-family review
69
+ # 2026-08-23, S1). `--vs-tarball` has exactly one caller in this repo: prepublishOnly. There is no
70
+ # legitimate "installed package" scenario on that path — `npm publish`/`npm pack` only make sense
71
+ # run from the source checkout that IS being published, so a missing `.git` there means the
72
+ # environment is not what the publish path expects, not that the check has nothing to do. Per the
73
+ # Irreversibility Surface-Class Degrade Invariant (CLAUDE.md): an irreversible surface (publish)
74
+ # fails CLOSED when its tooling/environment is off-shape, it does not get a free skip. Declaration
75
+ # mode keeps the original SKIP — it runs from more places (e.g. a routine sweep against an
76
+ # installed/vendored copy) where "no .git" genuinely does mean "nothing comparable to check".
77
+ if [ ! -d .git ] && [ ! -f .git ]; then
78
+ if [ "$MODE" = "tarball" ]; then
79
+ echo "FAIL files-manifest-shipping (--vs-tarball): no .git at repo root on the publish path —"
80
+ echo " this check has exactly one caller (prepublishOnly) and it always runs from the"
81
+ echo " source checkout being published. Fail-closed: an off-shape publish environment is"
82
+ echo " not a legitimate reason to skip an irreversible-surface check."
83
+ exit 1
84
+ fi
85
+ echo "SKIP files-manifest-shipping (no .git — looks like an installed package, not a source checkout)"
86
+ exit 0
87
+ fi
88
+
89
+ echo "files-manifest shipping check ($MODE)"
90
+
91
+ if [ "$MODE" = "tarball" ]; then
92
+ command -v npm >/dev/null 2>&1 || {
93
+ echo "FAIL files-manifest-shipping (--vs-tarball): npm is not on PATH — the tarball oracle is"
94
+ echo " UNAVAILABLE. Fail-closed: this is an irreversible-surface check (publish path), and"
95
+ echo " an unreadable oracle must never render as pass."
96
+ exit 1
97
+ }
98
+ # git is also required for the tarball-mode directory walk (walkTracked, below, via `git
99
+ # ls-files`). Checked here rather than left to fail mid-walk so a missing binary renders as an
100
+ # explicit instrument-unavailable FAIL, not as a per-directory "zero tracked files" phantom
101
+ # (cross-family review 2026-08-23, A4: a `git ls-files` failure must never be reported as if the
102
+ # TARGET were empty — it means the INSTRUMENT could not look).
103
+ command -v git >/dev/null 2>&1 || {
104
+ echo "FAIL files-manifest-shipping (--vs-tarball): git is not on PATH — the declared-directory"
105
+ echo " tracked-file walk is UNAVAILABLE. Fail-closed, same reasoning as the npm check above."
106
+ exit 1
107
+ }
108
+ fi
109
+
110
+ # Scratch directory, not a predictable /tmp/*.$$ filename. A predictable per-PID temp path is
111
+ # guessable and writable by any other local process before this one gets to read it back (cross-
112
+ # family review 2026-08-23, A2). `mktemp -d` gives a directory only this process's owner can see
113
+ # (mode 0700 by default on both GNU and BSD mktemp), and every write into it below is check-marked —
114
+ # a write that silently failed used to be indistinguishable from "nothing to report".
115
+ FMSC_DIR="$(mktemp -d "${TMPDIR:-/tmp}/fmsc.XXXXXXXX")" || {
116
+ echo "FAIL files-manifest-shipping: mktemp -d failed — cannot allocate a private scratch dir"
117
+ exit 1
118
+ }
119
+ trap 'rm -rf "$FMSC_DIR"' EXIT
120
+ FMSC_JS="$FMSC_DIR/check.js"
121
+ FMSC_PACK_JSON="$FMSC_DIR/pack.json"
122
+ FMSC_PACK_ERR="$FMSC_DIR/pack.err"
123
+
124
+ if [ "$MODE" = "tarball" ]; then
125
+ PACK_JSON=$(npm pack --dry-run --json 2>"$FMSC_PACK_ERR")
126
+ PACK_RC=$?
127
+ if [ "$PACK_RC" -ne 0 ] || [ -z "$PACK_JSON" ]; then
128
+ echo "FAIL files-manifest-shipping (--vs-tarball): npm pack exited $PACK_RC — tarball UNKNOWN"
129
+ sed 's/^/ /' "$FMSC_PACK_ERR" 2>/dev/null
130
+ exit 1
131
+ fi
132
+ printf '%s' "$PACK_JSON" > "$FMSC_PACK_JSON" || {
133
+ echo "FAIL files-manifest-shipping (--vs-tarball): could not write pack output to scratch dir"
134
+ exit 1
135
+ }
136
+ fi
137
+
138
+ # bash 3.2 (macOS system bash) has a documented heredoc-inside-command-substitution bug: a quoted
139
+ # heredoc (`<<'NODE'`) body containing single quotes can still desync `$( ... )`'s own quote count,
140
+ # producing a false "unexpected EOF" parse error even though the heredoc itself is syntactically
141
+ # correct. Writing the JS to a real file and invoking it by path sidesteps the bug entirely.
142
+ cat > "$FMSC_JS" <<'NODE'
143
+ const fs = require('fs');
144
+
145
+ const mode = process.argv[2];
146
+ const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
147
+
148
+ // Malformed `files` field must FAIL, not silently coerce to an empty/single-entry list (cross-
149
+ // family review 2026-08-23, A1: `pkg.files || []` let `"files": "."` pass as "1 entry checked").
150
+ // npm's own contract is that `files` is an array of path/glob strings; anything else is an invalid
151
+ // manifest, and an invalid manifest is not a clean result.
152
+ if (pkg.files !== undefined && !Array.isArray(pkg.files)) {
153
+ console.log(`FAIL\tpackage.json files[] is not an array (got ${typeof pkg.files}) — invalid`
154
+ + ' manifest, not a clean result');
155
+ process.exit(1);
156
+ }
157
+ const declared = pkg.files || [];
158
+
159
+ if (declared.length === 0) {
160
+ console.log('FAIL\tpackage.json files[] is EMPTY or missing — that is not a clean result, it is an\n\tinstrument that found nothing to check');
161
+ process.exit(1);
162
+ }
163
+
164
+ // Line-protocol sanitizer: every string emitted below goes through this first. Without it, a path
165
+ // containing a literal newline (attacker-controlled files[] entry, or a corrupted manifest) can
166
+ // inject a line that itself starts with "PASS" or another verdict token, which a naive human or
167
+ // grep-based reader downstream could mistake for the real verdict (cross-family review 2026-08-23,
168
+ // A3). JSON.stringify turns any control character, including \n and \t, into a visible escape and
169
+ // wraps the value in quotes, so an injected line can never masquerade as line-protocol output.
170
+ function safe(s) { return JSON.stringify(s); }
171
+
172
+ // SCOPE GUARD (cross-family review 2026-08-23, B1/B2): this script checks LITERAL paths only. An
173
+ // entry containing npm glob metacharacters cannot be resolved to a real filesystem path without
174
+ // re-implementing npm's own matcher, so treating a glob as a literal-and-missing path is a false
175
+ // PHANTOM, not a scope limitation being honest about itself. `./`-prefixed entries are npm's own
176
+ // documented way of writing a literal (npm strips the prefix when building the tarball), so THAT
177
+ // case is safe to normalize rather than punt out of scope.
178
+ const GLOB_RE = /[*?{}\[\]]/;
179
+ function normalizeLiteral(entry) {
180
+ return entry.startsWith('./') ? entry.slice(2) : entry;
181
+ }
182
+
183
+ let tarballSet = null;
184
+ if (mode === 'tarball') {
185
+ const packPath = process.argv[3];
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(fs.readFileSync(packPath, 'utf8'));
189
+ } catch (e) {
190
+ console.log(`FAIL\tnpm pack --json did not parse (${e.constructor.name}) — tarball UNKNOWN`);
191
+ process.exit(1);
192
+ }
193
+ const entry = Array.isArray(parsed) ? parsed[0] : null;
194
+ const list = entry && Array.isArray(entry.files) ? entry.files : null;
195
+ if (!list || list.length === 0) {
196
+ // Impossible-zero guard, same rule package_coverage_check.sh applies to this same oracle:
197
+ // a genuinely empty tarball means the instrument broke, not that the package shrank to nothing.
198
+ console.log(`FAIL\tnpm pack reported ${list ? list.length : 0} files — implausible, oracle UNAVAILABLE`);
199
+ process.exit(1);
200
+ }
201
+ // Below-threshold is now an ADVISORY, not an automatic FAIL (cross-family review 2026-08-23, B3:
202
+ // a legitimately tiny package — package.json + README + LICENSE + one file — used to hard-fail on
203
+ // count alone). A near-empty tarball is still worth a human's eyes, so it is surfaced as its own
204
+ // line-protocol kind rather than silently accepted, but it no longer blocks by itself; only the
205
+ // phantom/unpacked findings computed below can still FAIL the run.
206
+ if (list.length < 10) {
207
+ console.log(`ADVISORY\tnpm pack reported only ${list.length} files — small package, or a`
208
+ + ' shrunk oracle. Not auto-failed; verify by eye if this package is not meant to be tiny.');
209
+ }
210
+ tarballSet = new Set(list.map(f => normalizeLiteral(f.path)));
211
+ }
212
+
213
+ function walkTracked(dir) {
214
+ // git-tracked descendants only — untracked/gitignored files under a declared directory are not
215
+ // this check's business (they are correctly absent from both git and the tarball).
216
+ //
217
+ // INSTRUMENT FAILURE vs TARGET EMPTY (cross-family review 2026-08-23, A4): the git binary itself
218
+ // is checked for availability before this function is ever called (bash side, above), so an error
219
+ // reaching here means `git ls-files` itself failed against a directory that IS tracked in git
220
+ // (the .git-presence check upstream already established this is a real git checkout) — a
221
+ // corrupted index, a pathspec git rejects, or similar. That is the INSTRUMENT breaking, not the
222
+ // target having zero files, so it must not be folded into "zero tracked files" and reported as a
223
+ // phantom declared-directory. It throws instead, and the caller renders it as its own kind.
224
+ const { execFileSync } = require('child_process');
225
+ return execFileSync('git', ['ls-files', '--', dir], { encoding: 'utf8' })
226
+ .split('\n').filter(Boolean);
227
+ }
228
+
229
+ const phantoms = []; // declared, absent on disk
230
+ const unpacked = []; // exists on disk, declared, but did not make the real tarball (tarball mode only)
231
+ const outOfScope = []; // glob entry — this checker does not resolve glob patterns
232
+ const instrumentErrors = []; // the oracle itself failed while examining a specific entry
233
+
234
+ for (const rawEntry of declared) {
235
+ if (typeof rawEntry !== 'string') {
236
+ instrumentErrors.push(`non-string files[] entry: ${safe(rawEntry)}`);
237
+ continue;
238
+ }
239
+ if (GLOB_RE.test(rawEntry)) {
240
+ outOfScope.push(rawEntry);
241
+ continue;
242
+ }
243
+ const entry = normalizeLiteral(rawEntry);
244
+ let stat;
245
+ try {
246
+ stat = fs.statSync(entry);
247
+ } catch (e) {
248
+ phantoms.push(rawEntry);
249
+ continue;
250
+ }
251
+ if (mode !== 'tarball') continue;
252
+
253
+ if (stat.isDirectory()) {
254
+ let tracked;
255
+ try {
256
+ tracked = walkTracked(entry);
257
+ } catch (e) {
258
+ instrumentErrors.push(`git ls-files failed for declared dir '${rawEntry}': ${e.message}`);
259
+ continue;
260
+ }
261
+ if (tracked.length === 0) {
262
+ // A declared directory with zero git-tracked files under it is its own phantom shape —
263
+ // shipping an empty directory declaration gives the consumer nothing either way. This is
264
+ // reached only when `git ls-files` itself SUCCEEDED and reported nothing, so it is a real
265
+ // target finding, not an instrument failure (see walkTracked's comment above).
266
+ phantoms.push(rawEntry + '/ (declared directory, zero git-tracked files under it)');
267
+ continue;
268
+ }
269
+ for (const t of tracked) {
270
+ if (!tarballSet.has(normalizeLiteral(t))) unpacked.push(t + ' (under declared dir ' + rawEntry + ')');
271
+ }
272
+ } else {
273
+ if (!tarballSet.has(entry)) unpacked.push(rawEntry);
274
+ }
275
+ }
276
+
277
+ const hasFailure = phantoms.length > 0 || unpacked.length > 0 || instrumentErrors.length > 0;
278
+
279
+ if (!hasFailure) {
280
+ const scopeNote = outOfScope.length > 0 ? `, ${outOfScope.length} out-of-scope (glob)` : '';
281
+ console.log(`PASS\t${declared.length} files[] entries checked, 0 phantom, 0 unpacked${scopeNote}`);
282
+ process.exit(0);
283
+ }
284
+
285
+ for (const s of outOfScope) console.log('SCOPE\t' + safe(s));
286
+ for (const p of phantoms) console.log('PHANTOM\t' + safe(p));
287
+ for (const u of unpacked) console.log('UNPACKED\t' + safe(u));
288
+ for (const ie of instrumentErrors) console.log('INSTRUMENT-ERROR\t' + ie);
289
+ console.log(`FAIL\t${phantoms.length} phantom declaration(s), ${unpacked.length} declared-but-unpacked`
290
+ + ` path(s), ${instrumentErrors.length} instrument error(s)`);
291
+ process.exit(1)
292
+ NODE
293
+
294
+ if [ "$MODE" = "tarball" ]; then
295
+ RESULT=$(node "$FMSC_JS" "$MODE" "$FMSC_PACK_JSON")
296
+ else
297
+ RESULT=$(node "$FMSC_JS" "$MODE")
298
+ fi
299
+ RC=$?
300
+
301
+ echo "$RESULT" | while IFS=$'\t' read -r kind detail; do
302
+ case "$kind" in
303
+ PASS) echo "PASS files-manifest-shipping: $detail" ;;
304
+ ADVISORY) echo " ⚠️ $detail" ;;
305
+ FAIL) printf 'FAIL files-manifest-shipping: %s\n' "$detail" ;;
306
+ SCOPE) echo " ⏭️ out of scope (glob pattern, not resolved): $detail" ;;
307
+ PHANTOM) echo " ❌ declared in files[] but ABSENT on disk: $detail" ;;
308
+ UNPACKED) echo " ❌ declared, present on disk, but NOT in the real npm tarball: $detail" ;;
309
+ INSTRUMENT-ERROR) echo " 🛑 instrument failure examining this entry (target unproven, not clean): $detail" ;;
310
+ *) echo "$kind $detail" ;;
311
+ esac
312
+ done
313
+
314
+ exit "$RC"