@chrono-meta/fh-gate 2.8.0 → 2.9.1

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.
Files changed (45) hide show
  1. package/.claude/rules/fh_4axis_gate.md +33 -5
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/AGENTS.md +5 -0
  4. package/CLAUDE.md +47 -12
  5. package/README.ja.md +44 -29
  6. package/README.ko.md +43 -28
  7. package/README.md +48 -33
  8. package/README.zh.md +41 -28
  9. package/docs/ETHOS.md +48 -8
  10. package/docs/GATE_DAY.md +235 -0
  11. package/docs/OUTPUT_EVIDENCE.md +13 -2
  12. package/docs/codex-compat.md +10 -2
  13. package/knowledge/shared/harness-core/agents_md_runtime_details.md +10 -3
  14. package/knowledge/shared/harness-core/fh_three_layer_canon.md +20 -2
  15. package/knowledge/shared/harness-core/field_verdict_crossfamily_gate.md +23 -5
  16. package/knowledge/shared/harness-core/harness_incubator_doctrine.md +6 -1
  17. package/knowledge/shared/harness-core/measurement-integrity-checklist.md +31 -0
  18. package/knowledge/shared/harness-core/ship_readiness_gate.md +2 -2
  19. package/knowledge/shared/learnings/subagent_invocations_log.yaml +31 -0
  20. package/knowledge/shared/rules/multi_session_close_protocol.md +8 -1
  21. package/package.json +17 -3
  22. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  23. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  24. package/plugins/fh-meta/CHANGELOG.md +122 -0
  25. package/plugins/fh-meta/skills/cross-ecosystem-synergy-detection/SKILL.md +93 -3
  26. package/scripts/chamber_candidate_collect.sh +71 -13
  27. package/scripts/compaction_probe.sh +17 -2
  28. package/scripts/fh-gate.sh +58 -0
  29. package/scripts/files_manifest_shipping_check.sh +314 -0
  30. package/scripts/mapped_tracks.sh +113 -0
  31. package/scripts/package_coverage_check.sh +54 -0
  32. package/scripts/postinstall_notice.js +9 -2
  33. package/scripts/prior_art_prompt.sh +49 -2
  34. package/scripts/selfcheck.sh +58 -2
  35. package/scripts/session_close_check.sh +56 -3
  36. package/scripts/test_chamber_sig_lanes.sh +151 -0
  37. package/scripts/test_files_manifest_shipping_lanes.sh +260 -0
  38. package/scripts/test_leak_scan_control_lanes.sh +163 -0
  39. package/scripts/test_mapped_tracks_lanes.sh +162 -0
  40. package/scripts/test_peer_worktree_detect_lanes.sh +138 -0
  41. package/scripts/test_prepush_destructive_lanes.sh +366 -0
  42. package/scripts/test_prior_art_prompt_lanes.sh +48 -0
  43. package/scripts/test_regression_guard_ci_lanes.sh +124 -0
  44. package/templates/predelete_check.test.sh +56 -0
  45. package/templates/regression_guard.sh +75 -3
@@ -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"
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env bash
2
+ # mapped_tracks.sh — the ONE mechanical answer to "how many field harnesses are mapped in this hub?"
3
+ #
4
+ # WHY THIS EXISTS (measured 2026-08-22, known-pair in one run):
5
+ # main checkout : 11 mapped tracks
6
+ # a worktree : 1
7
+ # The mapping signal is the PRESENCE of `tracks/<name>/`, and that signal cannot survive into a
8
+ # worktree for two independent reasons: (a) `tracks/**` is gitignored, and (b) at least one mapped
9
+ # track (`pmh-dev`) is an EMPTY directory, which git cannot carry even if it were tracked. So a
10
+ # worktree does not have a smaller count — it has a STRUCTURALLY BLIND one.
11
+ #
12
+ # WHY THAT WAS SILENT: the synergy skill's Step 3-b closes as `run(n pairs)` or
13
+ # `skipped(<2 mapped tracks)`, and BOTH are mandatory-pass values. A worktree run therefore closed
14
+ # GREEN while blind — the same shape as the ①-c peer-detection defect fixed the same day, on the
15
+ # instrument that grades identity ④ itself.
16
+ #
17
+ # MECHANIZED AT N=2 BY CLASS, NOT BY COUNT: `operations.md` allows mechanization at "N>=3 **or the
18
+ # same class recurring on another surface**". This class (a count over gitignored, un-committable
19
+ # state read from cwd instead of the repo's common root) hit two distinct surfaces on 2026-08-22 —
20
+ # ①-c peer placement and Step 3-b mapped-track counting. Recorded here so the threshold is not
21
+ # claimed loosely.
22
+ #
23
+ # NOT-FOUND IS NOT ZERO. If the root cannot be resolved or `tracks/` is not there, this exits 3 with
24
+ # status=UNMEASURED. It never prints `count=0` for a question it could not ask.
25
+ #
26
+ # Usage: bash scripts/mapped_tracks.sh [--count-only]
27
+ # Exit: 0 = measured · 3 = UNMEASURED (a NON-PASS; never fold into "0 mapped") · 2 = bad usage
28
+
29
+ set -uo pipefail
30
+
31
+ COUNT_ONLY=0
32
+ case "${1:-}" in
33
+ --count-only) COUNT_ONLY=1 ;;
34
+ "") ;;
35
+ *) echo "usage: $0 [--count-only]" >&2; exit 2 ;;
36
+ esac
37
+
38
+ _die_unmeasured() {
39
+ echo "status=UNMEASURED"
40
+ echo "reason=$1"
41
+ echo "# not-found != zero — do NOT read this as 'no mapped tracks'"
42
+ exit 3
43
+ }
44
+
45
+ command -v git >/dev/null 2>&1 || _die_unmeasured "git-absent"
46
+
47
+ # Resolve the hub root the way this repo already sanctions for worktree-reachable evidence
48
+ # (`templates/.git-hooks/pre-commit` §EVIDENCE_ROOT): `--git-common-dir` returns the MAIN tree's .git
49
+ # from inside any worktree.
50
+ # ⚠️ Deliberately NOT the `$(cmd || echo "")` form used there. Under a `cmd || fallback` the guard
51
+ # depends on the failing command leaving stdout empty; the canonical form separates the value from
52
+ # the status so a command that fails WHILE printing cannot be mistaken for a success.
53
+ _repo_root=$(git rev-parse --show-toplevel 2>/dev/null); _rc_root=$?
54
+ [ "$_rc_root" -eq 0 ] && [ -n "$_repo_root" ] || _die_unmeasured "not-in-a-git-repo"
55
+
56
+ _gcd=$(git rev-parse --git-common-dir 2>/dev/null); _rc_gcd=$?
57
+ if [ "$_rc_gcd" -ne 0 ] || [ -z "$_gcd" ]; then
58
+ HUB_ROOT="$_repo_root" # degraded but named below, not silently
59
+ ROOT_SRC="repo-root(common-dir-unresolved)"
60
+ else
61
+ case "$_gcd" in
62
+ # `--git-common-dir` returns a RELATIVE path ('.git') at a repo root and an ABSOLUTE one inside a
63
+ # worktree. Comparing or using it raw is exactly the bug this script exists to close.
64
+ /*) HUB_ROOT=$(dirname "$_gcd") ;;
65
+ *) HUB_ROOT=$(dirname "$_repo_root/$_gcd") ;;
66
+ esac
67
+ ROOT_SRC="git-common-dir"
68
+ fi
69
+ # Normalise both sides before comparing — a raw string compare would reproduce the defect.
70
+ HUB_ROOT=$(cd "$HUB_ROOT" 2>/dev/null && pwd -P) || _die_unmeasured "hub-root-unreadable"
71
+ CWD_ROOT=$(cd "$_repo_root" 2>/dev/null && pwd -P) || CWD_ROOT="$_repo_root"
72
+
73
+ IN_WORKTREE=no
74
+ [ "$HUB_ROOT" != "$CWD_ROOT" ] && IN_WORKTREE=yes
75
+
76
+ [ -d "$HUB_ROOT/tracks" ] || _die_unmeasured "no-tracks-dir-at:$HUB_ROOT"
77
+
78
+ # 🟥 존재만 보면 부족하다 — «못 읽었다» 가 «없다» 로 접힌다 (2026-08-23 실측, 4케이스).
79
+ # 이 파일 머리가 "not-found != zero" 를 이유로 존재하는데, 초판은 그 규율을 **존재 검사 한 분기에만**
80
+ # 적용했다: 디렉터리가 있는데 읽을 수 없으면 아래 글롭이 조용히 0건을 내고 `status=OK count=0` 이
81
+ # 나간다 — 진짜로 매핑이 0개인 경우와 **출력이 글자 하나 안 다르다.** 그리고 하류(Step 3-b)에서
82
+ # 그 0 은 `skipped(<2 mapped tracks)` = **pass 값**으로 접히므로, 권한 문제가 초록으로 닫힌다.
83
+ # chmod 755 → -r ✓ -x ✓ 글롭 1 chmod 111 → -r ✗ -x ✓ 글롭 0 ← `-x` 만 보면 통과시킨다
84
+ # chmod 500 → -r ✓ -x ✓ 글롭 1 chmod 000 → -r ✗ -x ✗ 글롭 0
85
+ # ⇒ 둘 다 요구한다. 이 조합이 «글롭이 셀 수 있는가» 와 네 케이스 전부에서 일치한다(레인 P-1·P-2).
86
+ { [ -r "$HUB_ROOT/tracks" ] && [ -x "$HUB_ROOT/tracks" ]; } || _die_unmeasured "tracks-dir-unreadable-at:$HUB_ROOT"
87
+
88
+ # Count. Underscore-prefixed dirs are META (_meta/_audit/_contrib/_chamber…) and are not mapped
89
+ # projects — the test is a LEADING underscore only.
90
+ # ⚠️ Measured slip, kept as a comment because it cost a re-measure: a `case "$n" in *_*)` filter
91
+ # also eats `the_bible`, whose underscore is in the middle. Anchor the pattern.
92
+ NAMES=""; COUNT=0
93
+ for _d in "$HUB_ROOT"/tracks/*/; do
94
+ [ -d "$_d" ] || continue # unmatched glob stays literal in sh
95
+ _n=$(basename "$_d")
96
+ case "$_n" in _*) continue ;; esac
97
+ COUNT=$((COUNT + 1))
98
+ NAMES="$NAMES $_n"
99
+ done
100
+
101
+ if [ "$COUNT_ONLY" = "1" ]; then echo "$COUNT"; exit 0; fi
102
+
103
+ echo "status=OK"
104
+ echo "hub_root=$HUB_ROOT"
105
+ echo "root_source=$ROOT_SRC"
106
+ echo "in_worktree=$IN_WORKTREE"
107
+ echo "count=$COUNT"
108
+ echo "names=${NAMES# }"
109
+ if [ "$IN_WORKTREE" = "yes" ]; then
110
+ echo "# NOTE: running from a worktree; the count above is the MAIN tree's, resolved via"
111
+ echo "# --git-common-dir. The worktree's own tracks/ is NOT the answer to this question."
112
+ fi
113
+ exit 0
@@ -127,8 +127,62 @@ ACCEPTED_ABSENT=(
127
127
  # 「출하된 레인의 **주체**가 출하되나」를 안 본다. 그 갭은 아직 안 닫혔다(명시 잔여).
128
128
  "scripts/test_satellite_publish_gate_lanes.sh"
129
129
  "scripts/test_satellite_profile_schema_lanes.sh"
130
+ # · 2026-08-22, 파괴적-op 앵커 배선이 만든 셋. **같은 선례의 재현이고, 이 검사기가 또 잡았다** —
131
+ # `test_prepush_destructive_lanes.sh` 를 files[] 에 넣고 `selfcheck.sh` 의 pair-표에 전체
132
+ # 경로 두 줄을 쓴 순간, 그 두 파일이 이름 대는 것들이 팬텀이 됐다. 위 블록이 예고한 그대로다.
133
+ # ⓐ test_prepush_destructive_liveness.sh — 일부러 안 싣는다. 7단계 중 둘이 **레포-개발 전용
134
+ # 컨트롤**이라 소비자 install 에서 정직할 수 없다: ⑥ orphan 은 주체
135
+ # `templates/predelete_check.test.sh` 가 미출하라 **부재로 FAIL**(옳지 않은 red), ⑦
136
+ # containment 는 소비자 트리가 보통 git work tree 가 아니라 **잴 게 없다**. 싣게 하려면
137
+ # 패키지-모드 라우팅을 그 두 단계에 심어야 하는데 그건 소비자에게 값이 없는 코드다.
138
+ # ⓑ 🟥 **철회 — 이 자리에 있던 `test_new_code_anchor_lanes.sh` 항목을 뺐다.** 그 항목이
139
+ # 필요했던 유일한 이유는 `test_prepush_destructive_lanes.sh` 의 한 주석이 그 파일을 경로로
140
+ # 인용했기 때문인데, **그 인용이 이번 라운드에 재조준됐다**(추적되는 선례로). 단독 착지
141
+ # 준비 중 발견 — 안 고쳤으면 **커밋되지 않는 파일을 가리키는 팬텀 참조**를 출하할 뻔했다.
142
+ # 인용이 사라지면 예외도 사라져야 한다. **소비되지 않는 예외는 다음 진짜 누락을 삼킨다.**
143
+ # ⓒ templates/predelete_check.test.sh — 주체 `templates/predelete_check.sh` 는 **출하되는데**
144
+ # 이 앵커는 안 나간다. 🟥 위 test_chamber_run_lanes 와 **같은 모양의 빚**이고, 클린한 답이
145
+ # 아니다. 여기 등재하는 이유도 같다: files[] 추가는 소비자-대면 변경이라 false-FAIL 이
146
+ # 없음을 tarball 모드로 따로 증명해야 하는데, 이 델타는 **배선 델타**다. 카드로 이월.
147
+ "scripts/test_prepush_destructive_liveness.sh"
148
+ # 🟥 ⓒ 는 **철회했다 — cross-family R2 지적이 맞았다.** 초판이
149
+ # `templates/predelete_check.test.sh` 를 여기 넣고 «위 chamber 건과 같은 빚» 이라고 적었는데,
150
+ # 그 둘은 같지 않다: chamber 는 «주체가 출하되는데 앵커가 안 나간다» 를 **빚으로 남긴** 것이고,
151
+ # 여기 등재는 그 빚을 **침묵시킨다**. 이 목록의 뜻은 「출하 안 하는 게 옳다」이지
152
+ # 「출하해야 하는데 아직 안 했다」가 아니다. 후자를 여기 넣으면 **다음 사람이 같은 누락을
153
+ # 만나도 이 예외에 걸려 안 보인다** — 지적 원문: *"A future shipped reference to this same
154
+ # missing anchor will also be accepted, not surfaced."*
155
+ # ⇒ `files[]` 에 실었다. 주체 `templates/predelete_check.sh` 가 이미 출하되므로 소비자는
156
+ # 자기 enumerate 도구를 검증할 수 있게 되고, 부수로 liveness stage ⑥ 의 오탐(주체 부재로
157
+ # ORPHANED)도 닫힌다.
158
+ # ⓓ 🟥 **그리고 ⓑ 의 사유를 쓰자 그 사유가 팬텀을 만들었다.** 위 주석이 주체 이름을
159
+ # 경로로 적는데 **이 파일 자신이 shipped 문서**라, 「안 싣는 이유」를 설명한 행위가
160
+ # 곧 「shipped 문서가 미출하 경로를 가리킴」이 됐다. 계기가 자기 수리를 잡은 것이고,
161
+ # 위 블록이 예고한 형태(*전체 경로를 shipped 파일에 쓰면 팬텀이 된다*)의 **3차 재현**이다.
162
+ # 주체 자신도 같은 사유로 등재한다 — 신규 게이트 둘은 **이 레포 전용**이다(추가 파일을
163
+ # 이 레포 레인 코퍼스에 대고 판정한다). 소비자 트리엔 판정 대상이 없다.
130
164
  "scripts/residency_closure_scan.py"
131
165
  "scripts/test_residency_closure_lanes.sh"
166
+ # ── caller-zero-ratchet, 2026-08-22. 셋 다 **싣는 것이 틀렸다** — 「아직 안 실었다」가 아니다 ──
167
+ # 이 게이트는 「production 스크립트에 디스패처가 있나」를 **이 레포의 러너 표면**에 대고 판정한다.
168
+ # 그 표면의 하나가 `.github/workflows/**` 이고, **워크플로 디렉터리는 files[] 에 없다.** 그러므로
169
+ # 소비자 트리에서 이 검사기를 돌리면 워크플로에서만 디스패치되는 스크립트들이 전부 caller 0 으로
170
+ # 떨어지고, 그것들은 소비자의 `caller_zero_baseline.txt` 에 선언돼 있지 않으므로 **UNDECLARED →
171
+ # exit 1**. 즉 출하하면 **모든 신선한 설치에서 100% 적색**이다 — CLAUDE.md 가 「모든 새 install 을
172
+ # 막는 게이트는 엄격한 게이트가 아니라 우회 훈련기」라고 못박은 그 형태이고, 바로 위
173
+ # outbound_query_guard 블록과 **같은 사유**다.
174
+ # 앵커도 같이 안 나간다. 주체 부재라는 짝 규칙 말고 **자기 자신의 사유가 하나 더 있다**: 마지막
175
+ # 레인(L27)이 `.github/workflows/caller-zero-ratchet.yml` 을 읽어 워크플로가 리졸버를 인라인으로
176
+ # 되돌리지 않았는지 본다. 그 파일이 없는 트리에서 그 레인은 **부재를 결함으로 읽어 적색**이 된다.
177
+ # 🟥 위 ⓒ 의 교훈은 여기 **해당하지 않는다**: 저건 「주체는 출하되는데 앵커만 빠진」 빚이었고,
178
+ # 여기는 주체·앵커·베이스리졸버가 **셋 다** 소비자에게 판정 대상이 없다. 침묵시키는 게 아니라
179
+ # 애초에 그쪽 트리에 질문이 없다.
180
+ # ⚠️ 명시 잔여: 그래서 이 게이트는 **이 레포에서만** 회귀를 막는다. 소비자 설치본의
181
+ # built-but-not-wired 는 이것으로 안 잡히고, 그걸 잡으려면 러너 표면 목록을 패키지 모드로
182
+ # 라우팅하는 별도 설계가 필요하다 — 안 했다.
183
+ "scripts/script_caller_ratchet.sh"
184
+ "scripts/ratchet_base_resolve.sh"
185
+ "scripts/test_script_caller_ratchet_lanes.sh"
132
186
  # ── The two settings destinations, surfaced 2026-08-13 by fixing this file's own extractor ────
133
187
  # These were invisible until the `js|json` alternation below was corrected: every `.json`
134
188
  # reference in every shipped doc was being truncated to `.js`, a path that exists nowhere, so
@@ -24,8 +24,15 @@ if (process.env.CI || process.env.FH_NO_BANNER || process.env.CONTINUOUS_INTEGRA
24
24
  }
25
25
  try {
26
26
  process.stderr.write(
27
- '\n⭐ forge-harness (fh-gate) — if this is useful, a star helps others find it:\n' +
28
- ' https://github.com/chrono-meta/forge-harness\n' +
27
+ '\n✓ fh-gate installed — a governance gate for AI-written changes.\n' +
28
+ '\n' +
29
+ ' Try it on a change you already have:\n' +
30
+ ' npx fh-gate # reviews your git diff, returns a typed verdict\n' +
31
+ ' # PASS 0 · PENDING 1 · BLOCKED 2 · ESCALATE 3\n' +
32
+ ' Runs through your local `claude` CLI. Nothing staged? Stage something first —\n' +
33
+ ' with an empty diff it has nothing to review.\n' +
34
+ '\n' +
35
+ '⭐ Useful? A star helps others find it: https://github.com/chrono-meta/forge-harness\n' +
29
36
  ' (set FH_NO_BANNER=1 to silence this message)\n\n'
30
37
  );
31
38
  } catch (_) {
@@ -129,9 +129,56 @@ esac
129
129
  # 날짜로 degrade(침묵이 아니라 «덜 자주» 쪽).
130
130
  _SID_SAFE=$(printf '%s' "${SID:-}" | tr -cd 'A-Za-z0-9_-')
131
131
  STAMP="${CLAUDE_PROJECT_DIR:-.}/.claude/.prior_art_prompted_${_SID_SAFE:-$(date +%Y%m%d)}"
132
- [ -f "$STAMP" ] && exit 0
132
+
133
+ # ③-b 🟥 **세션당 1회로는 T2 를 구조적으로 못 잡는다** (실측 2026-08-22, 한 세션 전수 재생).
134
+ # 이 훅의 존재 이유는 이 파일 머리가 적어둔 «T2 = 컨텍스트가 길어진 뒤 **또** 새로 빌드업할 때» 인데,
135
+ # 스탬프가 세션 스코프면 그 «또» 가 영원히 억제된다. 한 세션(08:29~13:33)에서 새 메커니즘 3건이
136
+ # 08:38 · 13:06 · 13:07 에 났고, 세션당 1회는 **첫 건만** 띄웠다 — 억제된 둘이 정확히 T2 다.
137
+ # ⇒ 시간 재무장으로 바꾼다. 마지막 **발화** 시각에서 N초가 지나면 다시 무장한다.
138
+ #
139
+ # 🟥 N 은 임의로 골랐다. 이 값은 데이터가 정한 것이 아니다 — 같은 실측에서 **N=1h·2h·4h 가 전부
140
+ # 같은 결과(2 발화)** 를 냈다. 즉 **데이터가 N 을 판별하지 않았다**, n=1 세션이고, 그 세션의
141
+ # 간극이 4.5시간이라 임계에 둔감했을 뿐이다. §Mechanization Boundary 의 «오늘의 판단을 내일의
142
+ # 천장으로 굳히지 마라» 에 걸리는 자리라, 상수를 박는 대신 **아래 로그를 남겨서 다음 세션들이
143
+ # 실제 분포를 쌓게 한다.** N 재정은 그 로그 위에서만 해라 — 이 주석을 지우지 말고.
144
+ # 왜 «대상 파일당 1회» 가 아닌가: 같은 실측에서 13:06 `mapped_tracks.sh` 와 13:07 그 레인 스위트는
145
+ # **한 메커니즘**이다. 파일당이면 13:07 이 같은 메커니즘을 재질문하는 **오발화**가 된다. 이 파일
146
+ # 머리가 «오발화는 미발화보다 훨씬 비싸다(소음 = 자기무력화 경로)» 라고 못박은 방향과 반대다.
147
+ PRIOR_ART_REARM_SECONDS="${PRIOR_ART_REARM_SECONDS:-7200}" # 2h — 위 단락이 이 값의 출처이자 한계다
148
+
149
+ # 시계는 주입 가능하다 — 픽스처가 4.5시간을 실시간으로 기다릴 수는 없다. 테스트 시임일 뿐이고
150
+ # 억제를 **끄지는** 못한다(값을 넣어도 아래 산술을 그대로 통과해야 한다).
151
+ _NOW="${PRIOR_ART_NOW:-$(date +%s)}"
152
+ case "$_NOW" in ''|*[!0-9]*) _NOW=$(date +%s) ;; esac
153
+
154
+ _LAST=""
155
+ if [ -f "$STAMP" ]; then
156
+ _LAST=$(cat "$STAMP" 2>/dev/null | tr -cd '0-9')
157
+ fi
158
+
159
+ # 로그. 🟥 발화만이 아니라 **억제도** 남긴다 — 「몇 건 억제」만 세면 그것이 옳은 억제였는지 못
160
+ # 가른다. 그래서 무엇을(파일명) · 직전 발화로부터 얼마나(초) 를 같이 적는다.
161
+ # 실패해도 판정은 안 바뀐다(로깅은 게이트가 아니다).
162
+ _PA_LOG="${CLAUDE_PROJECT_DIR:-.}/.claude/.prior_art_events.tsv"
163
+ _pa_log() { # $1=FIRE|SUPPRESS $2=elapsed-or-dash
164
+ mkdir -p "$(dirname "$_PA_LOG")" 2>/dev/null || true
165
+ printf '%s\t%s\t%s\t%s\t%s\n' \
166
+ "$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null)" "$1" "${_SID_SAFE:-nosid}" "$2" "$FILE" \
167
+ >> "$_PA_LOG" 2>/dev/null || true
168
+ }
169
+
170
+ if [ -n "$_LAST" ]; then
171
+ _ELAPSED=$(( _NOW - _LAST ))
172
+ if [ "$_ELAPSED" -lt "$PRIOR_ART_REARM_SECONDS" ]; then
173
+ _pa_log SUPPRESS "$_ELAPSED"
174
+ exit 0
175
+ fi
176
+ _pa_log FIRE "$_ELAPSED"
177
+ else
178
+ _pa_log FIRE -
179
+ fi
133
180
  mkdir -p "$(dirname "$STAMP")" 2>/dev/null || true
134
- : > "$STAMP" 2>/dev/null || true
181
+ printf '%s\n' "$_NOW" > "$STAMP" 2>/dev/null || true
135
182
 
136
183
  MSG="🔎 새 메커니즘을 쓰려는 참이다 ($(basename "$FILE")). 짓기 전에 **책장부터, 없으면 도서관** —
137
184
  안 했으면 지금 하고, 했으면 이 줄은 무시해라.