@chrono-meta/fh-gate 3.29.0 → 3.31.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 (47) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/AGENTS.md +7 -2
  3. package/CLAUDE.md +1 -1
  4. package/README.ja.md +6 -5
  5. package/README.ko.md +6 -5
  6. package/README.md +15 -5
  7. package/README.zh.md +6 -5
  8. package/docs/REFERENCE.md +6 -5
  9. package/docs/USER_GUIDE.md +3 -0
  10. package/knowledge/shared/harness-core/claude_md_gate_details.md +1 -1
  11. package/knowledge/shared/harness-core/dispatch_conditional_prohibition.md +42 -0
  12. package/knowledge/shared/harness-core/sonnet_floor_doctrine.md +7 -0
  13. package/knowledge/shared/learnings/subagent_invocations_log.yaml +161 -0
  14. package/package.json +6 -1
  15. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  16. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/CHANGELOG.md +35 -0
  18. package/plugins/fh-meta/skills/install-wizard/SKILL.md +25 -0
  19. package/plugins/fh-meta/skills/install-wizard/SKILL_detail.md +24 -6
  20. package/plugins/fh-meta/skills/phantom-quench/SKILL.md +1 -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/abstract_consult_check.py +573 -0
  24. package/scripts/fh_detach.py +444 -0
  25. package/scripts/mapped_tracks.sh +20 -13
  26. package/scripts/memory_gc_report.py +55 -5
  27. package/scripts/pr_merge_verified.sh +56 -8
  28. package/scripts/selfcheck.sh +85 -6
  29. package/scripts/session_checklist.py +3 -2
  30. package/scripts/session_close_check.sh +1 -1
  31. package/scripts/sim_isolated_run.sh +62 -0
  32. package/scripts/stale_ref_scan.py +47 -3
  33. package/scripts/test_abstract_consult_check_lanes.sh +201 -0
  34. package/scripts/test_fh_detach_lanes.sh +252 -0
  35. package/scripts/test_hook_source_gate_lanes.sh +16 -2
  36. package/scripts/test_mapped_tracks_lanes.sh +55 -1
  37. package/scripts/test_memory_gc_report_lanes.sh +91 -1
  38. package/scripts/test_mutation_probe_lanes.sh +86 -10
  39. package/scripts/test_ollama_panel_lanes.sh +107 -11
  40. package/scripts/test_pr_merge_verified_lanes.sh +48 -1
  41. package/scripts/test_prepush_real_fire_lanes.sh +215 -0
  42. package/scripts/test_selfcheck_state_lanes.sh +73 -1
  43. package/scripts/test_session_checklist_lanes.sh +34 -0
  44. package/scripts/test_sim_isolated_run_lanes.sh +88 -0
  45. package/scripts/test_stale_ref_scan_lanes.sh +11 -1
  46. package/templates/.git-hooks/pre-push +82 -1
  47. package/templates/CLAUDE.md +16 -0
@@ -0,0 +1,444 @@
1
+ #!/usr/bin/env python3
2
+ """fh_detach.py — undo what /install-wizard wrote, and nothing else.
3
+
4
+ Usage:
5
+ python3 scripts/fh_detach.py [--project DIR] [--fh-dir DIR] [--home DIR] [--apply] [--plugin]
6
+
7
+ Default is a dry run: it prints the plan and changes nothing. `--apply` carries it out.
8
+
9
+ What counts as FH's (each is removed only on an EXACT match with what the wizard writes today):
10
+ ① ~/.zshrc the wizard's block (marked `# >>> forge-harness >>>` … or the older unmarked 4 lines)
11
+ ② <dir>/.claude/settings.json · settings.local.json
12
+ hook entries equal in every field (key order ignored) to an entry in a shipped
13
+ templates/settings.*.snippet.json, or to the Mode-D companion hook form. A file the wizard created is deleted when
14
+ nothing else is left in it; if a .prewizard backup equals the stripped file, its bytes are
15
+ put back (so the user's own formatting returns).
16
+ ③ <dir>/CLAUDE.local.md the «Companion-store session-start read» section the wizard appended
17
+ ④ git core.hooksPath only when it is `templates/.git-hooks` (the wizard's value) in the FH clone
18
+ ⑤ ~/.cc_sentinels/<project>_wizard_* (and the folder, when that leaves it empty)
19
+ ⑥ .claude/rules/local_fh_context.md · fh_env_context.jsonc only when byte-equal to the shipped template,
20
+ plus their exact lines in .git/info/exclude
21
+ ⑦ --plugin also runs `claude plugin uninstall` / `marketplace remove` for fh-meta@forge-harness
22
+
23
+ What it never does: delete a user's own hook (even one sharing a group or a script name with FH — a hook identical
24
+ to FH's shipped entry cannot be told apart and is treated as FH's), edit a line it did not write, or touch a file
25
+ it cannot parse (that is exit 10, file untouched). Scope: ① and ④ are machine/clone-wide, so this takes FH off the
26
+ whole setup, not one project.
27
+
28
+ Exit: 0 = no recognised FH trace left · 1 = something FH-like is left that needs a human look (listed) ·
29
+ 10 = could not read something it needed (nothing changed past that point) · 11 = bad arguments.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import subprocess
38
+ import sys
39
+
40
+ ZSH_BEGIN = "# >>> forge-harness (install-wizard) >>>"
41
+ ZSH_END = "# <<< forge-harness (install-wizard) <<<"
42
+ LEGACY_ZSH = [
43
+ re.compile(r'^export FH_DIR=".*"$'),
44
+ re.compile(r'^export CC_HUB_DIR=".*"$'),
45
+ re.compile(r'^export CC_SENTINELS_DIR="\$HOME/\.cc_sentinels"$'),
46
+ re.compile(r'^source "\$FH_DIR/templates/fh_audit_check\.zsh"$'),
47
+ ]
48
+ COMPANION_HEAD = "## Companion-store session-start read"
49
+ COMPANION_WIRING = ("At session start: read $BE_DIR/INDEX.md first; then ls -t paper-signals/ handoff/ digests/ and "
50
+ "open anything newer than the session card (card=pointer, store commit=truth) — not only handoffs.")
51
+ # Mode-D companion hooks (install-wizard SKILL_detail §Mode-D-Companion-Setup): BE_DIR is baked in at write time.
52
+ MODE_D_CMD = re.compile(r'^BE_DIR="[^"]*" bash "\$CLAUDE_PROJECT_DIR/scripts/(fh_session_load|fh_env_delta_scan)\.sh"$')
53
+ COPIED_TEMPLATES = (("local_fh_context.md", ".claude/rules/local_fh_context.md"),
54
+ ("fh_env_context.jsonc", ".claude/rules/fh_env_context.jsonc"))
55
+ SCRIPT_KEY = re.compile(r'scripts/([A-Za-z0-9_\-]+\.sh)')
56
+ FH_HINT = re.compile(r'CLAUDE_PROJECT_DIR|forge-harness|FH_DIR')
57
+
58
+
59
+ class HarnessError(Exception):
60
+ pass
61
+
62
+
63
+ def read(p):
64
+ with open(p, encoding="utf-8") as f:
65
+ return f.read()
66
+
67
+
68
+ def read_bytes(p):
69
+ with open(p, "rb") as f:
70
+ return f.read()
71
+
72
+
73
+ def canon(h):
74
+ return json.dumps(h, sort_keys=True, ensure_ascii=False)
75
+
76
+
77
+ def snippet_commands(fh_dir):
78
+ """Every hook entry the shipped snippets register — the exact objects the wizard writes (command AND every other
79
+ field: a hook whose timeout or message the user changed is theirs now, codex R1)."""
80
+ cmds, keys = set(), set()
81
+ snippets = sorted(glob.glob(os.path.join(fh_dir, "templates", "settings.*.snippet.json")))
82
+ if not snippets:
83
+ raise HarnessError("no templates/settings.*.snippet.json under %s — cannot tell FH hooks from yours" % fh_dir)
84
+ for s in snippets:
85
+ try:
86
+ blob = json.loads(read(s))
87
+ except (OSError, ValueError) as e:
88
+ raise HarnessError("unreadable snippet %s: %s" % (s, e))
89
+ for groups in ((blob.get("project_settings_json") or {}).get("hooks") or {}).values():
90
+ for g in groups if isinstance(groups, list) else []:
91
+ for h in g.get("hooks", []) if isinstance(g, dict) else []:
92
+ c = h.get("command") if isinstance(h, dict) else None
93
+ if isinstance(c, str):
94
+ cmds.add(canon(h))
95
+ keys.update(SCRIPT_KEY.findall(c))
96
+ keys.update({"fh_session_load.sh", "fh_env_delta_scan.sh"})
97
+ keys.update(os.path.basename(x) for x in glob.glob(os.path.join(fh_dir, "scripts", "*.sh")))
98
+ return cmds, keys
99
+
100
+
101
+ def is_fh_hook(h, cmds):
102
+ if canon(h) in cmds:
103
+ return True
104
+ # Mode-D companion form: exactly {type, command, timeout 20} as the wizard writes it
105
+ return (set(h) == {"type", "command", "timeout"} and h.get("type") == "command" and h.get("timeout") == 20
106
+ and bool(MODE_D_CMD.match(h.get("command", ""))))
107
+
108
+
109
+ def looks_fh(cmd, keys):
110
+ """FH-like but not byte-equal (an older snippet version, a hand edit): reported, never removed."""
111
+ return bool(FH_HINT.search(cmd)) and any(k in SCRIPT_KEY.findall(cmd) for k in keys)
112
+
113
+
114
+ def strip_settings(d, cmds):
115
+ """Return (stripped copy, removed commands). Keeps every non-FH hook, in order."""
116
+ out = json.loads(json.dumps(d))
117
+ removed = []
118
+ hooks = out.get("hooks")
119
+ if not isinstance(hooks, dict):
120
+ return out, removed
121
+ for ev in list(hooks):
122
+ groups = hooks[ev]
123
+ if not isinstance(groups, list):
124
+ continue
125
+ kept = []
126
+ for g in groups:
127
+ if not isinstance(g, dict) or not isinstance(g.get("hooks"), list):
128
+ kept.append(g)
129
+ continue
130
+ hs, took = [], False
131
+ for h in g["hooks"]:
132
+ c = h.get("command") if isinstance(h, dict) else None
133
+ if isinstance(c, str) and is_fh_hook(h, cmds):
134
+ removed.append(c)
135
+ took = True
136
+ else:
137
+ hs.append(h)
138
+ if hs or not took: # a group that was empty before is the user's — kept (codex R2)
139
+ g = dict(g)
140
+ g["hooks"] = hs
141
+ kept.append(g)
142
+ if kept:
143
+ hooks[ev] = kept
144
+ else:
145
+ del hooks[ev]
146
+ if not hooks:
147
+ del out["hooks"]
148
+ return out, removed
149
+
150
+
151
+ def suspects_in(d, keys):
152
+ out = []
153
+ for groups in (d.get("hooks") or {}).values() if isinstance(d.get("hooks"), dict) else []:
154
+ for g in groups if isinstance(groups, list) else []:
155
+ for h in g.get("hooks", []) if isinstance(g, dict) else []:
156
+ c = h.get("command") if isinstance(h, dict) else None
157
+ if isinstance(c, str) and looks_fh(c, keys):
158
+ out.append(c)
159
+ return out
160
+
161
+
162
+ class Plan:
163
+ def __init__(self, apply):
164
+ self.apply = apply
165
+ self.actions = [] # (label, fn)
166
+ self.left = [] # FH-like traces left for a human
167
+ self.notes = []
168
+
169
+ def act(self, label, fn):
170
+ self.actions.append((label, fn))
171
+
172
+
173
+ def plan_zshrc(plan, home):
174
+ p = os.path.join(home, ".zshrc")
175
+ if not os.path.isfile(p):
176
+ return
177
+ lines = read(p).split("\n")
178
+ out, i, hit = [], 0, 0
179
+ while i < len(lines):
180
+ if (lines[i] == ZSH_BEGIN and i + 5 < len(lines) and lines[i + 5] == ZSH_END
181
+ and all(LEGACY_ZSH[k].match(lines[i + 1 + k]) for k in range(4))):
182
+ i += 6 # markers bind only the wizard's exact four lines — anything added inside is the user's (codex R1)
183
+ hit += 1
184
+ continue
185
+ if lines[i] == ZSH_BEGIN and ZSH_END in lines[i:]:
186
+ j = lines.index(ZSH_END, i) + 1 # an edited block is the user's now — copied verbatim, never mined for
187
+ out.extend(lines[i:j]) # the four legacy lines (codex R2: that deleted them from inside the block)
188
+ i = j
189
+ continue
190
+ if i + 4 <= len(lines) and all(LEGACY_ZSH[k].match(lines[i + k]) for k in range(4)):
191
+ i += 4
192
+ hit += 1
193
+ continue
194
+ out.append(lines[i])
195
+ i += 1
196
+ if hit:
197
+ new = "\n".join(out)
198
+ seen = "\n".join(lines)
199
+
200
+ def do():
201
+ if read(p) != seen:
202
+ plan.left.append("~/.zshrc changed after the plan was made — not written; run detach again")
203
+ return
204
+ with open(p, "w", encoding="utf-8") as f:
205
+ f.write(new)
206
+ plan.act("~/.zshrc: remove the wizard block (%d)" % hit, do)
207
+ if any("fh_audit_check.zsh" in l or l in (ZSH_BEGIN, ZSH_END) for l in out):
208
+ plan.left.append("~/.zshrc: a line still sources fh_audit_check.zsh but is not the wizard's exact block")
209
+
210
+
211
+ def plan_settings(plan, path, cmds, keys):
212
+ if not os.path.isfile(path):
213
+ return
214
+ try:
215
+ cur = json.loads(read(path))
216
+ except ValueError as e:
217
+ raise HarnessError("cannot parse %s (%s) — left untouched" % (path, e))
218
+ if not isinstance(cur, dict):
219
+ raise HarnessError("%s is not a JSON object — left untouched" % path)
220
+ stripped, removed = strip_settings(cur, cmds)
221
+ for c in suspects_in(stripped, keys):
222
+ plan.left.append("%s: FH-like hook that is not byte-equal to a shipped snippet (older version?) — %s"
223
+ % (path, c[:120]))
224
+ bak = path + ".prewizard"
225
+ restore = drop_bak = None
226
+ if os.path.isfile(bak):
227
+ try:
228
+ prev_stripped, prev_fh = strip_settings(json.loads(read(bak)), cmds)
229
+ if prev_stripped == stripped:
230
+ if prev_fh:
231
+ drop_bak = bak # a re-run's backup: it holds only FH hooks beyond what stays (codex R2)
232
+ else:
233
+ restore = bak
234
+ except ValueError:
235
+ pass
236
+ seen = read(path)
237
+ if not removed and restore is None and drop_bak is None:
238
+ if os.path.isfile(bak):
239
+ plan.notes.append("%s: kept (it differs from your current settings — open it, delete it when done)" % bak)
240
+ return
241
+
242
+ def do():
243
+ if read(path) != seen: # another session wrote it after the plan (codex R2) — never overwrite their change
244
+ plan.left.append("%s changed after the plan was made — not written; run detach again" % path)
245
+ return
246
+ if drop_bak:
247
+ os.remove(drop_bak)
248
+ if restore:
249
+ shutil.copy2(restore, path)
250
+ os.remove(restore)
251
+ elif not stripped:
252
+ os.remove(path)
253
+ else:
254
+ with open(path, "w", encoding="utf-8") as f:
255
+ json.dump(stripped, f, indent=2, ensure_ascii=False)
256
+ f.write("\n")
257
+ how = ("restore your pre-wizard bytes from .prewizard" if restore
258
+ else "delete the file (only FH hooks were in it)" if not stripped
259
+ else "remove %d FH hook(s), keep the rest" % len(removed))
260
+ plan.act("%s: %s" % (path, how), do)
261
+ if os.path.isfile(bak) and not restore and not drop_bak:
262
+ plan.notes.append("%s: kept (it differs from your current settings — open it, delete it when done)" % bak)
263
+
264
+
265
+ def plan_claude_local(plan, d):
266
+ p = os.path.join(d, "CLAUDE.local.md")
267
+ if not os.path.isfile(p):
268
+ return
269
+ s = read(p)
270
+ block = "\n%s\n%s\n" % (COMPANION_HEAD, COMPANION_WIRING)
271
+ if block in s:
272
+ new = s.replace(block, "", 1)
273
+
274
+ def do():
275
+ if new:
276
+ with open(p, "w", encoding="utf-8") as f:
277
+ f.write(new)
278
+ else:
279
+ os.remove(p)
280
+ plan.act("%s: remove the wizard's companion-store section" % p, do)
281
+ elif COMPANION_HEAD in s:
282
+ plan.left.append("%s: a «%s» section that is not the wizard's exact text" % (p, COMPANION_HEAD))
283
+
284
+
285
+ def plan_hookspath(plan, fh_dir):
286
+ if not os.path.isdir(os.path.join(fh_dir, ".git")) and not os.path.isfile(os.path.join(fh_dir, ".git")):
287
+ return
288
+ r = subprocess.run(["git", "-C", fh_dir, "config", "--local", "--get", "core.hooksPath"],
289
+ capture_output=True, text=True)
290
+ v = r.stdout.strip()
291
+ if r.returncode not in (0, 1):
292
+ raise HarnessError("git config read failed in %s: %s" % (fh_dir, r.stderr.strip()))
293
+ if v == "templates/.git-hooks":
294
+ plan.act("%s: unset core.hooksPath (templates/.git-hooks)" % fh_dir,
295
+ lambda: subprocess.run(["git", "-C", fh_dir, "config", "--local", "--unset", "core.hooksPath"],
296
+ check=True))
297
+ elif v and "templates/.git-hooks" in v:
298
+ plan.left.append("%s: core.hooksPath=%s (not the wizard's value — left alone)" % (fh_dir, v))
299
+
300
+
301
+ def plan_sentinels(plan, home, project):
302
+ d = os.path.join(home, ".cc_sentinels")
303
+ if not os.path.isdir(d):
304
+ return
305
+ mine = sorted(glob.glob(os.path.join(d, glob.escape(project) + "_wizard_*")))
306
+ rest = sorted(set(os.listdir(d)) - {os.path.basename(m) for m in mine})
307
+
308
+ def do():
309
+ for m in mine:
310
+ os.remove(m)
311
+ if not os.listdir(d):
312
+ os.rmdir(d)
313
+ if mine:
314
+ plan.act("~/.cc_sentinels: remove %s" % ", ".join(os.path.basename(m) for m in mine), do)
315
+ if rest:
316
+ plan.notes.append("~/.cc_sentinels: %d other file(s) kept (other projects or audit stamps): %s"
317
+ % (len(rest), ", ".join(rest[:6])))
318
+
319
+
320
+ def _exclude_path(proj):
321
+ """.git/info/exclude through git itself — in a worktree .git is a file and the exclude lives in the common dir."""
322
+ r = subprocess.run(["git", "-C", proj, "rev-parse", "--path-format=absolute", "--git-path", "info/exclude"],
323
+ capture_output=True, text=True)
324
+ return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
325
+
326
+
327
+ def plan_copies(plan, fh_dir, proj):
328
+ excl = _exclude_path(proj)
329
+ removed = set()
330
+ for src, rel in COPIED_TEMPLATES:
331
+ dst = os.path.join(proj, rel)
332
+ tpl = os.path.join(fh_dir, "templates", src)
333
+ if os.path.isfile(dst):
334
+ # bytes, not text: universal-newline reading called a CRLF-converted copy «unchanged» (codex R1)
335
+ if os.path.isfile(tpl) and read_bytes(dst) == read_bytes(tpl):
336
+ plan.act("%s: remove (unchanged copy of templates/%s)" % (dst, src),
337
+ lambda dst=dst: os.remove(dst))
338
+ removed.add(rel)
339
+ else:
340
+ plan.left.append("%s: you edited this copy of templates/%s — kept" % (dst, src))
341
+ elif not os.path.lexists(dst):
342
+ removed.add(rel) # copy already gone (a rerun after a partial apply, codex R2) — its exclude goes too
343
+ if excl and os.path.isfile(excl) and removed:
344
+ lines = read(excl).split("\n")
345
+ # only the lines of copies removed above — a kept copy keeps its exclude, or git would start staging it (codex R1)
346
+ drop = removed | {"/" + rel for rel in removed}
347
+ new = [l for l in lines if l.strip() not in drop]
348
+ if new != lines:
349
+ def do():
350
+ with open(excl, "w", encoding="utf-8") as f:
351
+ f.write("\n".join(new))
352
+ plan.act("%s: remove the wizard's exclude line(s)" % excl, do)
353
+
354
+
355
+ def plan_rules_dir(plan, proj):
356
+ """Remove .claude/rules and .claude when the steps above leave them empty (checked at apply time)."""
357
+ def do():
358
+ for d in (os.path.join(proj, ".claude", "rules"), os.path.join(proj, ".claude")):
359
+ if os.path.isdir(d) and not os.listdir(d):
360
+ os.rmdir(d)
361
+ plan.actions.append((None, do))
362
+
363
+
364
+ def plan_plugin(plan):
365
+ def do():
366
+ for argv in (["claude", "plugin", "uninstall", "fh-meta@forge-harness"],
367
+ ["claude", "plugin", "marketplace", "remove", "forge-harness"]):
368
+ try:
369
+ r = subprocess.run(argv, capture_output=True, text=True)
370
+ rc, msg = r.returncode, (r.stdout + r.stderr).strip()
371
+ except OSError as e:
372
+ rc, msg = 127, str(e)
373
+ print(" $ %s → rc=%d %s" % (" ".join(argv), rc, msg[:160]))
374
+ if rc != 0: # a failed uninstall is a trace left, not a success (codex R1)
375
+ plan.left.append("plugin: `%s` failed (rc=%d) — run it yourself" % (" ".join(argv), rc))
376
+ plan.act("claude plugin: uninstall fh-meta@forge-harness · remove the forge-harness marketplace", do)
377
+
378
+
379
+ def main(argv=None):
380
+ ap = argparse.ArgumentParser(
381
+ description="Undo what /install-wizard wrote (dry run unless --apply). Machine-wide: the ~/.zshrc block and "
382
+ "the FH clone's hooks and core.hooksPath go too, not only --project.",
383
+ epilog="exit: 0 no recognised FH trace left · 1 something FH-like is LEFT (listed) for a human look · "
384
+ "10 could not read something it needed · 11 bad arguments")
385
+ ap.add_argument("--project", default=os.getcwd(), help="project the wizard ran in (default: cwd)")
386
+ ap.add_argument("--fh-dir", default=os.environ.get("FH_DIR") or os.path.dirname(os.path.dirname(
387
+ os.path.abspath(__file__))), help="FH clone/package (default: $FH_DIR, else this script's repo)")
388
+ ap.add_argument("--home", default=os.path.expanduser("~"), help="home directory to clean (default: ~)")
389
+ ap.add_argument("--apply", action="store_true", help="carry out the plan (default: print it, change nothing)")
390
+ ap.add_argument("--plugin", action="store_true",
391
+ help="also uninstall fh-meta@forge-harness and remove the forge-harness marketplace entry")
392
+ try:
393
+ a = ap.parse_args(argv)
394
+ except SystemExit as e:
395
+ return 11 if e.code else 0
396
+ proj = os.path.abspath(a.project)
397
+ fh = os.path.abspath(a.fh_dir)
398
+ plan = Plan(a.apply)
399
+ try:
400
+ cmds, keys = snippet_commands(fh)
401
+ plan_zshrc(plan, a.home)
402
+ seen = set()
403
+ for d in (proj, fh):
404
+ if d in seen:
405
+ continue
406
+ seen.add(d)
407
+ for name in ("settings.json", "settings.local.json"):
408
+ plan_settings(plan, os.path.join(d, ".claude", name), cmds, keys)
409
+ plan_claude_local(plan, d)
410
+ plan_hookspath(plan, fh)
411
+ plan_sentinels(plan, a.home, os.path.basename(proj))
412
+ plan_copies(plan, fh, proj)
413
+ plan_rules_dir(plan, proj)
414
+ if a.plugin:
415
+ plan_plugin(plan)
416
+ except HarnessError as e:
417
+ print("fh-detach: HARNESS-ERROR — %s" % e, file=sys.stderr)
418
+ return 10
419
+ steps = [l for l, _ in plan.actions if l]
420
+ print("fh-detach %s — %d step(s)" % ("APPLY" if a.apply else "DRY RUN (nothing changed; add --apply)", len(steps)))
421
+ for l in steps:
422
+ print(" - " + l)
423
+ if a.apply:
424
+ for label, fn in plan.actions:
425
+ try:
426
+ fn()
427
+ except (OSError, subprocess.CalledProcessError) as e:
428
+ print("fh-detach: HARNESS-ERROR at «%s»: %s" % (label, e), file=sys.stderr)
429
+ return 10
430
+ for n in plan.notes:
431
+ print(" note: " + n)
432
+ for l in plan.left:
433
+ print(" LEFT (look at it): " + l)
434
+ if not a.plugin:
435
+ print(" plugin: if you installed it, run `claude plugin uninstall fh-meta@forge-harness` (or pass --plugin)")
436
+ if plan.left:
437
+ return 1
438
+ if not a.apply and steps:
439
+ return 0
440
+ return 0
441
+
442
+
443
+ if __name__ == "__main__":
444
+ sys.exit(main())
@@ -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
@@ -14,6 +14,11 @@ WHAT: reads every topic file's frontmatter and the index, and reports
14
14
  · every entry — status, type, age (from `metadata.hits`), distinct days, last hit, index line
15
15
  · cold — non-user, age 1, last hit ≥ --cold-days ago → drop from the INDEX only
16
16
  · promote — age ≥ --promote-age across ≥ 2 distinct days → propose a rule/hook (human approves)
17
+ — only when the body cites at least one evidence anchor; otherwise «promote held»
18
+ · unanchored — feedback/project entries whose body cites no evidence anchor (commit sha · #PR/issue ·
19
+ file path · arXiv id · URL). harness2 (google-research, 2026-10) stores a lesson only with
20
+ a cited run contrast; this is the record-property half of that: present or not, never
21
+ whether the cited thing proves the lesson (judgment stays judgment).
17
22
  · order — user entries in index order, then valid measured entries by age (ties: index
18
23
  order), then the rest in index order; cold entries leave the order. Entries with an
19
24
  error status never drive cold / promote / measured ranking until repaired
@@ -36,6 +41,35 @@ exit: 0 report printed · 2 memory dir or index unreadable (instrument error, ne
36
41
  """
37
42
  import argparse, datetime as dt, json, os, re, sys, urllib.parse
38
43
 
44
+ # Evidence anchors a lesson can cite. A date alone is not an anchor (it says when, not what was measured).
45
+ # Presence is what is reported, never how many (one anchor is enough; double matches do not matter).
46
+ # NOT anchors, by design: [[wiki-links]] to other memories (a relation, not an artifact), bare dates.
47
+ # Round-1/2 review (codex · Gemini Flash, 2026-10-23) set these edges. Stopped at the round cap: a static string
48
+ # matcher does not converge (each round finds new edges) — residuals are listed in the lanes file, not chased.
49
+ _EXT = (r'md|sh|py|js|mjs|cjs|ts|tsx|jsx|json|ya?ml|toml|txt|plist|html|css|rs|go|rb|java|kt|swift|c|h|cpp|hpp|'
50
+ r'sql|lock|cfg|ini|env|xml|csv|ipynb')
51
+ ANCHOR_RES = [
52
+ # commit sha: hex mixing letters and digits, any case, not part of a #colour, UUID or longer word
53
+ re.compile(r'(?<![#\w-])(?=[0-9a-fA-F]*[0-9])(?=[0-9a-fA-F]*[a-fA-F])[0-9a-fA-F]{7,40}(?![\w-])'),
54
+ # commit sha named as such: then all-digit / all-letter hex counts too («commit 1234567», «커밋 deadbeef»)
55
+ re.compile(r'(?:commit|sha|커밋)\s*[:#]?\s*`?[0-9a-fA-F]{7,40}(?![\w-])', re.I),
56
+ # PR / issue: #N (not &#39; entities, not #section-slugs, not «#123456;» CSS) and owner/repo#N
57
+ re.compile(r'(?<![\w&#(])#\d+(?![\w;-])'), # not «(#2)» — a link to a section of the same document
58
+ re.compile(r'[\w.-]+/[\w.-]+#\d+\b'),
59
+ # file path (case-insensitive extension) and the usual extensionless build files
60
+ re.compile(r'[\w./~-]+\.(?:' + _EXT + r')\b', re.I),
61
+ re.compile(r'\b(?:Dockerfile|Makefile|Gemfile|Procfile)\b'),
62
+ re.compile(r'arXiv[: ]?(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?/\d{7})', re.I), # arXiv id (new and legacy)
63
+ re.compile(r'https?://\S+')] # URL
64
+
65
+
66
+ _WIKI = re.compile(r'\[\[[^\]]*\]\]')
67
+
68
+
69
+ def count_anchors(text):
70
+ text = _WIKI.sub(' ', text) # [[x]] / [[x.md]] is a relation to another memory, never an anchor
71
+ return sum(len(r.findall(text)) for r in ANCHOR_RES) # URL
72
+
39
73
  def link_dests(line):
40
74
  """Markdown inline-link destinations with their start offset: <...> form, balanced parens, title dropped."""
41
75
  out, i = [], 0
@@ -76,7 +110,7 @@ def indent(line):
76
110
 
77
111
  def parse_entry(path, today):
78
112
  """-> dict(status, type, hits[(date,str)], bad[str])"""
79
- out = {'status': 'OK', 'type': None, 'hits': [], 'bad': []}
113
+ out = {'status': 'OK', 'type': None, 'hits': [], 'bad': [], 'anchors': 0}
80
114
  try:
81
115
  text = open(path, encoding='utf-8').read()
82
116
  except (OSError, UnicodeDecodeError) as e:
@@ -88,11 +122,13 @@ def parse_entry(path, today):
88
122
  out['status'] = 'NO_FRONTMATTER'
89
123
  return out
90
124
  try:
91
- end = next(i for i in range(1, len(lines)) if lines[i].strip() == '---')
125
+ end = next(i for i in range(1, len(lines)) if lines[i].rstrip() == '---')
92
126
  except StopIteration:
93
127
  out['status'] = 'UNTERMINATED_FRONTMATTER'
94
128
  return out
95
129
  fm = lines[1:end]
130
+ body = "\n".join(lines[end + 1:])
131
+ out['anchors'] = count_anchors(body)
96
132
  meta_i = next((i for i, l in enumerate(fm) if indent(l) == 0 and re.match(r'^metadata:\s*$', l)), None)
97
133
  if meta_i is None:
98
134
  return out
@@ -143,6 +179,7 @@ def parse_entry(path, today):
143
179
  out['hits'].append((d.isoformat(), m.group(2)))
144
180
  if out['bad'] and out['status'] == 'OK':
145
181
  out['status'] = 'HITS_MALFORMED'
182
+ out['anchors'] += count_anchors("\n".join(t for _, t in out['hits'])) # a hit line may cite the evidence
146
183
  return out
147
184
 
148
185
 
@@ -199,7 +236,7 @@ def main():
199
236
  entries = []
200
237
  for n in names:
201
238
  p = parse_entry(os.path.join(a.memory_dir, n), today)
202
- e = {'file': n, 'status': p['status'], 'type': p['type'], 'bad': p['bad'],
239
+ e = {'file': n, 'status': p['status'], 'type': p['type'], 'bad': p['bad'], 'anchors': p['anchors'],
203
240
  'index_line': pos.get(n, {}).get('line'), 'index_ord': pos.get(n, {}).get('ord'),
204
241
  'past_cap': pos.get(n, {}).get('past_cap', False)}
205
242
  if p['hits']:
@@ -215,8 +252,11 @@ def main():
215
252
  ok = lambda e: e['status'] == 'OK'
216
253
  cold = [e for e in entries if ok(e) and e['type'] != 'user' and e['age'] == 1
217
254
  and days_since(e['last_hit']) >= a.cold_days]
218
- promote = [e for e in entries if ok(e) and e['age'] is not None and e['age'] >= a.promote_age
219
- and e['distinct_days'] >= 2]
255
+ due = [e for e in entries if ok(e) and e['age'] is not None and e['age'] >= a.promote_age
256
+ and e['distinct_days'] >= 2]
257
+ promote = [e for e in due if e['anchors'] > 0]
258
+ promote_held = [e for e in due if e['anchors'] == 0] # recurring, but cites nothing to promote on
259
+ unanchored = [e for e in entries if ok(e) and e['type'] in ('feedback', 'project') and e['anchors'] == 0]
220
260
  cold_set = {e['file'] for e in cold}
221
261
  listed = sorted((e for e in entries if e['index_line'] is not None), key=lambda e: e['index_ord'])
222
262
  users = [e for e in listed if e['type'] == 'user']
@@ -234,6 +274,8 @@ def main():
234
274
  'errors': [[e['file'], e['status'], e['bad']] for e in entries if e['status'] != 'OK'],
235
275
  'cold': [e['file'] for e in cold],
236
276
  'promote': [[e['file'], e['age'], e['distinct_days']] for e in promote],
277
+ 'promote_held': [[e['file'], e['age'], e['distinct_days']] for e in promote_held],
278
+ 'unanchored': [e['file'] for e in unanchored],
237
279
  'order': order, 'entries': entries}
238
280
  if a.json:
239
281
  print(json.dumps(rep, ensure_ascii=False, indent=1))
@@ -259,6 +301,14 @@ def main():
259
301
  print(f" promote candidates (age ≥ {a.promote_age} over ≥ 2 days → propose rule/hook, human approves): {len(promote)}")
260
302
  for e in promote:
261
303
  print(f" promote {e['file']} age {e['age']} · days {e['distinct_days']} · last {e['last_hit']}")
304
+ print(f" promote held (recurs, but the body cites no evidence anchor — add one before proposing): {len(promote_held)}")
305
+ for e in promote_held:
306
+ print(f" held {e['file']} age {e['age']} · days {e['distinct_days']} · last {e['last_hit']}")
307
+ print(f" unanchored feedback/project (no commit · #PR · file · arXiv · URL in the body): {len(unanchored)}")
308
+ for e in unanchored[:20]:
309
+ print(f" unanchored {e['file']}")
310
+ if len(unanchored) > 20:
311
+ print(f" … {len(unanchored) - 20} more (--json lists all)")
262
312
  print(f" proposed order ({len(order)}):")
263
313
  for n, f in enumerate(order, 1):
264
314
  print(f" {n:>3}. {f}")