@chrono-meta/fh-gate 3.44.0 → 3.46.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 (101) hide show
  1. package/.claude/rules/fh_4axis_gate.md +50 -608
  2. package/.claude-plugin/marketplace.json +4 -4
  3. package/CATALOG.md +21 -0
  4. package/CHEATSHEET.md +13 -3
  5. package/docs/codex-compat.md +1 -1
  6. package/knowledge/shared/harness-core/fh_4axis_gate_detail.md +679 -0
  7. package/knowledge/shared/harness-core/fh_detail_protocols.md +1 -0
  8. package/knowledge/shared/harness-core/fh_integration_contract.md +1 -1
  9. package/knowledge/shared/harness-core/fh_module_contract.md +106 -3
  10. package/knowledge/shared/harness-core/heavy_skill_to_cartridge.md +185 -0
  11. package/knowledge/shared/learnings/subagent_invocations_log.yaml +209 -0
  12. package/package.json +19 -1
  13. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  14. package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +9 -8
  15. package/plugins/fh-commons/skills/ko-tech-writer/SKILL_detail.md +20 -0
  16. package/plugins/fh-commons/skills/mcp-circuit-breaker/SKILL.md +12 -6
  17. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  18. package/plugins/fh-meta/CHANGELOG.md +122 -0
  19. package/plugins/fh-meta/skills/auto-decorrelation/SKILL.md +13 -0
  20. package/plugins/fh-meta/skills/context-doctor/SKILL.md +1 -0
  21. package/plugins/fh-meta/skills/deep-clarify/SKILL.md +76 -22
  22. package/plugins/fh-meta/skills/harvest-loop/SKILL.md +2 -2
  23. package/plugins/fh-meta/skills/install-wizard/SKILL_detail.md +4 -0
  24. package/plugins/fh-meta/skills/memory-hygiene/SKILL.md +6 -0
  25. package/plugins/fh-meta/skills/steel-quench/SKILL_detail.md +2 -1
  26. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  27. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  28. package/scripts/agy_launch_guard.sh +117 -1
  29. package/scripts/below_floor_scan.sh +30 -0
  30. package/scripts/codex_launch_guard.sh +38 -2
  31. package/scripts/correction_moments.py +23 -2
  32. package/scripts/fh-gate.sh +612 -14
  33. package/scripts/fh-goal.sh +56 -12
  34. package/scripts/fh-run.sh +1 -1
  35. package/scripts/fh_gate_exec.sh +272 -0
  36. package/scripts/fh_session_load.sh +17 -0
  37. package/scripts/finding_fleet.sh +2 -1
  38. package/scripts/finding_verifier.sh +2 -1
  39. package/scripts/fixtures/heavy_skill_smell/clean/tidy-notes/README.md +16 -0
  40. package/scripts/fixtures/heavy_skill_smell/clean/tidy-notes/scripts/check_refs.py +12 -0
  41. package/scripts/fixtures/heavy_skill_smell/clean/tidy-notes/scripts/test_check_refs.py +24 -0
  42. package/scripts/fixtures/heavy_skill_smell/clean/tidy-notes/skills/tidy-notes/SKILL.md +16 -0
  43. package/scripts/fixtures/heavy_skill_smell/clean/tidy-notes/skills/tidy-notes/fh-module.yaml +20 -0
  44. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/SKILL.md +25 -0
  45. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/hooks/hooks.json +7 -0
  46. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/scripts/check_links.py +25 -0
  47. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/scripts/publish.sh +9 -0
  48. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/scripts/publish_guard.py +6 -0
  49. package/scripts/fixtures/heavy_skill_smell/heavy/docs-publisher-pro/scripts/setup.sh +5 -0
  50. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/SKILL.md +25 -0
  51. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/hooks/hooks.json +10 -0
  52. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/scripts/check_refs.py +12 -0
  53. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/scripts/guard_push.py +9 -0
  54. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/scripts/install.sh +6 -0
  55. package/scripts/fixtures/heavy_skill_smell/heavy/release-notes-pro/scripts/ship.sh +9 -0
  56. package/scripts/heavy_skill_smell.py +311 -0
  57. package/scripts/job_heartbeat.py +186 -0
  58. package/scripts/live_eval_matrix.py +128 -0
  59. package/scripts/live_eval_trace.py +197 -4
  60. package/scripts/package_coverage_check.sh +18 -0
  61. package/scripts/pr_merge_verified.sh +14 -4
  62. package/scripts/prepush_guard_check.sh +8 -0
  63. package/scripts/probe_live_eval.sh +32 -0
  64. package/scripts/probe_live_eval_lib.py +8 -2
  65. package/scripts/selfcheck.sh +113 -0
  66. package/scripts/selfcheck_shard_weights.txt +2 -0
  67. package/scripts/sidecar_calibrate.sh +7 -5
  68. package/scripts/sim_isolated_run.sh +20 -0
  69. package/scripts/test_agy_launch_guard_lanes.sh +120 -0
  70. package/scripts/test_below_floor_scan_lanes.sh +85 -0
  71. package/scripts/test_codex_launch_guard_lanes.sh +45 -0
  72. package/scripts/test_correction_moments_lanes.sh +37 -0
  73. package/scripts/test_deep_clarify_interview_lanes.sh +108 -0
  74. package/scripts/test_deep_clarify_spec_path_lanes.sh +91 -0
  75. package/scripts/test_fh_gate_absorb_lanes.sh +255 -0
  76. package/scripts/test_fh_gate_defaults_lanes.sh +188 -0
  77. package/scripts/test_fh_gate_exec_lanes.sh +244 -0
  78. package/scripts/test_fh_gate_fusion_lanes.sh +202 -0
  79. package/scripts/test_fh_gate_regressions.sh +92 -1
  80. package/scripts/test_fh_goal_change_detection_lanes.sh +103 -3
  81. package/scripts/test_finding_pipeline_lanes.sh +35 -1
  82. package/scripts/test_guard_anchor_override_env_lanes.sh +84 -0
  83. package/scripts/test_heavy_skill_smell_lanes.sh +160 -0
  84. package/scripts/test_job_heartbeat_lanes.sh +96 -0
  85. package/scripts/test_live_eval_construct_lanes.sh +29 -6
  86. package/scripts/test_live_eval_matrix_lanes.sh +53 -0
  87. package/scripts/test_live_eval_trace_lanes.sh +132 -5
  88. package/scripts/test_name_boundary_locale_lanes.sh +36 -5
  89. package/scripts/test_pr_merge_verified_lanes.sh +15 -2
  90. package/scripts/test_prepush_marker_lookup_lanes.sh +143 -0
  91. package/scripts/test_probe_live_eval_lanes.sh +44 -0
  92. package/scripts/test_regression_guard_sibling_lanes.sh +52 -1
  93. package/scripts/test_sidecar_calibrate_lanes.sh +1 -1
  94. package/scripts/test_sim_isolated_run_lanes.sh +43 -0
  95. package/scripts/universal_guard_check.sh +8 -0
  96. package/scripts/worktree_reclaim.sh +1 -1
  97. package/templates/.claude/rules/mcp_tool_gating.md +27 -0
  98. package/templates/.git-hooks/pre-push +60 -3
  99. package/templates/PRE-PUBLISH-CHECKLIST.md +22 -0
  100. package/templates/regression_guard.sh +8 -4
  101. package/templates/settings.LaneGap.snippet.json +27 -0
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env python3
2
+ """live_eval_matrix.py — per-probe verdicts across every nightly live-eval report, read once.
3
+
4
+ Why (frontier digest 2026-11-12, arXiv:2611.13709): a pooled pass rate such as 0.8 can hide a
5
+ probe that has never passed. probe_live_eval.sh already compares each report with the one before it
6
+ (`moved since previous`). It does not show the whole history: which probes always pass, which never
7
+ did, and which flip back and forth. This reads every live_eval_<YYYY-MM-DD>.md in a folder and
8
+ prints a probe × date matrix plus four lists:
9
+ always-pass — every scored report says PASS (scored = PASS or FAIL)
10
+ never-pass — every scored report says FAIL
11
+ mixed — both PASS and FAIL appear
12
+ too-few — fewer than 2 scored reports, so no bin applies (an absence is not a bin)
13
+
14
+ Record only. It prints record properties (counts and lists) and no verdict. No threshold, and the
15
+ exit code ignores the bins. Whether a never-pass probe means a dead rule or a broken probe is a
16
+ human judgment. UNCALIBRATED, FAILED-TO-RUN and rows whose verdict is outside the enum are counted in their own columns and are never
17
+ counted as FAIL. A probe that did not run did not fail.
18
+
19
+ Parsing reuses probe_live_eval_lib.parse_prev_report (single source for the run-table shape).
20
+
21
+ Usage:
22
+ live_eval_matrix.py [--dir <folder>] # default <repo>/tracks/_meta (the reports are gitignored)
23
+ exit: 0 printed · 10 input error (folder missing)
24
+ """
25
+ import glob
26
+ import os
27
+ import re
28
+ import sys
29
+
30
+ HERE = os.path.dirname(os.path.abspath(__file__))
31
+ sys.path.insert(0, HERE)
32
+ import probe_live_eval_lib as L # noqa: E402
33
+
34
+ NAME = re.compile(r"^live_eval_(\d{4}-\d{2}-\d{2})\.md$")
35
+ OUT_OF_ENUM = "OUT-OF-ENUM" # row present, verdict cell outside the run-table enum (not scored, not absent)
36
+ SHORT = {L.PASS: "P", L.FAIL: "F", L.UNCALIBRATED: "U", L.FAILED_TO_RUN: "R", "UNKNOWN-ID": "?", OUT_OF_ENUM: "N"}
37
+
38
+
39
+ def collect(folder):
40
+ """-> (dates, {date: {id: verdict}}, unreadable[names]). Files are matched by exact name only;
41
+ stratify/RESULT files and other suffixes are not run tables of this shape and are skipped."""
42
+ reports, unreadable = {}, []
43
+ for p in sorted(glob.glob(os.path.join(folder, "live_eval_*.md"))):
44
+ m = NAME.match(os.path.basename(p))
45
+ if not m:
46
+ continue
47
+ rows = L.parse_prev_report(p)
48
+ if rows is None:
49
+ unreadable.append(os.path.basename(p))
50
+ else:
51
+ reports[m.group(1)] = rows
52
+ # parse_prev_report keeps only enum verdicts. A known probe row whose verdict cell is outside the
53
+ # enum (measured 2026-11-13: «NOT-LIVE-MEASURABLE (…)» in 60+ real reports) would otherwise print
54
+ # as absent, which claims the probe was not in that report when it was there but not scored.
55
+ ids = {i for r in reports.values() for i in r}
56
+ for d, rows in reports.items():
57
+ text = L._read_text(os.path.join(folder, "live_eval_%s.md" % d)) or ""
58
+ for line in text.splitlines():
59
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
60
+ if line.startswith("|") and len(cells) >= 2 and cells[0] in ids and cells[0] not in rows:
61
+ rows[cells[0]] = OUT_OF_ENUM
62
+ return sorted(reports), reports, unreadable
63
+
64
+
65
+ def bins(dates, reports):
66
+ ids = sorted({i for d in dates for i in reports[d]})
67
+ out = {"always-pass": [], "never-pass": [], "mixed": [], "too-few": []}
68
+ detail = {}
69
+ for i in ids:
70
+ seq = [reports[d].get(i) for d in dates]
71
+ scored = [v for v in seq if v in (L.PASS, L.FAIL)]
72
+ p, f = scored.count(L.PASS), scored.count(L.FAIL)
73
+ other = sum(1 for v in seq if v is not None and v not in (L.PASS, L.FAIL))
74
+ absent = seq.count(None)
75
+ if len(scored) < 2:
76
+ b = "too-few"
77
+ elif f == 0:
78
+ b = "always-pass"
79
+ elif p == 0:
80
+ b = "never-pass"
81
+ else:
82
+ b = "mixed"
83
+ out[b].append(i)
84
+ detail[i] = {"seq": seq, "pass": p, "fail": f, "other": other, "absent": absent, "bin": b}
85
+ return out, detail
86
+
87
+
88
+ def render(folder, dates, reports, unreadable):
89
+ lines = ["live-eval matrix (record only — no verdict, exit code ignores bins)",
90
+ "folder: %s" % folder,
91
+ "reports read: %d%s" % (len(dates), (" (%s .. %s)" % (dates[0], dates[-1])) if dates else ""),
92
+ "reports unreadable or without a run table: %d%s" % (
93
+ len(unreadable), (" — " + ", ".join(unreadable)) if unreadable else "")]
94
+ if not dates:
95
+ lines.append("no readable report — nothing to bin (not measured, not zero)")
96
+ return "\n".join(lines)
97
+ b, detail = bins(dates, reports)
98
+ lines.append("legend: P=PASS F=FAIL U=UNCALIBRATED R=FAILED-TO-RUN ?=UNKNOWN-ID N=row present, verdict outside the enum .=absent from that report")
99
+ lines.append("")
100
+ w = max(len(i) for i in detail)
101
+ for i in sorted(detail):
102
+ d = detail[i]
103
+ cells = "".join(SHORT.get(v, "?") if v is not None else "." for v in d["seq"])
104
+ lines.append("%-*s %s pass=%d fail=%d not-scored=%d absent=%d %s" % (
105
+ w, i, cells, d["pass"], d["fail"], d["other"], d["absent"], d["bin"]))
106
+ lines.append("")
107
+ for k in ("always-pass", "never-pass", "mixed", "too-few"):
108
+ lines.append("%s: %d%s" % (k, len(b[k]), (" — " + ", ".join(b[k])) if b[k] else ""))
109
+ return "\n".join(lines)
110
+
111
+
112
+ def main(argv):
113
+ folder = os.path.join(os.path.dirname(HERE), "tracks", "_meta")
114
+ if len(argv) >= 2 and argv[0] == "--dir":
115
+ folder = argv[1]
116
+ elif argv:
117
+ sys.stderr.write("usage: live_eval_matrix.py [--dir <folder>]\n")
118
+ return 10
119
+ if not os.path.isdir(folder):
120
+ sys.stderr.write("folder not found: %s\n" % folder)
121
+ return 10
122
+ dates, reports, unreadable = collect(folder)
123
+ print(render(folder, dates, reports, unreadable))
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ sys.exit(main(sys.argv[1:]))
@@ -11,7 +11,9 @@ Two uses:
11
11
  extract <stream.jsonl> <out.txt> <tools.txt> (runner) write the final result text and the init
12
12
  tool/MCP/plugin inventory. Exit 3 on a stream that has no parseable result event — never an empty
13
13
  «the session said nothing» (same rule as sim_isolated_run.sh's turns path).
14
- library: parse_stream(path) · behave_hit(trace, spec) · inventory(trace)
14
+ profile <stream.jsonl> (runner) one record-only line: top-level tool calls in four bins + first error depth
15
+ (explore · edit · test-run · other). Exit 3 and «trace=UNREADABLE» on a stream it cannot read.
16
+ library: parse_stream(path) · behave_hit(trace, spec) · inventory(trace) · profile_bins(trace)
15
17
 
16
18
  `behave:` grammar (one per probe, value is an ERE, no colon by probes_live.yaml convention):
17
19
  read=<re> some SUCCESSFUL Read (file_path) or Grep (path) call matches — Python `re`, not POSIX
@@ -35,7 +37,8 @@ def parse_stream(path):
35
37
  lines = open(path, encoding='utf-8').read().splitlines()
36
38
  except (OSError, UnicodeDecodeError):
37
39
  return None
38
- out = {'result': None, 'tools': None, 'mcp': None, 'plugins': None, 'calls': [], 'damaged': 0, 'ok_ids': set()}
40
+ out = {'result': None, 'tools': None, 'mcp': None, 'plugins': None, 'calls': [], 'damaged': 0, 'ok_ids': set(),
41
+ 'res_ids': set(), 'err_ids': set()}
39
42
  inits = [] # plugin set of every init event, in order
40
43
  for ln in lines:
41
44
  ln = ln.strip()
@@ -74,8 +77,12 @@ def parse_stream(path):
74
77
  out['calls'].append((str(c.get('name', '')), c.get('input') or {}, c.get('id')))
75
78
  elif t == 'user':
76
79
  for c in (ev.get('message') or {}).get('content') or []:
77
- if isinstance(c, dict) and c.get('type') == 'tool_result' and not c.get('is_error'):
78
- out['ok_ids'].add(c.get('tool_use_id'))
80
+ if isinstance(c, dict) and c.get('type') == 'tool_result':
81
+ out['res_ids'].add(c.get('tool_use_id'))
82
+ if c.get('is_error'):
83
+ out['err_ids'].add(c.get('tool_use_id'))
84
+ else:
85
+ out['ok_ids'].add(c.get('tool_use_id'))
79
86
  elif t == 'result':
80
87
  if ev.get('subtype') not in (None, 'success') or ev.get('is_error'):
81
88
  out['damaged'] += 1 # an error result is not a finished session
@@ -89,6 +96,46 @@ def parse_stream(path):
89
96
  return out
90
97
 
91
98
 
99
+ def inventory_parts(trace):
100
+ """The arm's surface as three sets — the same elements `inventory` joins — so a reader can be told
101
+ WHICH ones differ. None when the init event was absent. plugins=None means UNKNOWN (no list)."""
102
+ if trace is None or trace['tools'] is None:
103
+ return None
104
+ return {'tools': set(trace['tools']), 'mcp': set(trace['mcp'] or []),
105
+ 'plugins': set(trace['plugins']) if trace.get('plugins') is not None else None}
106
+
107
+
108
+ def _plugin_label(entry):
109
+ """«source[=version]» for a plugin entry (the JSON array [name, source, version]); the source
110
+ already carries the name in the real init (name@marketplace). Anything else is shown as stored —
111
+ including a multi-init mismatch blob (named residual: it is not broken down per plugin)."""
112
+ try:
113
+ n, src, ver = json.loads(entry)
114
+ except Exception:
115
+ return entry
116
+ src = str(src or '') # unvalidated init JSON: a non-string source must not raise (it would change rc)
117
+ lab = src if src.startswith('%s@' % n) else ('%s@%s' % (n, src) if src else str(n))
118
+ return lab + ('=%s' % ver if ver else '')
119
+
120
+
121
+ def surface_diff(parts_list):
122
+ """Elements that are not in every arm, per kind — «mcp=a,b; plugins=x@y=1.0» — or '' when the
123
+ sets agree. Nothing is dropped: an UNKNOWN plugin list in some arm is named as such."""
124
+ out = []
125
+ for key in ('tools', 'mcp', 'plugins'):
126
+ sets = [p[key] for p in parts_list]
127
+ unknown = key == 'plugins' and any(x is None for x in sets)
128
+ sets = [x for x in sets if x is not None]
129
+ if unknown and sets:
130
+ out.append('plugins=UNKNOWN in some arm')
131
+ # among the arms whose list is known (codex R1: an UNKNOWN arm must not hide a known difference)
132
+ diff = set().union(*sets) - set.intersection(*sets) if sets else set()
133
+ if diff:
134
+ shown = sorted(_plugin_label(e) for e in diff) if key == 'plugins' else sorted(diff)
135
+ out.append('%s=%s' % (key, ','.join(shown)))
136
+ return '; '.join(out) # SURFACE_DIFF_RETURN (TR24 mutates this line)
137
+
138
+
92
139
  def inventory(trace):
93
140
  """One comparable string for the arm's tool/MCP/plugin surface, or None when the init event was
94
141
  absent. An init without a plugin list reads plugins=UNKNOWN, so it never equals an arm that has one."""
@@ -123,6 +170,150 @@ def behave_hit(trace, spec):
123
170
  return any(_read_hit(c, trace, pat) for c in file_calls)
124
171
 
125
172
 
173
+ # ── Behaviour profile (2026-11-17, record only — never read by a scorer) ─────────────────────────
174
+ # Two arms with the same PASS rate can still behave differently (arXiv:2611.17440): one may skip
175
+ # verification and pass anyway. The profile counts the arm's top-level tool calls in four bins.
176
+ # Every EMITTED call counts, successful or not — an attempted test run is still a test run.
177
+ # Bash is binned by its command text, in this order (first match wins):
178
+ # test-run some segment RUNS a test: its command word is a runner (pytest, jest, vitest, npm/pnpm/
179
+ # yarn test, go/cargo test, make test|check, python -m pytest|unittest), or a test
180
+ # script (selfcheck.sh, test_*.sh|py, *_lanes.sh) as the command or as the script
181
+ # argument of bash/sh/zsh/python. Naming a test file as data (`cat test_x.py`) is not a run.
182
+ # edit a write shape: a redirect to a file (not /dev/null, not >&N), sed -i / -Ei / --in-place,
183
+ # tee, or a segment whose command word is mv cp rm mkdir touch chmod ln
184
+ # explore the first command after any leading `cd …` is a read-only one (ls cat grep find …,
185
+ # git log/status/diff/show/…, gh … view/list/status/diff/checks)
186
+ # other anything else — running a script that is not a test lands here
187
+ # Named residuals: only the first non-cd segment decides explore, so `ls && ./build.sh` reads as
188
+ # explore; a redirect inside a quoted string reads as edit; a test runner named differently from the
189
+ # list reads as other; a runner inside a shell string (`bash -c 'pytest'`) or behind a wrapper that
190
+ # carries options (`env -i pytest`, `nice -n 10 pytest`, `timeout --signal=TERM 60 pytest`) reads as
191
+ # other; `git branch` / `git remote` read as other even when they only list. These are a heuristic's
192
+ # edges — after two cross-family rounds each found new ones, they are named here, not chased (a static
193
+ # shell-string reader does not converge). The profile is record only, so a misbinned call moves no
194
+ # verdict. Binning is calibrated on two hand-labelled nightly runs (17/17 calls, explore and other
195
+ # bins) — edit and test-run were exercised on fixtures only.
196
+ EXPLORE_TOOLS = ('Read', 'Grep', 'Glob', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'ToolSearch')
197
+ EDIT_TOOLS = ('Edit', 'Write', 'MultiEdit', 'NotebookEdit')
198
+ _TEST_SCRIPT_RE = re.compile(r'^(?:selfcheck\.sh|test_[\w.-]*\.(?:sh|py)|[\w.-]*_lanes?\.sh)$')
199
+ _TEST_RUNNERS = ('pytest', 'py.test', 'jest', 'vitest')
200
+ _SHELLS = ('bash', 'sh', 'zsh', 'python', 'python3')
201
+ _WRITE_RE = re.compile(r'>>?(?!&)\s*(?!/dev/null\b)[^\s&|;>]|\btee\b')
202
+ _EDIT_WORDS = ('mv', 'cp', 'rm', 'mkdir', 'touch', 'chmod', 'ln')
203
+ _EXPLORE_WORDS = ('ls', 'cat', 'head', 'tail', 'grep', 'egrep', 'rg', 'find', 'wc', 'tree', 'stat', 'file',
204
+ 'pwd', 'which', 'echo', 'printf', 'less', 'diff', 'du', 'sort', 'uniq', 'cut', 'sed', 'awk',
205
+ 'jq', 'readlink', 'realpath', 'basename', 'dirname', 'date', 'id', 'whoami')
206
+ _GIT_READ = ('log', 'status', 'diff', 'show', 'ls-files', 'ls-tree', 'blame',
207
+ 'rev-parse', 'grep', 'describe', 'shortlog', 'reflog')
208
+ _GH_READ = ('view', 'list', 'status', 'diff', 'checks')
209
+ PROFILE_BINS = ('explore', 'edit', 'test-run', 'other')
210
+
211
+
212
+ def _segments(cmd):
213
+ """Each segment's words, with leading VAR=value assignments and the wrappers env / time / nice /
214
+ exec / command / timeout <secs> dropped, so the command word is the one that runs; empty
215
+ segments skipped."""
216
+ for seg in re.split(r'&&|\|\||;|\n|\|', cmd):
217
+ words = seg.split()
218
+ while words:
219
+ if re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', words[0]) or words[0] in ('env', 'time', 'nice', 'exec', 'command'):
220
+ words = words[1:]
221
+ elif words[0] == 'timeout' and len(words) > 1:
222
+ words = words[2:]
223
+ else:
224
+ break
225
+ if words:
226
+ yield words
227
+
228
+
229
+ def _runs_test(w):
230
+ base = lambda x: x.rsplit('/', 1)[-1]
231
+ if w[0] in _TEST_RUNNERS or _TEST_SCRIPT_RE.match(base(w[0])):
232
+ return True
233
+ if w[0] in ('npm', 'pnpm', 'yarn') and 'test' in w[1:3]:
234
+ return True
235
+ if (w[0] in ('go', 'cargo') and w[1:2] == ['test']) or (w[0] == 'make' and w[1:2] in (['test'], ['check'])):
236
+ return True
237
+ if w[0] in _SHELLS:
238
+ args = [x for x in w[1:] if not x.startswith('-')]
239
+ if w[0].startswith('python') and '-m' in w and w[w.index('-m') + 1:w.index('-m') + 2] in (['pytest'], ['unittest']):
240
+ return True
241
+ return bool(args) and bool(_TEST_SCRIPT_RE.match(base(args[0])))
242
+ return False
243
+
244
+
245
+ def _sed_in_place(w):
246
+ return w[0] == 'sed' and any(x.startswith('--in-place') or re.match(r'^-[a-zA-Z]*i', x) for x in w[1:])
247
+
248
+
249
+ def _bash_bin(cmd):
250
+ cmd = str(cmd or '')
251
+ segs = list(_segments(cmd))
252
+ if any(_runs_test(w) for w in segs):
253
+ return 'test-run'
254
+ if _WRITE_RE.search(cmd) or any(w[0] in _EDIT_WORDS or _sed_in_place(w) for w in segs):
255
+ return 'edit'
256
+ first = next((w for w in segs if w[0] != 'cd'), None)
257
+ if not first:
258
+ return 'other'
259
+ if first[0] in _EXPLORE_WORDS:
260
+ return 'explore'
261
+ if first[0] == 'git' and any(w in _GIT_READ for w in first[1:3] if not w.startswith('-')):
262
+ return 'explore'
263
+ if first[0] == 'gh' and any(w in _GH_READ for w in first[1:4]):
264
+ return 'explore'
265
+ return 'other'
266
+
267
+
268
+ def profile_bins(trace):
269
+ """{bin: count} over the top-level calls of a parsed trace."""
270
+ out = dict.fromkeys(PROFILE_BINS, 0)
271
+ for name, inp, _ in trace['calls']:
272
+ if name in EXPLORE_TOOLS:
273
+ b = 'explore'
274
+ elif name in EDIT_TOOLS:
275
+ b = 'edit'
276
+ elif name == 'Bash':
277
+ b = _bash_bin((inp or {}).get('command') if isinstance(inp, dict) else '')
278
+ else:
279
+ b = 'other'
280
+ out[b] += 1
281
+ return out
282
+
283
+
284
+ def first_error(trace):
285
+ """1-based position of the first top-level call whose result is an error · 'none' when every top-level call
286
+ has a result and none is an error · 'unknown' when a call has no result before that (not measured ≠ no error).
287
+ Record only (AQ-20261101-2): a final PASS can hide a run that hit errors early and recovered by luck."""
288
+ for i, (_, _, cid) in enumerate(trace['calls'], 1):
289
+ if cid in trace['err_ids']:
290
+ return str(i)
291
+ if cid not in trace['res_ids']:
292
+ return 'unknown'
293
+ return 'none'
294
+
295
+
296
+ def _profile(src):
297
+ """One line for the report. A stream that cannot be read says so (exit 3) — never counts of 0.
298
+ A stream with no result event or damaged lines keeps its counts and says they are a lower bound."""
299
+ tr = parse_stream(src)
300
+ if tr is None:
301
+ print('trace=UNREADABLE')
302
+ return 3
303
+ p = profile_bins(tr)
304
+ line = ' '.join('%s=%d' % (b, p[b]) for b in PROFILE_BINS) + ' total=%d' % sum(p.values())
305
+ line += ' first_error=%s' % first_error(tr)
306
+ flags = []
307
+ if tr['result'] is None:
308
+ flags.append('result=MISSING')
309
+ if tr['damaged']:
310
+ flags.append('damaged=%d' % tr['damaged'])
311
+ if flags:
312
+ line += ' ' + ' '.join(flags) + ' (counts are a lower bound)'
313
+ print(line)
314
+ return 0
315
+
316
+
126
317
  def _extract(src, dst_txt, dst_tools):
127
318
  tr = parse_stream(src)
128
319
  if tr is None or tr['result'] is None or tr['damaged']:
@@ -137,5 +328,7 @@ def _extract(src, dst_txt, dst_tools):
137
328
  if __name__ == '__main__':
138
329
  if len(sys.argv) == 5 and sys.argv[1] == 'extract':
139
330
  sys.exit(_extract(*sys.argv[2:5]))
331
+ if len(sys.argv) == 3 and sys.argv[1] == 'profile':
332
+ sys.exit(_profile(sys.argv[2]))
140
333
  print(__doc__, file=sys.stderr)
141
334
  sys.exit(2)
@@ -84,6 +84,24 @@ ACCEPTED_ABSENT=(
84
84
  # release by default. selfcheck resolves its row as SKIP («not in files[], and absent») on a consumer tree.
85
85
  "scripts/cartridge_admit.py"
86
86
  "scripts/test_cartridge_admit_lanes.sh"
87
+ # 2026-11-18 — core cartridge loader (SessionStart hook), its snippet, example list and lanes. The loader only loads
88
+ # snapshots that cartridge_admit.py admitted (the list carries its snapshot_sha256), and that checker is not
89
+ # shipped (above) — so ship all of them together when the operator decides to publish cartridges, or none.
90
+ # Shipping the snippet alone would make install-wizard register a hook for consumers who cannot admit anything.
91
+ "scripts/cartridge_loader.py"
92
+ "scripts/cartridge_loader.sh"
93
+ "scripts/test_cartridge_loader_lanes.sh"
94
+ "templates/settings.CartridgeLoader.snippet.json"
95
+ # 2026-11-19 — measurement scoreboard renderer and its lanes. It reads the operator's sealed measurement records across
96
+ # their own repositories; a consumer has none of those records, so it is not shipped. selfcheck resolves the anchor
97
+ # row as SKIP («not in files[], and absent»).
98
+ "scripts/scoreboard_render.py"
99
+ "scripts/test_scoreboard_render_lanes.sh"
100
+ # 2026-11-19 — FH-side check that the published fh-techwriter copy of ko-tech-writer still matches FH's export,
101
+ # and its lanes. A maintainer tool for this repository's own export, not a consumer capability: a consumer has
102
+ # no fh-techwriter copy to compare. selfcheck resolves its anchor row as SKIP («not in files[], and absent»).
103
+ "scripts/fh_techwriter_sync_check.sh"
104
+ "scripts/test_fh_techwriter_sync_lanes.sh"
87
105
  # 🟥 2026-09-21 (야간) — 정책렌즈 채점기와 그 레인. **FH 자기 연구의 실험 기록**이지 소비자
88
106
  # 능력이 아니다: 판정 대상이 `scripts/fixtures/policy_lens_knownpair_2026-09-21/` 안의
89
107
  # 1차 런 48개 파일(236K)이고, 그것까지 실어 보내면 아무도 안 쓰는 실험 아카이브가 패키지
@@ -16,7 +16,7 @@
16
16
  # 🟥 This script does not decide whether to merge. Approval is still yours — it only makes the
17
17
  # verification impossible to forget once you do.
18
18
  #
19
- # USAGE bash scripts/pr_merge_verified.sh <pr-number> --rerun '<command>' [--repo <path>] [--lease '<label>']
19
+ # USAGE bash scripts/pr_merge_verified.sh <pr-number> --rerun '<command>' [--repo <path>] [--lease '<label>'] [--expect-head <full sha>]
20
20
  # RECEIPT once GitHub has accepted the merge request (every outcome from there: verified · verify failed · queued/not completed ·
21
21
  # merged from another head · not fetchable — never for a refusal or a merge GitHub did not take) one JSON line goes to
22
22
  # ${PMV_RECEIPTS:-<git common dir>/fh-merge-receipts.jsonl} — local, never pushed: pr · head · merge · outcome ·
@@ -25,8 +25,10 @@
25
25
  # Why: arXiv:2610.28683 — 27% of merges that passed a «non-author review» gate rested on an agent approving under a
26
26
  # human account; who decided must be on the record, not inferred later (frontier digest 2026-10-23).
27
27
  # EXIT 0 merged + verified · 1 merged but verify FAILED (the merge stands — act on it)
28
- # 2 usage (nothing merged) · 3 trivial --rerun refused (nothing merged)
29
- # 4 harness error (see message: before or after the merge)
28
+ # 2 usage (nothing merged) — includes an --expect-head that is not a full 40/64-char lowercase hex id
29
+ # 3 trivial --rerun refused (nothing merged)
30
+ # 4 harness error (see message: before or after the merge) — includes a PR head read from gh that is not a full
31
+ # 40/64-char lowercase hex id (cut on the way, e.g. by an output-compression proxy; nothing merged)
30
32
  # 6 merge accepted but not completed (queue/lag) — NOT verified, nothing claimed
31
33
  # 7 lease merge refused: a --lease other than «operator…» and selfdev_merge_tier.sh did not say AUTO, or the tier
32
34
  # could not be read (nothing merged)
@@ -48,8 +50,15 @@ while [ $# -gt 0 ]; do
48
50
  *) [ -z "$PR" ] || { echo "🟥 one PR number only" >&2; exit 2; }; PR="$1"; shift ;;
49
51
  esac
50
52
  done
51
- case "$PR" in ''|*[!0-9]*) echo "🟥 usage: pr_merge_verified.sh <pr-number> --rerun '<cmd>'" >&2; exit 2 ;; esac
53
+ case "$PR" in ''|*[!0-9]*) echo "🟥 usage: pr_merge_verified.sh <pr-number> --rerun '<cmd>' [--repo <path>] [--lease '<label>'] [--expect-head <full sha>]" >&2; exit 2 ;; esac
52
54
  [ "$RERUN_SET" -eq 1 ] || { echo "🟥 --rerun is required — checked before merging so the verify half cannot be skipped" >&2; exit 2; }
55
+ # _full_oid <value> — true only for a full commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex. A shorter value can
56
+ # still resolve locally (git accepts abbreviations), so «resolves» is not «whole». A field run saw an output-compression
57
+ # proxy cut `git rev-parse HEAD` to 37 chars, and the API that took it failed later with no hint why.
58
+ _full_oid() { case "$1" in *[!0-9a-f]*|'') return 1 ;; esac; [ "${#1}" -eq 40 ] || [ "${#1}" -eq 64 ]; }
59
+ if [ -n "$EXPECT_HEAD" ] && ! _full_oid "$EXPECT_HEAD"; then
60
+ echo "🟥 --expect-head is not a full 40- or 64-hex commit id («${EXPECT_HEAD}», ${#EXPECT_HEAD} chars) — a shortened or cut value (an output proxy can do this) cannot pin a merge; not merging" >&2; exit 2
61
+ fi
53
62
  PSV="$(cd "$(dirname "$0")" && pwd)/post_squash_verify.sh"
54
63
  [ -f "$PSV" ] || { echo "🟥 HARNESS-ERROR (before merge): $PSV missing — not merging" >&2; exit 4; }
55
64
 
@@ -96,6 +105,7 @@ _clog() { # outcome-label merge_oid
96
105
  # 1. head before merge
97
106
  HEAD_OID=$(gh pr view "$PR" --json headRefOid -q .headRefOid < /dev/null) || HEAD_OID=""
98
107
  [ -n "$HEAD_OID" ] || { echo "🟥 HARNESS-ERROR (before merge): could not read PR #$PR head" >&2; exit 4; }
108
+ _full_oid "$HEAD_OID" || { echo "🟥 HARNESS-ERROR (before merge): PR #$PR head «${HEAD_OID}» is not a full 40- or 64-hex commit id (${#HEAD_OID} chars) — the value may have been cut on the way (an output proxy can do this); not merging" >&2; exit 4; }
99
109
  git fetch -q origin "pull/$PR/head" < /dev/null 2>/dev/null || git fetch -q origin "$HEAD_OID" < /dev/null 2>/dev/null || true
100
110
  git cat-file -e "$HEAD_OID^{commit}" 2>/dev/null \
101
111
  || { echo "🟥 HARNESS-ERROR (before merge): PR head $HEAD_OID not fetchable — not merging" >&2; exit 4; }
@@ -19,6 +19,14 @@
19
19
  # Runs in throwaway repos (mktemp): never touches this repo's index or worktree.
20
20
  # Usage: bash scripts/prepush_guard_check.sh → exit 0 all pairs hold, 1 otherwise.
21
21
  set -uo pipefail
22
+ # Measure the pre-push hook as it behaves by DEFAULT: an override the caller exported (PUBLIC_SURFACE_OK=1 …) must
23
+ # not reach the hook under test (pmh-dev #91 ②, 2026-11-15). Lane: scripts/test_guard_anchor_override_env_lanes.sh.
24
+ # Also the two non-override inputs the hook reads from the environment (codex R1): PSA_PATTERNS replaces the
25
+ # fixtures' synthetic operator patterns, FH_DESTRUCTIVE_BASE moves the destructive-advisory baseline.
26
+ unset PUBLIC_SURFACE_OK DESTRUCTIVE_OP_OK FH_NOVELTY_OK MAIN_PUSH_OK PUSH_ZONE_OK TAG_VERSION_OK TRACKS_GITLINK_OK TRACKS_PUBLIC_OK PSA_PATTERNS FH_DESTRUCTIVE_BASE 2>/dev/null || true
27
+ # Every PSA_* input too (codex R2: PSA_ALLOWLIST suppressed a planted positive) — by prefix, so a new PSA_ input
28
+ # cannot slip past a hand-written list. The scan library sets the ones it needs itself.
29
+ for _v in $(compgen -v | grep '^PSA_'); do unset "$_v"; done; unset _v
22
30
 
23
31
  REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
24
32
  HOOK_SRC="$REPO_ROOT/templates/.git-hooks/pre-push"
@@ -439,6 +439,38 @@ score_rc=$?
439
439
  done < "$SPEC_DIR/selected_ids.txt"
440
440
  } >> "$REPORT_PATH"
441
441
 
442
+ # Behaviour profile (2026-11-17, arXiv:2611.17440 — record only, never read by the scorer above).
443
+ # Two arms with the same pass rate can still behave differently — one may skip verification and pass
444
+ # anyway. One line per rep: the arm's top-level tool calls in four bins, counted from the event stream
445
+ # the runner already keeps (bin rules: scripts/live_eval_trace.py). A rep with no stream says MISSING,
446
+ # an unreadable one UNREADABLE — never counts of 0. Appended AFTER score; score_rc is untouched.
447
+ {
448
+ echo ""
449
+ echo "## Behaviour profile (record only — not scored)"
450
+ echo ""
451
+ if [ -z "$FH_LIVE_TRACE_ARG" ]; then
452
+ echo "behaviour-profile: not recorded — FH_LIVE_TRACE=0 (no event stream kept)"
453
+ else
454
+ while IFS= read -r id; do
455
+ [ -z "$id" ] && continue
456
+ for arm in primary control control_b; do
457
+ [ "$arm" = control_b ] && [ ! -f "$SPEC_DIR/$id.control_b.txt" ] && continue
458
+ r=1
459
+ while [ "$r" -le "$REPS" ]; do
460
+ st="$OUTDIR/$id/${arm}_r${r}.stream.jsonl"
461
+ if [ ! -f "$st" ]; then
462
+ echo "behaviour-profile: $id $arm r$r trace=MISSING"
463
+ else
464
+ bp="$(python3 "$REPO_ROOT/scripts/live_eval_trace.py" profile "$st" 2>/dev/null)"
465
+ echo "behaviour-profile: $id $arm r$r ${bp:-trace=UNREADABLE}"
466
+ fi
467
+ r=$((r + 1))
468
+ done
469
+ done
470
+ done < "$SPEC_DIR/selected_ids.txt"
471
+ fi
472
+ } >> "$REPORT_PATH"
473
+
442
474
  if [ -n "$EVIDENCE_DIR" ]; then
443
475
  # The report is part of the evidence: a preserved body set with no verdict beside it forces the
444
476
  # next reader to re-derive what the run concluded.
@@ -529,6 +529,7 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
529
529
  except (ValueError, re.error) as e:
530
530
  behave_err, behave = str(e), None
531
531
  inventories, inv_unknown, traces, no_trace, b_reps = set(), 0, {}, 0, []
532
+ inv_parts = {} # inventory string → its three sets, so the INVALID reason can name the difference
532
533
  damaged, any_trace = 0, False
533
534
  ctrl_b_absent = False # rep-1 only, diagnostic: which arm actually produced nothing
534
535
  per_rep = [] # [(verdict, phit, chit, primary_text, control_text)]
@@ -569,6 +570,7 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
569
570
  inv = _trace.inventory(tr)
570
571
  if inv is not None:
571
572
  inventories.add(inv)
573
+ inv_parts[inv] = _trace.inventory_parts(tr)
572
574
  elif tr is not None:
573
575
  inv_unknown += 1
574
576
  traces[(arm, i)] = tr
@@ -633,8 +635,12 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
633
635
  elif behave and any_trace and (no_trace or damaged):
634
636
  row['reason'] = 'TRACE-INCOMPLETE: %d rep(s) missing an arm trace · %d damaged stream(s)' % (no_trace, damaged)
635
637
  elif len(inventories) > 1:
636
- row['reason'] = 'INVALID-COMPARISON: arms saw %d different tool/MCP/plugin lists — %s' % (
637
- len(inventories), ' ≠ '.join(sorted(inventories)))
638
+ # Name what differs FIRST (2026-11-20 weekly audit: two 840-char lists side by side, the
639
+ # diff left to a human, INVALID rose 0→3/12 unexplained); the full lists still follow.
640
+ _d = _trace.surface_diff([inv_parts[x] for x in sorted(inventories)])
641
+ row['reason'] = 'INVALID-COMPARISON: arms saw %d different tool/MCP/plugin lists — %s%s' % (
642
+ len(inventories), ('not in every arm: %s — ' % (_d or 'none — the lists differ only in duplicates or count')),
643
+ ' ≠ '.join(sorted(inventories)))
638
644
  if len(ran_reps) > 1 and 0 < len(pass_reps) < len(ran_reps):
639
645
  flaky = 'FLAKY across reps (%s)' % ','.join(r[0] for r in per_rep)
640
646
  # an INVALID-COMPARISON reason must survive: the surface mismatch is why there is no number