@chrono-meta/fh-gate 3.28.0 → 3.30.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.
Files changed (56) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/AGENTS.md +7 -2
  3. package/CHEATSHEET.md +2 -2
  4. package/CLAUDE.md +5 -2
  5. package/docs/REFERENCE.md +4 -1
  6. package/knowledge/shared/harness-core/claude_md_full_reference.md +2 -0
  7. package/knowledge/shared/harness-core/claude_md_gate_details.md +8 -1
  8. package/knowledge/shared/harness-core/dispatch_conditional_prohibition.md +12 -0
  9. package/knowledge/shared/harness-core/fh_three_layer_canon.md +12 -0
  10. package/knowledge/shared/harness-core/measurement-integrity-checklist.md +16 -0
  11. package/knowledge/shared/learnings/subagent_invocations_log.yaml +161 -0
  12. package/package.json +4 -1
  13. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  14. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  15. package/plugins/fh-meta/CHANGELOG.md +41 -0
  16. package/plugins/fh-meta/skills/auto-decorrelation/SKILL.md +17 -0
  17. package/plugins/fh-meta/skills/phantom-quench/SKILL.md +1 -1
  18. package/plugins/fh-meta/skills/sim-conductor/SKILL.md +2 -2
  19. package/plugins/fh-meta/skills/sim-conductor/SKILL_detail.md +3 -3
  20. package/plugins/fh-meta/skills/steel-quench/SKILL.md +25 -1
  21. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  22. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  23. package/scripts/degrade_direction_scan.sh +43 -0
  24. package/scripts/dispatch_receipt.py +185 -0
  25. package/scripts/doc_claim_triad_scan.py +43 -4
  26. package/scripts/fh-gate.sh +71 -11
  27. package/scripts/finding_fleet.sh +15 -3
  28. package/scripts/mapped_tracks.sh +20 -13
  29. package/scripts/memory_gc_report.py +55 -5
  30. package/scripts/package_coverage_check.sh +5 -0
  31. package/scripts/pr_merge_verified.sh +56 -8
  32. package/scripts/selfcheck.sh +43 -20
  33. package/scripts/session_checklist.py +158 -14
  34. package/scripts/session_close_check.sh +1 -1
  35. package/scripts/sim_isolated_run.sh +62 -0
  36. package/scripts/stale_ref_scan.py +47 -3
  37. package/scripts/test_degrade_scan_shell_probes.sh +81 -0
  38. package/scripts/test_dispatch_receipt_lanes.sh +95 -0
  39. package/scripts/test_doc_claim_triad_lanes.sh +30 -0
  40. package/scripts/test_fh_audit_check_lanes.sh +10 -5
  41. package/scripts/test_fh_gate_regressions.sh +71 -1
  42. package/scripts/test_finding_pipeline_lanes.sh +83 -0
  43. package/scripts/test_hook_source_gate_lanes.sh +16 -2
  44. package/scripts/test_locale_invariance_lanes.sh +19 -0
  45. package/scripts/test_mapped_tracks_lanes.sh +55 -1
  46. package/scripts/test_memory_gc_report_lanes.sh +91 -1
  47. package/scripts/test_mutation_probe_lanes.sh +40 -8
  48. package/scripts/test_pr_merge_verified_lanes.sh +48 -1
  49. package/scripts/test_prepush_real_fire_lanes.sh +215 -0
  50. package/scripts/test_selfcheck_state_lanes.sh +32 -0
  51. package/scripts/test_session_checklist_lanes.sh +172 -0
  52. package/scripts/test_sim_isolated_run_lanes.sh +88 -0
  53. package/scripts/test_stale_ref_scan_lanes.sh +11 -1
  54. package/templates/.git-hooks/pre-push +82 -1
  55. package/templates/PRE-PUBLISH-CHECKLIST.md +10 -0
  56. package/templates/degrade_direction_scan.sh +43 -0
@@ -525,7 +525,8 @@ over **unchanged** code:
525
525
  terminal) or run one more round over the trimmed artifact before declaring Done.
526
526
  2. **Record the per-round yield vector** in the Axis-2 marker — `axis2-rounds: 4A / 3A+1B / 2A /
527
527
  0A+3B / 1A+2B`. It is what makes the stop decision auditable afterwards, and a flat or rising
528
- vector is criterion 4's only input.
528
+ vector is the input to criterion 4's reduce-the-design branch (its premise-attack branch fires on
529
+ shared assumptions, whatever the vector).
529
530
 
530
531
  **PIN THE TARGET — mandatory on every dispatched Wave, and the reason criterion 1 can be trusted
531
532
  at all.** The dispatch prompt carries a measured fingerprint and orders the agent to report
@@ -584,6 +585,29 @@ over **unchanged** code:
584
585
  stays flat is not telling you to review harder; it is telling you that each round's repairs are
585
586
  manufacturing the next round's findings. Cut the scope that is generating them (see the
586
587
  Added-Scope Gate in `.claude/rules/fh_4axis_gate.md`) and re-audit the smaller artifact.
588
+ **Attack the premise before the third repair — when two rounds' A-or-higher findings share one assumption,
589
+ whether or not the yield falls.**
590
+ When two rounds' A-or-higher findings are different instances of one assumption — «this list can
591
+ be completed», «this string shape covers every caller» — another instance-level repair is likely
592
+ to repeat the failure. Before choosing the next repair, write the shared premise down in one line,
593
+ test it directly (one counter-example settles it), and if it falls, change the design rather than
594
+ the list: flip a blocklist to an allowlist, move the check to where the input is already typed, or
595
+ drop the exemption. **Which cure**: flipping to «unknown goes to a person» is right on an
596
+ irreversible surface, or where the expected rate of person-routed prompts fits a review budget you
597
+ can name — it moves the cost
598
+ into over-blocking, and an over-block that fires often trains the bypass. Elsewhere prefer moving the
599
+ check to typed input or dropping the exemption. If you flip, say what the over-block costs (which
600
+ common inputs now reach a person). Two more flips on 2026-10-19 were gate surfaces and list their
601
+ accepted over-blocks in the PR body (FoD #80 delete outside the working folder: `echo rm …`,
602
+ `git rm`, `rm x # /path` · #81 writes to the user settings file: `jq … > tmp && mv`, quoted `>`,
603
+ `cat … 2>/dev/null`). Measured 2026-10-19, same day, two surfaces: FoD gate read-side exemptions
604
+ (5 A in one cross-family round — `_getframe`, NFKC fullwidth names, `PYTHONPATH`, …) and the
605
+ cartridge admission checker (R1 4 A, R2 1 A) both rested on «a blocklist of shell/tool strings can
606
+ be completed»; the exemptions were dropped and the checker flipped to an allowlist, so an unknown
607
+ string now lands on the human instead of on a missing list entry. That flip is not convergence —
608
+ the checker shipped NOT-CONVERGED at the round cap, and said so
609
+ ([[feedback_static_shell_string_check_does_not_converge]]).
610
+ Prior art: the «attack the premise» principle in pstack (`cursor/plugins`).
587
611
  5. Full Wave results → recommend persisting to `tracks/_meta/steel_quench_YYYY_MM_DD_{slug}.md`
588
612
 
589
613
  > **Why this replaced "zero new S-grade → terminate" (measured 2026-08-02, PR #231).** A single
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-preprep",
3
- "version": "3.28.0",
3
+ "version": "3.30.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-qp",
3
- "version": "3.28.0",
3
+ "version": "3.30.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -588,6 +588,49 @@ for f in "${FILES[@]}"; do
588
588
  | grep -vE '^[0-9]+:[[:space:]]*#' \
589
589
  | grep -vE '#[[:space:]]*noqa[:[:space:]]*degrade')
590
590
  fi
591
+
592
+ # S7 — `set -e` under a declared exit contract that has its OWN error code, with no ERR trap.
593
+ # Under `set -e` a command that fails where nobody expected it ends the script with THAT
594
+ # command's status — usually 1. If the contract reserves a separate code for "the tool itself
595
+ # broke" (10 HARNESS_ERROR and the like), the low codes are verdicts, so a crash leaks out as
596
+ # one of them. Measured 2026-10-20 on fh-gate.sh: a failing `mktemp` exited 1 = PENDING
597
+ # ("proceed with awareness"); reported from outside, fixed in #927. The cure is an ERR trap
598
+ # that exits the error code, plus an exit-time check that 0..N only leave through the verdict
599
+ # sites (`set -u` and a failing EXIT-trap function end with 1 WITHOUT firing ERR).
600
+ # SCOPE, so this stays quiet: all three must hold — `set -…e…` · a comment header naming exit
601
+ # codes · a contract line naming an error code (harness/internal/tool error). A contract of
602
+ # just "0 = pass, 1 = fail" is excluded: there an unexpected 1 already points the safe way.
603
+ # Census 2026-10-20 over this repo's tracked shell: 1 file matched the shape (fh-gate.sh).
604
+ # FILE-level probe: it reports the `set -e` line once.
605
+ # Round-1 cross-family review (codex) widened three things: `set -o errexit` and `cmd; set -e`
606
+ # activate it; an `EXIT_*ERROR=10`-style constant counts as a contract; and a trap only counts
607
+ # when it EXITS — `trap cleanup ERR` (no exit) and a commented-out trap do not protect anything.
608
+ # A grep that ERRORS (rc>1) is reported as S7-UNMEASURED, never read as "no hit" — the same
609
+ # default-toward-clean shape this probe exists to find.
610
+ _s7_rc() { grep "$@" "$f" >/dev/null 2>&1; echo $?; }
611
+ _s7_lines=$(grep -nE '(^|[;{&|])[[:space:]]*set[[:space:]]+(-[A-Za-z]*e[A-Za-z]*|-o[[:space:]]+errexit)([[:space:];]|$)' "$f" 2>/dev/null); _s7_r1=$?
612
+ _s7_set=$(printf '%s\n' "$_s7_lines" | grep -vE '^[0-9]+:[[:space:]]*#' | grep -vE '#[[:space:]]*noqa[:[:space:]]*degrade' | sed -n 1p)
613
+ _s7_r2=$(_s7_rc -qE '^[[:space:]]*#.*\b[Ee]xit([[:space:]]+codes?|[[:space:]]+status(es)?)?[[:space:]]*:')
614
+ _s7_r3=$(_s7_rc -qiE '^[[:space:]]*#.*\b[0-9]+([[:space:]]*(—|–|-|=|:|\))[[:space:]]*.{0,40}|[[:space:]]+)(harness|internal|tool)[ _-]?error')
615
+ # ^ a CONTRACT ENTRY (`10 — Harness error`, `10 harness error`), not prose that happens to hold a
616
+ # number and the word (an old test file's comment «the count is 0 … HARNESS_ERROR» was flagged).
617
+ _s7_r4=$(_s7_rc -qE '^[[:space:]]*[A-Z_]*(HARNESS|INTERNAL|TOOL)_?ERR(OR)?[A-Z_]*=[0-9]+')
618
+ # protecting trap: an ACTIVE (non-comment) `trap … ERR` line that exits, or that names a handler
619
+ # function whose body (next 12 lines) exits.
620
+ _s7_traps=$(grep -nE "^[^#]*\btrap[[:space:]].*[[:space:]'\"]ERR(['\"]|[[:space:];]|$)" "$f" 2>/dev/null); _s7_r5=$?
621
+ _s7_guard=""
622
+ if [ -n "$_s7_traps" ]; then
623
+ if printf '%s\n' "$_s7_traps" | grep -qE '\bexit\b'; then _s7_guard=1
624
+ else
625
+ _s7_h=$(printf '%s\n' "$_s7_traps" | sed -nE "s/.*trap[[:space:]]+['\"]?([A-Za-z_][A-Za-z0-9_]*)['\"]?[[:space:]].*/\\1/p" | sed -n 1p)
626
+ [ -n "$_s7_h" ] && grep -A12 -E "^[[:space:]]*(function[[:space:]]+)?${_s7_h}[[:space:]]*\(\)" "$f" 2>/dev/null | grep -qE '\bexit\b' && _s7_guard=1
627
+ fi
628
+ fi
629
+ if [ "$_s7_r1" -gt 1 ] || [ "$_s7_r2" -gt 1 ] || [ "$_s7_r3" -gt 1 ] || [ "$_s7_r4" -gt 1 ] || [ "$_s7_r5" -gt 1 ]; then
630
+ emit "$f" 1 "S7-UNMEASURED(sh)" "could not read this file for the set -e / exit-contract check (grep error) — NOT checked, not clean"
631
+ elif [ -n "$_s7_set" ] && { { [ "$_s7_r2" -eq 0 ] && [ "$_s7_r3" -eq 0 ]; } || [ "$_s7_r4" -eq 0 ]; } && [ -z "$_s7_guard" ]; then
632
+ emit "$f" "${_s7_set%%:*}" "S7:set-e-leaks-verdict(sh)" "\`set -e\` under an exit contract that has its own error code, but no ERR trap that exits — an unexpected failure exits with the failing command's status (usually 1), which the contract reads as a verdict; add \`trap '…; exit <error-code>' ERR\` and an EXIT check that 0..N only leave through the verdict sites (set -u and EXIT-trap failures do not fire ERR). Do NOT add set -E without checking \`\$( ) || rc=\$?\` captures"
633
+ fi
591
634
  fi
592
635
 
593
636
  # Probe A — except/else/finally block returning a permissive value within 2 lines.
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ """dispatch_receipt.py — the governor's own receipt for edit work a dispatched agent says it did.
3
+
4
+ Why (2026-10-20): an agent's hand-back («committed 7f2acd2, 11 files, tests green») is a claim. CLAUDE.md §Agent Dispatch
5
+ says a sidecar's findings stay evidence until the governor closes each against a mechanical anchor — for EDIT work there was
6
+ no anchor, so the close step read the agent's own summary. Outside anchors for the same gap: arXiv:2610.15459 and «report ≠
7
+ change» (frontier digest 2026-10-20). This prints what the repository says, measured by the governor, and with a claim
8
+ compares it with the files the agent named.
9
+
10
+ Usage: python3 scripts/dispatch_receipt.py <repo-or-worktree> <base-ref> [--claimed a,b,...] [--claimed-file F] [--head REF]
11
+ --claimed comma-separated paths. An empty entry, a duplicate or a path with leading/trailing space is REFUSED (rc 2):
12
+ a claim is never silently rewritten. Paths containing a comma need --claimed-file.
13
+ --claimed-file one path per line (or NUL-separated if the file contains NUL bytes), same refusal rules.
14
+ Prints head sha · branch · commits base..head · per-path line (sha256 prefix of the blob at head, «deleted», «submodule <sha>»,
15
+ «symlink <sha>») · uncommitted(tracked) / untracked counts.
16
+ Exit: 0 = receipt printed and the claim (if any) equals the changed set exactly · 1 = claim differs (named both ways), or tracked
17
+ changes are not committed · 2 = usage / malformed claim · 10 = harness error (any git call failed, base is not an ancestor of head).
18
+ 🟥 Rename detection is OFF: a move lists both the old and the new path — every affected path, independent of git config.
19
+ 🟥 «0 paths» is not a pass when a claim names files: rc 1.
20
+ 🟥 Named residual (codex R3, rounds capped there): the receipt overrides the git settings that changed its answer in review
21
+ (GIT_* env, replace refs, diff.relative, ignoreSubmodules, fileMode, quotePath) and measures from the top level. It still
22
+ trusts the rest of the repository's own config and hooks-free plumbing; it is a receipt for cooperative dispatch, not a
23
+ sandbox for a hostile repository.
24
+ """
25
+ import hashlib, os, subprocess, sys
26
+
27
+ # 🟥 codex R3: inherited GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE … would make it measure another repository — drop every GIT_*
28
+ # variable, then set only what the receipt needs. Replacement refs off: the printed sha must be the measured history.
29
+ ENV = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
30
+ ENV.update(GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0", GIT_LITERAL_PATHSPECS="1", GIT_NO_REPLACE_OBJECTS="1", LC_ALL="C")
31
+
32
+
33
+ class HarnessError(Exception):
34
+ pass
35
+
36
+
37
+ def git(repo, *args):
38
+ r = subprocess.run(["git", "-C", repo, "-c", "core.fsmonitor=false", "-c", "core.quotePath=false",
39
+ "-c", "diff.ignoreSubmodules=none", "-c", "status.showUntrackedFiles=normal",
40
+ "-c", "diff.relative=false", "-c", "core.fileMode=true", *args],
41
+ capture_output=True, env=ENV)
42
+ if r.returncode != 0:
43
+ raise HarnessError("git %s failed (rc=%d): %s" % (" ".join(args[:2]), r.returncode,
44
+ r.stderr.decode("utf-8", "replace").strip()[:200]))
45
+ return r.stdout
46
+
47
+
48
+ def usage(msg):
49
+ print("usage: dispatch_receipt.py <repo-or-worktree> <base-ref> [--claimed a,b] [--claimed-file F] [--head REF]", file=sys.stderr)
50
+ if msg:
51
+ print(" " + msg, file=sys.stderr)
52
+ return 2
53
+
54
+
55
+ def parse_claim(entries, origin):
56
+ """→ (set of paths, error or None). Nothing is normalised: an ambiguous entry is an error, not a guess."""
57
+ seen = []
58
+ for e in entries:
59
+ if e == "":
60
+ return None, "empty entry in %s (a trailing or doubled separator?)" % origin
61
+ if e != e.strip():
62
+ return None, "entry with leading/trailing space in %s: %r — say exactly which path" % (origin, e)
63
+ if e in seen:
64
+ return None, "duplicate entry in %s: %r" % (origin, e)
65
+ seen.append(e)
66
+ return set(seen), None
67
+
68
+
69
+ def main(argv):
70
+ if len(argv) < 2:
71
+ return usage("")
72
+ repo, base, rest = argv[0], argv[1], argv[2:]
73
+ head_ref, claim, have_claim = "HEAD", set(), False
74
+ i = 0
75
+ while i < len(rest):
76
+ a = rest[i]
77
+ if a in ("--claimed", "--claimed-file", "--head") and i + 1 >= len(rest):
78
+ return usage("%s needs a value" % a)
79
+ if a == "--head":
80
+ head_ref = rest[i + 1]
81
+ elif a == "--claimed":
82
+ got, err = parse_claim(rest[i + 1].split(","), "--claimed")
83
+ if err:
84
+ return usage(err)
85
+ if claim & got:
86
+ return usage("duplicate entry across claim options: %r" % sorted(claim & got)[0])
87
+ claim |= got; have_claim = True
88
+ elif a == "--claimed-file":
89
+ try:
90
+ raw = open(rest[i + 1], "rb").read().decode("utf-8")
91
+ except (OSError, UnicodeDecodeError) as exc:
92
+ return usage("cannot read --claimed-file: %s" % exc)
93
+ parts = raw.split("\0") if "\0" in raw else raw.split("\n")
94
+ if parts and parts[-1] == "":
95
+ parts.pop() # ONE final terminator is normal; a second one is an empty entry
96
+ got, err = parse_claim(parts, "--claimed-file")
97
+ if err:
98
+ return usage(err)
99
+ if claim & got:
100
+ return usage("duplicate entry across claim options: %r" % sorted(claim & got)[0])
101
+ claim |= got; have_claim = True
102
+ else:
103
+ return usage("unknown argument %r" % a)
104
+ i += 2
105
+ if not os.path.isdir(repo):
106
+ print("HARNESS-ERROR: not a directory: %s" % repo, file=sys.stderr); return 10
107
+ try:
108
+ repo = git(repo, "rev-parse", "--show-toplevel").decode().strip() # codex R3: a subdirectory must not narrow the diff
109
+ head = git(repo, "rev-parse", "--verify", "--quiet", head_ref + "^{commit}").decode().strip()
110
+ base_sha = git(repo, "rev-parse", "--verify", "--quiet", base + "^{commit}").decode().strip()
111
+ r = subprocess.run(["git", "-C", repo, "merge-base", "--is-ancestor", base_sha, head], capture_output=True, env=ENV)
112
+ if r.returncode == 1:
113
+ raise HarnessError("base %s is not an ancestor of head %s — the receipt would mix unrelated history" % (base_sha[:12], head[:12]))
114
+ if r.returncode != 0:
115
+ raise HarnessError("merge-base failed (rc=%d)" % r.returncode)
116
+ b = subprocess.run(["git", "-C", repo, "symbolic-ref", "--quiet", "--short", "HEAD"], capture_output=True, env=ENV)
117
+ branch = b.stdout.decode().strip() if b.returncode == 0 else "(detached)"
118
+ commits = int(git(repo, "rev-list", "--count", "%s..%s" % (base_sha, head)).decode().strip())
119
+ paths = [p.decode("utf-8", "surrogateescape") for p in
120
+ git(repo, "diff", "--name-only", "-z", "--no-renames", "--ignore-submodules=none", base_sha, head).split(b"\0") if p]
121
+ lines = []
122
+ for p in paths:
123
+ t = git(repo, "ls-tree", "-z", head, "--", p).split(b"\0")[0]
124
+ if not t:
125
+ prev = git(repo, "ls-tree", "-z", base_sha, "--", p).split(b"\0")[0]
126
+ if not prev:
127
+ raise HarnessError("path %r is in the diff but in neither tree" % p)
128
+ lines.append(("deleted", p)); continue
129
+ meta, _, _name = t.partition(b"\t")
130
+ mode, typ, obj = meta.decode().split(" ")
131
+ if typ == "commit":
132
+ lines.append(("submodule " + obj[:12], p)); continue
133
+ if typ != "blob":
134
+ raise HarnessError("unexpected object type %s for %r" % (typ, p))
135
+ data = git(repo, "cat-file", "blob", obj)
136
+ tag = hashlib.sha256(data).hexdigest()[:16]
137
+ lines.append((("symlink " if mode == "120000" else "") + tag, p))
138
+ st = git(repo, "status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none").split(b"\0")
139
+ # assume-unchanged (h) / skip-worktree (S) entries are invisible to status — count them, they make «committed» unprovable
140
+ hidden = sum(1 for e in git(repo, "ls-files", "-v", "-z").split(b"\0") if e[:1] in (b"h", b"S", b"s"))
141
+ dirty = untracked = 0
142
+ skip = False
143
+ for e in st:
144
+ if skip:
145
+ skip = False; continue
146
+ if not e:
147
+ continue
148
+ code = e[:2]
149
+ if code == b"??":
150
+ untracked += 1
151
+ else:
152
+ dirty += 1
153
+ if code[:1] in (b"R", b"C"):
154
+ skip = True # rename/copy entries carry the source path as the next field
155
+ except HarnessError as exc:
156
+ print("HARNESS-ERROR: %s" % exc, file=sys.stderr); return 10
157
+ print("receipt repo=%s" % repo)
158
+ print(" head=%s branch=%s base=%s" % (head, branch, base_sha))
159
+ print(" commits=%d paths=%d" % (commits, len(paths)))
160
+ print(" uncommitted(tracked)=%d untracked=%d hidden-from-status=%d" % (dirty, untracked, hidden))
161
+ for tag, p in lines:
162
+ print(" path %-18s %s" % (tag, p))
163
+ rc = 0
164
+ if dirty:
165
+ print("NOT-COMMITTED: %d tracked path(s) changed but not committed — the receipt covers commits only" % dirty); rc = 1
166
+ if hidden:
167
+ print("UNPROVABLE-CLEAN: %d path(s) marked assume-unchanged/skip-worktree — status cannot show their edits" % hidden); rc = 1
168
+ if have_claim:
169
+ actual = set(paths)
170
+ missing, extra = sorted(claim - actual), sorted(actual - claim)
171
+ if missing:
172
+ print("CLAIMED-NOT-CHANGED:"); [print(" " + p) for p in missing]; rc = 1
173
+ if extra:
174
+ print("CHANGED-NOT-CLAIMED:"); [print(" " + p) for p in extra]; rc = 1
175
+ if not missing and not extra:
176
+ print("CLAIMED-MATCHES: %d path(s)" % len(claim))
177
+ return rc
178
+
179
+
180
+ if __name__ == "__main__":
181
+ try:
182
+ sys.exit(main(sys.argv[1:]))
183
+ except Exception as exc: # an instrument crash is never a pass
184
+ print("HARNESS-ERROR: %s: %s" % (type(exc).__name__, exc), file=sys.stderr)
185
+ sys.exit(10)
@@ -17,7 +17,7 @@
17
17
  🟥 구조 술어만 쓴다 — FH 고유 어휘(마커·4축·영혼)를 넣지 않는다. 그래야 남의 레포에도 돈다.
18
18
  """
19
19
  from __future__ import annotations
20
- import os, re, sys, json, argparse
20
+ import os, re, sys, json, argparse, subprocess
21
21
  from typing import Dict, List, Tuple
22
22
 
23
23
  DOC_EXT = {".md"}
@@ -56,14 +56,53 @@ def _inside(root: str, path: str) -> bool:
56
56
  return c == r or c.startswith(r + os.sep)
57
57
 
58
58
 
59
+ _TRACKED_CACHE: dict = {}
60
+ _INVENTORY_FAILED = "INVENTORY-FAILED"
61
+
62
+
63
+ def _tracked(root: str):
64
+ """git 저장소면 추적된 파일의 실경로 집합(frozenset), git 밖이면 None, git 인데 목록을 못 얻으면 _INVENTORY_FAILED.
65
+ 🟥 2026-10-20: 이름 대체 찾기가 os.walk 로 트리 «전체» 를 훑어서, 저자 머신의 미추적 실험 폴더(tracks/_meta/claude200 안 복제본
66
+ 10개)가 known-pair 대상의 이름을 겹치게 만들었다 → 보정이 «대상이 실재하지 않는다» 로 거짓 실패(깨끗한 복제본은 통과).
67
+ 반대로 미추적 파일 하나가 사라진 대상을 «있다» 로 만들 수도 있다(되돌림 레인 L9 B 에서 실측).
68
+ 🟥 codex 1라운드: git 이 실패하면 «git 밖» 으로 떨어져 옛 동작이 돌아오면 안 된다 — «git 밖» 은 rev-parse 가 그렇다고 말할 때만,
69
+ 그 밖의 실패는 _INVENTORY_FAILED(resolve 가 아무것도 못 찾는 닫힌 쪽). 서브모듈 안 파일도 포함(--recurse-submodules),
70
+ 충돌 단계 중복은 한 번만(--deduplicate), 실경로 집합은 루트마다 한 번만 계산."""
71
+ if root in _TRACKED_CACHE:
72
+ return _TRACKED_CACHE[root]
73
+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
74
+ out = _INVENTORY_FAILED
75
+ try:
76
+ top = subprocess.run(["git", "-C", root, "rev-parse", "--show-toplevel"], capture_output=True, env=env, timeout=10)
77
+ if top.returncode != 0:
78
+ msg = top.stderr.decode("utf-8", "replace").lower()
79
+ out = None if "not a git repository" in msg else _INVENTORY_FAILED
80
+ else:
81
+ t = top.stdout.decode("utf-8", "surrogateescape").strip()
82
+ r = subprocess.run(["git", "-C", t, "-c", "core.fsmonitor=false", "ls-files", "-z", "--full-name",
83
+ "--recurse-submodules", "--deduplicate"], capture_output=True, env=env, timeout=30)
84
+ if r.returncode == 0:
85
+ out = frozenset(os.path.realpath(os.path.join(t, x.decode("utf-8", "surrogateescape")))
86
+ for x in r.stdout.split(b"\0") if x)
87
+ except (OSError, subprocess.SubprocessError):
88
+ out = _INVENTORY_FAILED
89
+ _TRACKED_CACHE[root] = out
90
+ return out
91
+
92
+
59
93
  def resolve(root: str, p: str) -> str | None:
60
94
  # `..` 를 담은 참조는 «해석하기 전에» 거절한다 — 해석 후 판정은 심링크 한 겹에 뚫린다.
61
95
  cand = os.path.join(root, p)
62
- if os.path.isfile(cand) and not os.path.islink(cand) and _inside(root, cand):
96
+ tracked = _tracked(root)
97
+ if tracked == _INVENTORY_FAILED:
98
+ return None # git 인데 목록을 못 얻었다 — 못 찾은 것으로(닫힌 쪽), 옛 전체 훑기로 안 떨어진다
99
+ if os.path.isfile(cand) and not os.path.islink(cand) and _inside(root, cand) \
100
+ and (tracked is None or os.path.realpath(cand) in tracked):
63
101
  return cand
64
102
  base = os.path.basename(p)
65
- hits = [f for f in walk(root)
66
- if os.path.basename(f) == base and not os.path.islink(f) and _inside(root, f)]
103
+ pool = sorted(tracked) if tracked is not None else walk(root) # git 이면 추적 파일만, 아니면 종전처럼 트리 전체
104
+ hits = [f for f in pool
105
+ if os.path.basename(f) == base and os.path.isfile(f) and not os.path.islink(f) and _inside(root, f)]
67
106
  return hits[0] if len(hits) == 1 else None
68
107
 
69
108
  # 실행 증거: 인터프리터 뒤 또는 명령 위치. 주석줄과 grep 패턴 안은 제외.
@@ -30,6 +30,37 @@
30
30
  # FH_RECORD_BASE=<p> directory for governance_log YAML (default: FH_ROOT/tracks/_meta)
31
31
 
32
32
  set -euo pipefail
33
+ # Unexpected failure → HARNESS_ERROR (10), never PENDING (1). Under `set -e` a command that fails where
34
+ # nobody expected it ends the script with that command's status — usually 1, which the contract reads as
35
+ # PENDING ("proceed with awareness"). MEASURED 2026-10-20: `TMPDIR=/nonexistent` made `mktemp` fail and
36
+ # the gate exited 1 (also through bin/fh-gate.js). Every intended outcome leaves through an explicit
37
+ # `exit N`, which does not fire ERR. A failing `X=$(cmd)` at top level still fires it.
38
+ # 🟥 NOT `set -E`: errtrace carries the trap INTO command substitutions, where it ignores the caller's
39
+ # `|| rc=$?`. Measured on the first draft: the cross-mode leg capture `_legout=$(…) || _legrc=$?` got
40
+ # 10 instead of the leg's 2, and one lane folded a BLOCKED leg into a PASS union. The regression suite
41
+ # (`cross: one leg BLOCKED → union BLOCKED`) is the anchor for this line.
42
+ # 10 is written as a literal because EXIT_HARNESS_ERROR is defined further down.
43
+ trap 'echo "ERROR: fh-gate: unexpected failure at line $LINENO (status $?) — failing closed as HARNESS_ERROR." >&2 || :; exit 10' ERR
44
+ # The ERR trap does not see every unexpected end: an unbound variable under `set -u` exits 1 without
45
+ # firing ERR, and so does a failure inside a function called from the EXIT trap (cross-family review,
46
+ # 2026-10-20 — `cleanup(){ false; }; trap cleanup EXIT; exit 2` returned 1). So the exit itself is the
47
+ # second check: a status of 0-3 is a verdict, and a verdict may only leave through a line that set
48
+ # _FH_VERDICT_EXIT=1 first (--version, --help, the cross union, the final verdict). Anything else that
49
+ # ends with 0-3 is reported as HARNESS_ERROR. Cleanup runs here too, and its own failure cannot change
50
+ # the status. Every message on these paths is `|| :` — with stderr closed a failing echo would otherwise
51
+ # end the handler before its `exit 10` (cross-family review round 2: `--invalid 2>&-` returned 1).
52
+ _FH_VERDICT_EXIT=0
53
+ _FH_CLEANUP=0
54
+ _fh_on_exit() {
55
+ local rc=$?
56
+ if [ "$_FH_CLEANUP" = 1 ]; then cleanup 2>/dev/null || true; fi
57
+ if [ "$rc" -le 3 ] && [ "$_FH_VERDICT_EXIT" != 1 ]; then
58
+ echo "ERROR: fh-gate: ended with status $rc without reaching a verdict — failing closed as HARNESS_ERROR." >&2 || :
59
+ exit 10
60
+ fi
61
+ exit "$rc"
62
+ }
63
+ trap _fh_on_exit EXIT
33
64
 
34
65
  FH_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
35
66
  # Single source of truth: read version from the package.json shipped alongside this script.
@@ -76,7 +107,7 @@ EXIT_DRY_RUN=12
76
107
  case "${1:-}" in
77
108
  --version|-V)
78
109
  printf '%s\n' "fh-gate $VERSION"
79
- exit 0
110
+ _FH_VERDICT_EXIT=1; exit 0
80
111
  ;;
81
112
  --help|-h)
82
113
  printf '%s\n' "fh-gate $VERSION — FH governance gate"
@@ -110,7 +141,7 @@ case "${1:-}" in
110
141
  printf '%s\n' " FH_VERBOSE=1 print full backend stderr"
111
142
  printf '%s\n' ""
112
143
  printf '%s\n' " https://github.com/chrono-meta/forge-harness"
113
- exit 0
144
+ _FH_VERDICT_EXIT=1; exit 0
114
145
  ;;
115
146
  -*)
116
147
  printf '%s\n' "ERROR: unrecognized option '${1}'." >&2
@@ -153,7 +184,8 @@ esac
153
184
  # `cross` is a REQUEST, not a guarantee — a machine may have only one family installed. When a leg is
154
185
  # unavailable or errors, this degrades to the surviving leg and SAYS SO, loudly, in both the human and
155
186
  # the machine-readable output. A single-leg result that reads as if it were cross-checked is the same
156
- # class of defect as a check that did not run reading as PASS.
187
+ # class of defect as a check that did not run reading as PASS. Since 2026-10-22 the EXIT CODE says so too:
188
+ # a single-leg PASS/PENDING leaves as ESCALATE (3) unless FH_GATE_CROSS_ALLOW_SINGLE=1 (see below).
157
189
  #
158
190
  # COST: cross is ~2x. It is deliberately NOT a default — [[feedback_decorrelation_not_fanout_cost_boundary]]
159
191
  # says match the parallelisation axis to the failure mode rather than multiply. Callers should request
@@ -171,6 +203,15 @@ if [[ "$FH_BACKEND" == "cross" ]]; then
171
203
  # without letting it abort. Verified against a BLOCKED leg, not assumed.
172
204
  _legrc=0
173
205
  _legout=$(FH_BACKEND="$_leg" "$0" "$@" 2>/dev/null) || _legrc=$?
206
+ # 11 (argument error) and 12 (dry-run) are not a leg failing — every leg gets the same arguments, so
207
+ # every leg would say the same. Pass them through instead of folding them into "harness error 10"
208
+ # (found 2026-10-20 by a local-model self-audit candidate, reproduced: cross + bad level → 10, not 11;
209
+ # cross + FH_DRY_RUN=1 → 10 and the prompt was lost). A dry-run leg's stdout IS the prompt — print it.
210
+ if [ "$_legrc" -eq "$EXIT_ARG_ERROR" ] || [ "$_legrc" -eq "$EXIT_DRY_RUN" ]; then
211
+ [ "$_legrc" -eq "$EXIT_DRY_RUN" ] && printf '%s\n' "$_legout"
212
+ echo "→ fh-gate: cross mode — leg $_leg exited $_legrc (same arguments for every leg); passing it through" >&2 || :
213
+ exit "$_legrc"
214
+ fi
174
215
  if [ "$_legrc" -ge 10 ]; then
175
216
  _CROSS_ERR="${_CROSS_ERR}${_CROSS_ERR:+, }$_leg (harness error $_legrc)"; continue
176
217
  fi
@@ -189,22 +230,40 @@ $(printf '%s' "$_legout" | sed -n '/^---$/,$p')"
189
230
  exit $EXIT_HARNESS_ERROR
190
231
  fi
191
232
 
233
+ # 🟥 A single-leg PASS/PENDING used to leave with 0/1 — the codes a two-family run gives — so a caller reading
234
+ # only the exit code could not tell «cross-checked» from «one family alone» (2026-10-22, LLM call-site inventory).
235
+ # Cross was requested and could not be provided: that goes to a person (ESCALATE), unless the caller says
236
+ # exactly FH_GATE_CROSS_ALLOW_SINGLE=1, which is echoed into the output. BLOCKED/ESCALATE already stop.
237
+ _CROSS_FINAL="$_CROSS_WORST"; _CROSS_OVERRIDE=""
238
+ if [ "$_CROSS_RAN" -lt 2 ] && [ "$(_sev_rank "$_CROSS_WORST")" -lt "$(_sev_rank ESCALATE)" ]; then
239
+ if [ "${FH_GATE_CROSS_ALLOW_SINGLE:-}" = "1" ]; then
240
+ _CROSS_OVERRIDE=1
241
+ else
242
+ _CROSS_FINAL="ESCALATE"
243
+ fi
244
+ fi
192
245
  printf 'FH_STATUS: SUCCESS\n'
193
- printf 'FH_GATE_VERDICT: %s\n' "$_CROSS_WORST"
246
+ printf 'FH_GATE_VERDICT: %s\n' "$_CROSS_FINAL"
194
247
  printf 'FH_GATE_MODE: cross\n'
195
248
  printf 'FH_GATE_LEGS: %s\n' "$_CROSS_LEGS"
196
249
  if [ "$_CROSS_RAN" -lt 2 ]; then
197
250
  # Degraded, and it must be impossible to mistake this for a two-family result.
198
251
  printf 'FH_GATE_DECORRELATED: no\n'
199
252
  printf 'FH_GATE_DEGRADED: %s\n' "$_CROSS_ERR"
253
+ if [ "$_CROSS_FINAL" != "$_CROSS_WORST" ]; then
254
+ printf 'FH_GATE_ESCALATE_REASON: cross-degraded (single leg %s said %s; set FH_GATE_CROSS_ALLOW_SINGLE=1 to accept one family)\n' "$_CROSS_LEGS" "$_CROSS_WORST"
255
+ elif [ -n "$_CROSS_OVERRIDE" ]; then
256
+ printf 'FH_GATE_CROSS_OVERRIDE: FH_GATE_CROSS_ALLOW_SINGLE=1 (single leg %s accepted as %s)\n' "$_CROSS_LEGS" "$_CROSS_WORST"
257
+ fi
200
258
  echo "WARN: FH_BACKEND=cross ran a SINGLE leg ($_CROSS_LEGS) — $_CROSS_ERR." >&2
201
259
  echo " This verdict is NOT decorrelated. Treat it as $_CROSS_LEGS alone." >&2
202
260
  else
203
261
  printf 'FH_GATE_DECORRELATED: yes\n'
204
262
  fi
205
263
  printf '%s\n' "$_CROSS_OUT"
206
- echo "→ fh-gate: cross mode — legs [$_CROSS_LEGS], union verdict $_CROSS_WORST" >&2
207
- case "$_CROSS_WORST" in
264
+ echo "→ fh-gate: cross mode — legs [$_CROSS_LEGS], union verdict $_CROSS_WORST, final $_CROSS_FINAL" >&2 || :
265
+ _FH_VERDICT_EXIT=1
266
+ case "$_CROSS_FINAL" in
208
267
  PASS) exit $EXIT_PASS ;;
209
268
  PENDING) exit $EXIT_PENDING ;;
210
269
  BLOCKED) exit $EXIT_BLOCKED ;;
@@ -436,7 +495,7 @@ else
436
495
  fi
437
496
 
438
497
  cleanup() { rm -f "$PROMPT_FILE" "$OUTPUT_FILE" "$ERR_FILE" "$PARSE_FILE" "$SCHEMA_FILE" "$CODEX_LAST"; }
439
- trap cleanup EXIT
498
+ _FH_CLEANUP=1 # _fh_on_exit (top of file) calls cleanup from here on
440
499
 
441
500
  # --- Build prompt ---
442
501
  cat > "$PROMPT_FILE" <<PROMPT
@@ -764,11 +823,12 @@ FINDINGS_N_LOG=$(grep -m 1 "^FH_FINDINGS_COUNT:" "$PARSE_FILE" 2>/dev/null | awk
764
823
  } >> "$RECORD_PATH" || echo "WARN: governance log write failed: $RECORD_PATH" >&2
765
824
 
766
825
  # Exit code
826
+ _FH_VERDICT_EXIT=1
767
827
  case "$VERDICT" in
768
- PASS) echo "→ verdict: PASS" >&2; exit $EXIT_PASS ;;
769
- PENDING) echo "→ verdict: PENDING" >&2; exit $EXIT_PENDING ;;
770
- BLOCKED) echo "→ verdict: BLOCKED" >&2; exit $EXIT_BLOCKED ;;
771
- ESCALATE) echo "→ verdict: ESCALATE" >&2; exit $EXIT_ESCALATE ;;
828
+ PASS) echo "→ verdict: PASS" >&2 || :; exit $EXIT_PASS ;;
829
+ PENDING) echo "→ verdict: PENDING" >&2 || :; exit $EXIT_PENDING ;;
830
+ BLOCKED) echo "→ verdict: BLOCKED" >&2 || :; exit $EXIT_BLOCKED ;;
831
+ ESCALATE) echo "→ verdict: ESCALATE" >&2 || :; exit $EXIT_ESCALATE ;;
772
832
  *)
773
833
  echo "ERROR: unrecognized verdict '${VERDICT:-EMPTY}' — harness error, failing safe (commit not allowed)" >&2
774
834
  exit $EXIT_HARNESS_ERROR
@@ -142,7 +142,7 @@ with open(sys.argv[2], "w", encoding="utf-8") as w:
142
142
  eval "$cmd" < "$pf" > "$raw" 2>"$out/err2_${fam}_${role}.txt"
143
143
  local rc=$?
144
144
  FAM="$fam" ROLE="$role" RC="$rc" /usr/bin/python3 - "$raw" "$out/part2_${fam}_${role}.jsonl" "$out/findings_r1.jsonl" <<'PYR2'
145
- import json, os, sys
145
+ import json, os, re, sys
146
146
  own_r1 = {} # own round-1 id -> its trusted member_id alias (or None)
147
147
  try:
148
148
  for _l in open(sys.argv[3], encoding="utf-8"):
@@ -186,9 +186,21 @@ with open(dst, "w", encoding="utf-8") as w:
186
186
  line = line.strip().lstrip("\ufeff")
187
187
  if line.startswith("DROPPED:"):
188
188
  _body = line[len("DROPPED:"):]
189
+ # 🟥 A DROPPED line withdraws ONE finding: the one its body STARTS with (id or title, the longest that
190
+ # fits, followed by a non-[A-Za-z0-9_-] char or the end). Searching the whole line used to withdraw
191
+ # every finding merely named in it — «codex-logic-10» took «codex-logic-1», title «Q10» took «Q1»,
192
+ # «… Race condition remains valid» took «Race condition» — and the silently omitted finding then
193
+ # counted as accounted for, so no fallback ran (L125–L127, 2026-10-22, codex R1). An unrecognised
194
+ # withdrawal falls back to round 1 (the safe side). ASCII boundary so «codex-logic-1은» still counts.
195
+ _head = _body.strip().lstrip("\"'`*#([ ").strip()
196
+ _best = None
189
197
  for _id, _t in own_r1_titles.items():
190
- if _id in _body or (_t and _t in _body):
191
- withdrawn_ids.add(_id)
198
+ for _ref in (_id, _t):
199
+ if _ref and _head.startswith(_ref) and not re.match(r"[A-Za-z0-9_-]", _head[len(_ref):len(_ref) + 1]):
200
+ if _best is None or len(_ref) > len(_best[1]):
201
+ _best = (_id, _ref)
202
+ if _best:
203
+ withdrawn_ids.add(_best[0])
192
204
  # 🟥 saw_bytes 를 여기서 «올리지 않는다». DROPPED 는 2차 계약이 요구한 출력이므로
193
205
  # 「계약 밖 응답」의 증거가 될 수 없다 (cross-family #5, codex 2026-09-10).
194
206
  # 🟥 "DROPPED: none" 은 삭제가 아니다. 세면 «숨은 수확 손실» 계측이 그 자리에서 거짓이 된다.
@@ -138,31 +138,38 @@ if command -v git >/dev/null 2>&1 && [ -d "$HUB_ROOT/.git" ] || { command -v
138
138
  if git -C "$HUB_ROOT" rev-parse --git-dir >/dev/null 2>&1; then _TRACKED_OK=1; fi
139
139
  fi
140
140
 
141
+ _TRACKED_NL=$'\n'"$_TRACKED"$'\n'
141
142
  _SESS=0
142
143
  _SESS_NAMES=""
143
144
  _is_shipped() { # $1 = path relative to HUB_ROOT
144
145
  [ "$_TRACKED_OK" = "1" ] || return 1
145
- # 🟥 here-string, NOT a pipe. Under `set -o pipefail` a matching `grep -qxF` exits before
146
- # reading its input, the producer dies of SIGPIPE, and pipefail raises that 141 as the
147
- # pipeline's status — so **a match is read as a non-match**. `$_TRACKED` is `git ls-files`
148
- # output, which grows with the hub, so there is no structural bound to hide behind: the
149
- # scanner's own measurements put the onset near ~16 KB (`pipefail_earlyexit_scan.sh` header),
150
- # ≈300 tracked paths under tracks/. Reproduced deterministically at 6,000 paths
151
- # (2026-09-28): pipe form → rc=141 “NO-MATCH”, here-string → MATCH.
152
- # 🟥 And the direction is the one this function exists to prevent: a shipped file read as
153
- # user-made makes a **fresh clone** answer `returning`, the onboarding FP CLAUDE.md names.
154
- # Lane: test_mapped_tracks_lanes.sh §L-pipe.
155
- grep -qxF "$1" <<<"$_TRACKED"
146
+ # 🟥 In-process literal match (no pipe, no per-file fork).
147
+ # · Why NOT a pipe: under `set -o pipefail` a matching `grep -qxF` exits before reading its
148
+ # input, the producer dies of SIGPIPE, and pipefail raises that 141 as the pipeline's
149
+ # status — so **a match is read as a non-match**. `$_TRACKED` is `git ls-files` output,
150
+ # which grows with the hub, so there is no structural bound to hide behind: the scanner's
151
+ # own measurements put the onset near ~16 KB (`pipefail_earlyexit_scan.sh` header), ≈300
152
+ # tracked paths under tracks/. Reproduced deterministically at 6,000 paths (2026-09-28):
153
+ # pipe form → rc=141 “NO-MATCH”, here-string → MATCH.
154
+ # · And the direction is the one this function exists to prevent: a shipped file read as
155
+ # user-made makes a **fresh clone** answer `returning`, the onboarding FP CLAUDE.md names.
156
+ # Lane: test_mapped_tracks_lanes.sh §L-pipe.
157
+ # · Why NOT `grep -qxF "$1" <<<"$_TRACKED"`: the here-string avoids SIGPIPE, but forks a
158
+ # process per file across tracks/*/session_*.md and tracks/_meta/*.md (≈1,300–1,800 files,
159
+ # measured ≈6–12 s on macOS). Precomputing `$_TRACKED_NL` once and matching via `case`
160
+ # keeps it in-shell; quoting `"$1"` forces glob characters (`[`, `]`, `*`, `?`) in a path
161
+ # to match literally rather than as patterns (Lane §L-glob).
162
+ case "$_TRACKED_NL" in *$'\n'"$1"$'\n'*) return 0;; *) return 1;; esac
156
163
  }
157
164
  for _f in "$HUB_ROOT"/tracks/*/session_*.md "$HUB_ROOT"/tracks/_meta/*.md; do
158
165
  [ -f "$_f" ] || continue
159
166
  _rel="tracks/${_f#"$HUB_ROOT"/tracks/}"
160
- case "$(basename "$_f")" in .gitkeep) continue ;; esac
167
+ case "${_f##*/}" in .gitkeep) continue ;; esac
161
168
  _is_shipped "$_rel" && continue
162
169
  _SESS=$((_SESS + 1))
163
170
  # Cap the sample. The COUNT is the answer; the names are a debugging aid, and an operator hub
164
171
  # has hundreds — dumping them turns a one-line verdict into a screenful nobody reads.
165
- [ "$_SESS" -le 3 ] && _SESS_NAMES="$_SESS_NAMES $(basename "$_f")"
172
+ [ "$_SESS" -le 3 ] && _SESS_NAMES="$_SESS_NAMES ${_f##*/}"
166
173
  done
167
174
 
168
175
  if [ "$_TRACKED_OK" = "1" ]; then