@chrono-meta/fh-gate 3.20.1 → 3.22.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 (36) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/CATALOG.md +5 -0
  3. package/CLAUDE.md +67 -283
  4. package/knowledge/shared/dialogue/claude_code_runtime_flow.md +1 -0
  5. package/knowledge/shared/harness-core/checkout_layer_drift.md +28 -0
  6. package/knowledge/shared/harness-core/claude_md_gate_details.md +343 -0
  7. package/knowledge/shared/harness-core/dispatch_conditional_prohibition.md +89 -0
  8. package/knowledge/shared/harness-core/fh_detail_protocols.md +88 -0
  9. package/knowledge/shared/harness-core/fh_three_layer_canon.md +49 -0
  10. package/knowledge/shared/harness-core/field_verdict_crossfamily_gate.md +29 -0
  11. package/knowledge/shared/harness-core/hook_channel_visibility.md +80 -0
  12. package/knowledge/shared/harness-core/measurement-integrity-checklist.md +9 -0
  13. package/knowledge/shared/learnings/subagent_invocations_log.yaml +39 -0
  14. package/knowledge/shared/rules/operations.md +7 -0
  15. package/package.json +8 -1
  16. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  18. package/plugins/fh-meta/CHANGELOG.md +36 -0
  19. package/plugins/fh-meta/skills/goal-quench/SKILL.md +1 -1
  20. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  21. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  22. package/scripts/fh_node_check.sh +4 -1
  23. package/scripts/fh_session_load.sh +55 -0
  24. package/scripts/hook_drift_check.sh +188 -0
  25. package/scripts/selfcheck.sh +71 -0
  26. package/scripts/session_close_check.sh +44 -7
  27. package/scripts/session_config_fingerprint.sh +139 -0
  28. package/scripts/sidecar_calibrate.sh +168 -13
  29. package/scripts/test_claude_md_size_lanes.sh +74 -0
  30. package/scripts/test_fh_audit_check_lanes.sh +140 -0
  31. package/scripts/test_hook_drift_lanes.sh +143 -0
  32. package/scripts/test_ollama_panel_lanes.sh +69 -10
  33. package/scripts/test_session_config_fingerprint_lanes.sh +116 -0
  34. package/scripts/test_session_load_mirror_fp_lanes.sh +122 -0
  35. package/scripts/test_subagent_tally_hook_lanes.sh +11 -7
  36. package/templates/.claude/rules/mcp_tool_gating.md +17 -1
@@ -268,19 +268,138 @@ OLLAMA_HOST_URL="${FH_OLLAMA_HOST:-http://127.0.0.1:11434}"
268
268
  # carry a verdict". At 512 the same model answered `PASS`. Budget starvation and incapacity are
269
269
  # different findings and must not be reported as one.
270
270
  OLLAMA_NUM_PREDICT="${FH_OLLAMA_NUM_PREDICT:-512}"
271
+ # Per-model generate deadline (seconds). Overridable so the lanes can drive a mid-body stall without
272
+ # waiting four minutes; the default is unchanged.
273
+ OLLAMA_GEN_TIMEOUT="${FH_OLLAMA_GEN_TIMEOUT:-240}"
274
+
275
+ # _http <max-secs> <url> [json-body] — one request, and it KEEPS THE STATUS CODE.
276
+ # Sets HTTP_CODE (000 when no HTTP answer came back at all), HTTP_BODY, HTTP_RC (curl's own rc).
277
+ #
278
+ # 🟥 WHY NOT `curl -sf` (2026-09-24, Glimmer G1): `-f` throws the body away on ANY 4xx/5xx and prints
279
+ # nothing, so «the node answered "invalid model name"» and «no node answered» both reached the
280
+ # caller as the same empty string — and the empty string was rendered UNREACHABLE-THIS-RUN with
281
+ # «(measured, not inferred)» after it. What had been measured was the empty string, not reachability.
282
+ # Those two point the operator in opposite directions (network vs. name/inventory), so they must
283
+ # never share a label. Body and code travel together through one capture; the code is split off
284
+ # the LAST line — no pipe, so no rc is dropped on the way (pipefail class lock).
285
+ _http() {
286
+ local secs="$1" url="$2" data="${3:-}" raw
287
+ if [ -n "$data" ]; then
288
+ raw="$(curl -s --max-time "$secs" -w '\n%{http_code}' "$url" -d "$data" 2>/dev/null)"; HTTP_RC=$?
289
+ else
290
+ raw="$(curl -s --max-time "$secs" -w '\n%{http_code}' "$url" 2>/dev/null)"; HTTP_RC=$?
291
+ fi
292
+ HTTP_CODE="${raw##*$'\n'}"
293
+ case "$raw" in *$'\n'*) HTTP_BODY="${raw%$'\n'*}" ;; *) HTTP_BODY="" ;; esac
294
+ case "$HTTP_CODE" in [0-9][0-9][0-9]) : ;; *) HTTP_CODE="000" ;; esac
295
+ }
296
+
297
+ # _http_why — human reason for HTTP_CODE=000, from curl's rc. Only the common three are named; any
298
+ # other rc is printed as a number rather than guessed at.
299
+ _http_why() {
300
+ case "$HTTP_RC" in
301
+ 7) echo "connection refused" ;;
302
+ 28) echo "timed out" ;;
303
+ 52) echo "empty reply — connection closed without an HTTP answer" ;;
304
+ 6) echo "host not resolved" ;;
305
+ *) echo "curl rc=$HTTP_RC" ;;
306
+ esac
307
+ }
308
+
309
+ # _err_summary — the server's own words for a non-200: the JSON `error` field when there is one,
310
+ # else the first 80 chars of the raw body. One line, no parentheses (they close the label).
311
+ _err_summary() {
312
+ local s
313
+ s="$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys
314
+ try: d=json.load(sys.stdin); e=d.get("error","") if isinstance(d,dict) else ""
315
+ except Exception: e=""
316
+ print(e if isinstance(e,str) else json.dumps(e))' 2>/dev/null)"
317
+ [ -n "$s" ] || s="$HTTP_BODY"
318
+ s="$(printf '%s' "$s" | tr '\r\n()' ' []' | cut -c1-80)"
319
+ [ -n "$s" ] || s="empty body"
320
+ printf '%s' "$s"
321
+ }
271
322
 
272
323
  probe_ollama() {
273
324
  command -v curl >/dev/null 2>&1 || { echo "ollama ABSENT — curl missing (absence measured)"; return 0; }
274
- curl -sf --max-time 10 "$OLLAMA_HOST_URL/api/version" >/dev/null 2>&1 || {
275
- printf 'ollama ABSENT — no server at the configured host (absence measured, not assumed)\n'
325
+ _http 10 "$OLLAMA_HOST_URL/api/version"
326
+ if [ "$HTTP_CODE" = "000" ]; then
327
+ printf 'ollama ABSENT — no server at the configured host (%s; absence measured, not assumed)\n' "$(_http_why)"
276
328
  printf ' set FH_OLLAMA_HOST to probe a remote node; default is loopback\n'
277
329
  return 0
278
- }
330
+ fi
331
+ if [ "$HTTP_RC" -ne 0 ]; then
332
+ # An answer started (http code present) but did not finish — nothing about the host was measured.
333
+ printf 'ollama UNMEASURED — /api/version answered http %s but the transfer did not complete (%s)\n' "$HTTP_CODE" "$(_http_why)"
334
+ return 0
335
+ fi
336
+ if [ "$HTTP_CODE" != "200" ]; then
337
+ # Something IS listening — it just is not answering as an Ollama server. Not ABSENT.
338
+ printf 'ollama HOST-ERROR — something answered at the configured host, but /api/version returned http %s: %s\n' \
339
+ "$HTTP_CODE" "$(_err_summary)"
340
+ printf ' a server was reached, so this is not absence; check that FH_OLLAMA_HOST points at Ollama\n'
341
+ return 0
342
+ fi
343
+ # 🟥 «Any 200» is not «an Ollama server» (cross-family review, 2026-09-26). A host that answers
344
+ # 200 to everything and echoes the pinned name back in a generate envelope would otherwise reach
345
+ # PIN-OK(envelope) and JOIN THE PANEL — the envelope anchor is only a server-side fact if the
346
+ # server is the one we think it is. Require the Ollama shape: a JSON object with a string
347
+ # `version`. Anything else is HOST-ERROR and the leg stops.
348
+ if ! printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys
349
+ d=json.load(sys.stdin)
350
+ raise SystemExit(0 if isinstance(d,dict) and isinstance(d.get("version"),str) and d["version"] else 1)' >/dev/null 2>&1; then
351
+ printf 'ollama HOST-ERROR — /api/version returned http 200 but not the Ollama shape {"version": "..."}: %s\n' "$(_err_summary)"
352
+ printf ' something answered, but it is not recognisably Ollama — nothing from this host enters the panel\n'
353
+ return 0
354
+ fi
279
355
 
356
+ # ── FH_OLLAMA_MODELS: comma-separated. Whitespace around an item is trimmed; whitespace INSIDE an
357
+ # item is REJECTED, not normalised. Chosen deliberately (2026-09-24 G1):
358
+ # · Ollama model names cannot contain whitespace, so an inner space means the caller used a
359
+ # different separator contract. Normalising would mean the calibrator GUESSING the input it
360
+ # was given — and a marker quotes this run's output, so "a b" and "a,b" would become
361
+ # indistinguishable in the record, hiding the contract drift that caused the incident.
362
+ # · Trimming "a, b" is not a guess — the commas are there, only padding is removed.
363
+ # · The cost of rejecting is one loud, cheap rephrase (the message prints the corrected value);
364
+ # the cost of guessing is silent. Exit stays 0 — detector, not gate.
280
365
  local models="${FH_OLLAMA_MODELS:-}"
281
- if [ -z "$models" ]; then
282
- models=$(curl -sf --max-time 15 "$OLLAMA_HOST_URL/api/tags" 2>/dev/null \
283
- | python3 -c 'import json,sys
366
+ if [ -n "$models" ]; then
367
+ local cleaned="" item bad="" IFS=,
368
+ for item in $models; do
369
+ item="$(printf '%s' "$item" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//')"
370
+ [ -n "$item" ] || continue
371
+ case "$item" in *[[:space:]]*) bad="$item" ;; esac
372
+ cleaned="${cleaned:+$cleaned,}$item"
373
+ done
374
+ if [ -z "$cleaned" ]; then
375
+ # Explicitly set, but nothing survives trimming. Falling through to /api/tags would probe
376
+ # models the caller never named; staying silent would read as "no models".
377
+ printf 'ollama INPUT-ERROR — FH_OLLAMA_MODELS is set but has no model names after trimming: "%s"\n' "$models"
378
+ printf ' unset it to probe the listed models, or give a comma-separated list. Nothing was probed.\n'
379
+ return 0
380
+ fi
381
+ if [ -n "$bad" ]; then
382
+ printf 'ollama INPUT-ERROR — FH_OLLAMA_MODELS item contains whitespace: "%s"\n' "$bad"
383
+ printf ' the separator is a COMMA; model names cannot contain spaces. Nothing was probed.\n'
384
+ printf ' did you mean: FH_OLLAMA_MODELS="%s"\n' "$(printf '%s' "$cleaned" | tr -s '[:space:]' ',')"
385
+ return 0
386
+ fi
387
+ models="$cleaned"
388
+ else
389
+ _http 15 "$OLLAMA_HOST_URL/api/tags"
390
+ if [ "$HTTP_CODE" != "200" ] || [ "$HTTP_RC" -ne 0 ]; then
391
+ # A failed listing is not an empty listing. And a tags call that got no HTTP answer did not
392
+ # measure reachability either — say only what was measured.
393
+ if [ "$HTTP_CODE" = "000" ]; then
394
+ printf 'ollama model list UNMEASURED (tags call got no HTTP answer: %s) — not empty\n' "$(_http_why)"
395
+ elif [ "$HTTP_RC" -ne 0 ]; then
396
+ printf 'ollama model list UNMEASURED (tags call answered http %s but did not complete: %s) — not empty\n' "$HTTP_CODE" "$(_http_why)"
397
+ else
398
+ printf 'ollama REACHABLE but /api/tags returned http %s: %s — model list UNMEASURED, not empty\n' "$HTTP_CODE" "$(_err_summary)"
399
+ fi
400
+ return 0
401
+ fi
402
+ models=$(printf '%s' "$HTTP_BODY" | python3 -c 'import json,sys
284
403
  try: d=json.load(sys.stdin)
285
404
  except Exception: raise SystemExit
286
405
  print(",".join(m["name"] for m in d.get("models",[])[:6]))' 2>/dev/null)
@@ -289,10 +408,21 @@ print(",".join(m["name"] for m in d.get("models",[])[:6]))' 2>/dev/null)
289
408
 
290
409
  # Control runs ONCE per host, not per model: it is a property of the server, and repeating it per
291
410
  # model would just multiply the cost of a fact that cannot differ.
292
- local ctl ctl_state
293
- ctl=$(curl -s --max-time 20 "$OLLAMA_HOST_URL/api/generate" \
294
- -d '{"model":"fh-calib-nonexistent:99b","prompt":"hi","stream":false}' 2>&1)
295
- if printf '%s' "$ctl" | grep -qiE '"error"|not found'; then ctl_state="rejects-bogus"; else ctl_state="accepts-bogus"; fi
411
+ # 🟥 A control that got NO answer is unmeasured — it was previously read as "accepts-bogus"
412
+ # because an empty body contains no "error". Silence is not acceptance.
413
+ local ctl_state
414
+ _http 20 "$OLLAMA_HOST_URL/api/generate" '{"model":"fh-calib-nonexistent:99b","prompt":"hi","stream":false}'
415
+ # 🟥 Only a 4xx is evidence of rejection. A 5xx is the server FAILING, which says nothing about
416
+ # whether it would have validated the name; 000 and an incomplete transfer measured nothing.
417
+ # All three are `unmeasured` (cross-family review, 2026-09-26: 5xx was read as rejects-bogus).
418
+ case "$HTTP_CODE" in
419
+ 4[0-9][0-9]) ctl_state="rejects-bogus" ;;
420
+ 200)
421
+ if printf '%s' "$HTTP_BODY" | grep -qiE '"error"|not found'; then ctl_state="rejects-bogus"
422
+ else ctl_state="accepts-bogus"; fi ;;
423
+ *) ctl_state="unmeasured" ;;
424
+ esac
425
+ [ "$HTTP_RC" -ne 0 ] && ctl_state="unmeasured"
296
426
 
297
427
  local IFS=,
298
428
  for m in $models; do
@@ -305,10 +435,35 @@ print(",".join(m["name"] for m in d.get("models",[])[:6]))' 2>/dev/null)
305
435
  local body out env_model resp compact pin v
306
436
  body=$(python3 -c 'import json,sys; print(json.dumps({"model":sys.argv[1],"prompt":sys.argv[2],"stream":False,"options":{"num_predict":int(sys.argv[3]),"temperature":0}}))' \
307
437
  "$m" "$VERDICT_PROMPT" "$OLLAMA_NUM_PREDICT")
308
- out=$(curl -sf --max-time 240 "$OLLAMA_HOST_URL/api/generate" -d "$body" 2>/dev/null)
309
- if [ -z "$out" ]; then
310
- printf 'ollama %-22s UNREACHABLE-THIS-RUN (measured, not inferred)\n' "$m"; continue
438
+ _http "$OLLAMA_GEN_TIMEOUT" "$OLLAMA_HOST_URL/api/generate" "$body"
439
+ # 🟥 A status line is not a completed answer. If curl failed AFTER the headers (timeout mid-body,
440
+ # connection reset), HTTP_CODE can read 200 while HTTP_BODY is whatever arrived — possibly a
441
+ # complete-looking JSON that would parse to PIN-OK and join the panel. rc≠0 wins over the code.
442
+ if [ "$HTTP_RC" -ne 0 ] && [ "$HTTP_CODE" != "000" ]; then
443
+ printf 'ollama %-22s UNMEASURED-THIS-RUN (http %s but the transfer did not complete: %s) — not in the panel\n' "$m" "$HTTP_CODE" "$(_http_why)"
444
+ continue
311
445
  fi
446
+ # Three different events, three different labels — never collapse them again:
447
+ # 000 → no HTTP answer at all → UNREACHABLE-THIS-RUN (this one IS about the network)
448
+ # 4xx → the server answered and refused → MODEL-ERROR(<its words>) — name / inventory problem
449
+ # 5xx → the server answered and failed → SERVER-ERROR(<its words>) — load / OOM / runtime
450
+ # None of them joins the panel, and none of them is PIN-OK or UNTRUSTED-PIN: nothing was served.
451
+ case "$HTTP_CODE" in
452
+ 000)
453
+ printf 'ollama %-22s UNREACHABLE-THIS-RUN (%s — no HTTP answer to the generate call)\n' "$m" "$(_http_why)"
454
+ continue ;;
455
+ 4[0-9][0-9])
456
+ printf 'ollama %-22s MODEL-ERROR(%s) · control: %s\n' "$m" "$(_err_summary)" "$ctl_state"
457
+ printf ' the server WAS reached and answered http %s — check the model name and this node'"'"'s\n' "$HTTP_CODE"
458
+ printf ' inventory, not the network. Not in the panel: no model was served.\n'
459
+ continue ;;
460
+ 200) : ;;
461
+ *)
462
+ printf 'ollama %-22s SERVER-ERROR(http %s: %s) · control: %s\n' "$m" "$HTTP_CODE" "$(_err_summary)" "$ctl_state"
463
+ printf ' the server WAS reached but failed to serve (load / memory / runtime). Not in the panel.\n'
464
+ continue ;;
465
+ esac
466
+ out="$HTTP_BODY"
312
467
  env_model=$(printf '%s' "$out" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("model",""))' 2>/dev/null)
313
468
  resp=$(printf '%s' "$out" | python3 -c 'import json,sys; print((json.load(sys.stdin).get("response") or "").strip())' 2>/dev/null)
314
469
  compact=$(printf '%s' "$resp" | tr -s '[:space:]' ' ' | sed 's/^ *//; s/ *$//')
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env bash
2
+ # test_claude_md_size_lanes.sh — CLAUDE.md 크기 가드 (2026-09-26 신설).
3
+ #
4
+ # 왜: Claude Code 는 세션 시작 시 CLAUDE.md 가 150.0k **문자**를 넘으면
5
+ # `⚠ CLAUDE.md is over the 150.0k-char limit` 경고를 띄운다. 허브 CLAUDE.md 는 tracked·출하 파일이라
6
+ # README 주 경로(git clone)로 들어온 모든 사용자가 그 경고를 본다(v3.16.0~v3.21.0 실측: 150,733 → 154,149).
7
+ # 파일은 주당 ~1k 씩 자라므로, 경고가 뜨기 **전에** 이 레인이 빨개지도록 한계를 145,000 으로 둔다.
8
+ # 무엇을 세나: Python `len()` 을 UTF-8 디코드한 텍스트에 건다 = **문자 수**(바이트 아님). CC 경고가 문자를
9
+ # 세므로 같은 단위다. `wc -c` 는 바이트라 한글 한 글자를 3 으로 세어 과차단한다(L4 가 그 차이를 박는다).
10
+ # 처방: 빨개지면 지우지 말고 **옮겨라** — 근거·실측·철회 경위를 detail 파일로 verbatim 이관하고 상주에는
11
+ # 규칙 + 포인터만 남긴다(선례: tracks/_meta/claude_md_diet_2026-09-26/ 의 diet.py·verify.py).
12
+ set -uo pipefail
13
+ HERE="$(cd "$(dirname "$0")" && pwd)"; ROOT="$(cd "$HERE/.." && pwd)"
14
+ LIMIT=145000
15
+ PASS=0; FAIL=0
16
+ ok(){ PASS=$((PASS+1)); printf ' ✅ %s\n' "$1"; }
17
+ no(){ FAIL=$((FAIL+1)); printf ' ❌ %s — %s\n' "$1" "${2:-}"; }
18
+
19
+ # size_check <file> <limit> → prints the char count; rc 0 = within, 1 = over, 2 = cannot measure.
20
+ size_check() {
21
+ python3 - "$1" "$2" <<'PY'
22
+ import sys
23
+ path, limit = sys.argv[1], int(sys.argv[2])
24
+ try:
25
+ n = len(open(path, encoding="utf-8").read())
26
+ except (OSError, UnicodeDecodeError) as e:
27
+ print(f"UNMEASURED: {e}"); sys.exit(2)
28
+ print(n); sys.exit(0 if n <= limit else 1)
29
+ PY
30
+ }
31
+
32
+ echo "── test_claude_md_size_lanes (limit ${LIMIT} chars) ──"
33
+ command -v python3 >/dev/null 2>&1 || { no "L0 환경" "python3 없음 — 레인 미측정(통과 아님)"; echo "PASS=$PASS FAIL=$FAIL"; echo "FAILED=1"; exit 1; }
34
+ D="$(mktemp -d 2>/dev/null)" || D=""
35
+ [ -n "$D" ] && [ -w "$D" ] || { no "L0 환경" "mktemp -d 불가 — 레인 미측정(통과 아님)"; echo "PASS=$PASS FAIL=$FAIL"; echo "FAILED=1"; exit 1; }
36
+ trap 'rm -rf "$D"' EXIT
37
+
38
+ # L2 known-positive: 150k ASCII chars (the CC warning line) must FAIL.
39
+ python3 -c 'import sys; open(sys.argv[1],"w",encoding="utf-8").write("a"*150000)' "$D/big.md"
40
+ OUT=$(size_check "$D/big.md" "$LIMIT"); RC=$?
41
+ [ "$RC" -eq 1 ] && ok "L2 known-positive: 150,000자 → FAIL (rc=1, count=$OUT)" || no "L2 known-positive" "rc=$RC out=$OUT — 가드가 죽었다"
42
+
43
+ # L3 known-negative: small file must PASS.
44
+ printf '# small\n' > "$D/small.md"
45
+ OUT=$(size_check "$D/small.md" "$LIMIT"); RC=$?
46
+ [ "$RC" -eq 0 ] && ok "L3 known-negative: 작은 파일 → PASS" || no "L3 known-negative" "rc=$RC out=$OUT"
47
+
48
+ # L4 unit = characters, not bytes: 100,000 Hangul chars = 300,000 bytes must PASS.
49
+ python3 -c 'import sys; open(sys.argv[1],"w",encoding="utf-8").write("가"*100000)' "$D/ko.md"
50
+ OUT=$(size_check "$D/ko.md" "$LIMIT"); RC=$?; BYTES=$(wc -c < "$D/ko.md" | tr -d ' ')
51
+ [ "$RC" -eq 0 ] && [ "$OUT" = "100000" ] && [ "$BYTES" -gt "$LIMIT" ] \
52
+ && ok "L4 단위 = 문자: 한글 100,000자(${BYTES} bytes) → PASS" || no "L4 단위" "rc=$RC chars=$OUT bytes=$BYTES — 바이트를 세고 있다"
53
+
54
+ # L5 boundary: exactly LIMIT passes, LIMIT+1 fails.
55
+ python3 -c 'import sys; open(sys.argv[1],"w",encoding="utf-8").write("a"*int(sys.argv[2]))' "$D/eq.md" "$LIMIT"
56
+ python3 -c 'import sys; open(sys.argv[1],"w",encoding="utf-8").write("a"*(int(sys.argv[2])+1))' "$D/p1.md" "$LIMIT"
57
+ size_check "$D/eq.md" "$LIMIT" >/dev/null; R1=$?; size_check "$D/p1.md" "$LIMIT" >/dev/null; R2=$?
58
+ [ "$R1" -eq 0 ] && [ "$R2" -eq 1 ] && ok "L5 경계: ${LIMIT} PASS · $((LIMIT+1)) FAIL" || no "L5 경계" "eq rc=$R1 +1 rc=$R2"
59
+
60
+ # L6 absent file is UNMEASURED (rc=2), never a pass.
61
+ OUT=$(size_check "$D/nope.md" "$LIMIT"); RC=$?
62
+ [ "$RC" -eq 2 ] && ok "L6 부재 → UNMEASURED rc=2 (0 으로 접지 않는다)" || no "L6 부재" "rc=$RC out=$OUT"
63
+
64
+ # L1 the real subject: the hub CLAUDE.md.
65
+ if [ ! -f "$ROOT/CLAUDE.md" ]; then
66
+ no "L1 CLAUDE.md" "파일 부재 — 미측정(통과 아님)"
67
+ else
68
+ OUT=$(size_check "$ROOT/CLAUDE.md" "$LIMIT"); RC=$?
69
+ if [ "$RC" -eq 0 ]; then ok "L1 CLAUDE.md = ${OUT}자 ≤ ${LIMIT} (CC 경고선 150,000 까지 $((150000-OUT)))"
70
+ else no "L1 CLAUDE.md" "${OUT}자 > ${LIMIT} — 지우지 말고 detail 파일로 옮겨라(헤더 처방)"; fi
71
+ fi
72
+
73
+ echo "PASS=$PASS FAIL=$FAIL"
74
+ [ "$FAIL" -eq 0 ] || { echo "FAILED=1"; exit 1; }
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env bash
2
+ # Lanes for templates/fh_audit_check.zsh — the terminal «Audit Reminders» banner.
3
+ #
4
+ # Usage: bash scripts/test_fh_audit_check_lanes.sh [NEW_SCRIPT] [ORIG_SCRIPT]
5
+ # NEW_SCRIPT default: templates/fh_audit_check.zsh (the script under test)
6
+ # ORIG_SCRIPT optional: the pre-fix script. When given, every fail-before lane is run against it
7
+ # and MUST emit the false line (proves the fixture reproduces the defect).
8
+ #
9
+ # Never touches the real HOME, ~/.cc_sentinels or ~/.zshrc: every run is `zsh -f` (no rc files)
10
+ # with a fake HOME and fixture dirs under mktemp.
11
+ set -u
12
+ REPO="$(cd "$(dirname "$0")/.." && pwd)"
13
+ NEW="${1:-$REPO/templates/fh_audit_check.zsh}"
14
+ ORIG="${2:-}"
15
+ [ -f "$NEW" ] || { echo "HARNESS-ERROR: script under test not found: $NEW"; exit 3; }
16
+ command -v zsh >/dev/null 2>&1 || { echo "HARNESS-ERROR: zsh not installed"; exit 3; }
17
+
18
+ T="$(mktemp -d "${TMPDIR:-/tmp}/fhaudit.XXXXXX")" || exit 3
19
+ [ -n "$T" ] && [ -d "$T" ] || { echo "HARNESS-ERROR: mktemp"; exit 3; }
20
+ trap 'rm -rf "$T"' EXIT
21
+ PASS=0; FAIL=0
22
+
23
+ # N days ago as a touch -t stamp (BSD date first, GNU fallback — both checked for non-empty)
24
+ ago() { local s; s=$(date -v-"$1"d +%Y%m%d%H%M 2>/dev/null) || s=$(date -d "$1 days ago" +%Y%m%d%H%M 2>/dev/null); [ -n "$s" ] || { echo "HARNESS-ERROR: date"; exit 3; }; echo "$s"; }
25
+ mk() { mkdir -p "$(dirname "$1")"; : > "$1"; touch -t "$(ago "$2")" "$1"; }
26
+
27
+ # banner SCRIPT HUB SENT → stdout+stderr, ANSI stripped. FH_DIR=CC_HUB_DIR=HUB.
28
+ banner() {
29
+ env -i PATH="$PATH" HOME="$T/fakehome" FH_DIR="$2" CC_HUB_DIR="$2" CC_SENTINELS_DIR="$3" \
30
+ zsh -f -c 'source "$1"; _fh_audit_check' _ "$1" 2>&1 | sed $'s/\033\\[[0-9;]*m//g'
31
+ }
32
+ ok() { PASS=$((PASS+1)); echo " PASS $1"; }
33
+ bad() { FAIL=$((FAIL+1)); echo " FAIL $1"; echo "$2" | sed 's/^/ | /'; }
34
+ has() { local o; o=$(banner "$1" "$2" "$3"); if echo "$o" | grep -qF -- "$4"; then ok "$5"; else bad "$5 (expected: $4)" "$o"; fi; }
35
+ hasnt() { local o; o=$(banner "$1" "$2" "$3"); if echo "$o" | grep -qF -- "$4"; then bad "$5 (unexpected: $4)" "$o"; else ok "$5"; fi; }
36
+
37
+ # bannerk: same as banner but the caller shell has KSH_ARRAYS on (as a user's own zshrc might)
38
+ bannerk() {
39
+ env -i PATH="$PATH" HOME="$T/fakehome" FH_DIR="$2" CC_HUB_DIR="$2" CC_SENTINELS_DIR="$3" \
40
+ zsh -f -c 'setopt KSH_ARRAYS; source "$1"; _fh_audit_check' _ "$1" 2>&1 | sed $'s/\033\\[[0-9;]*m//g'
41
+ }
42
+ hasntk() { local o; o=$(bannerk "$1" "$2" "$3"); if echo "$o" | grep -qF -- "$4"; then bad "$5 (unexpected: $4)" "$o"; else ok "$5"; fi; }
43
+ hub() { local h="$T/$1"; mkdir -p "$h/tracks/_meta" "$h/tracks/_audit" "$h/knowledge/shared/harness-core"; mkdir -p "$T/$1.sent"; echo "$h"; }
44
+
45
+ # ── fixtures ────────────────────────────────────────────────────────────────
46
+ # F1: weekly audit 2d old, no harvest_* (the operator's real shape) — nothing is overdue
47
+ F1=$(hub f1); mk "$F1/tracks/_audit/weekly_audit_x.md" 2; mk "$F1/tracks/_meta/frontier_digest_x.md" 1; mk "$F1/tracks/_meta/sim_x_area_B.md" 3
48
+ # F2: weekly audit genuinely overdue (10d)
49
+ F2=$(hub f2); mk "$F2/tracks/_audit/weekly_audit_x.md" 10; mk "$F2/tracks/_meta/frontier_digest_x.md" 1; mk "$F2/tracks/_meta/sim_x_area_B.md" 3
50
+ # F3: no weekly audit at all
51
+ F3=$(hub f3); mk "$F3/tracks/_meta/frontier_digest_x.md" 1; mk "$F3/tracks/_meta/sim_x_area_B.md" 3
52
+ # F4: Area B 40d old but a recent area_D report (2d) — old glob resets the B clock
53
+ F4=$(hub f4); mk "$F4/tracks/_audit/weekly_audit_x.md" 1; mk "$F4/tracks/_meta/sim_x_area_B.md" 40; mk "$F4/tracks/_meta/sim_y_area_D_split.md" 2
54
+ # F5: Area B 116d (the operator's real shape — a TRUE alarm)
55
+ F5=$(hub f5); mk "$F5/tracks/_audit/weekly_audit_x.md" 1; mk "$F5/tracks/_meta/sim_x_area_BD.md" 116
56
+ # F6: sentinels — 4 state markers + 1 genuine custom audit sentinel, all past 90d
57
+ F6=$(hub f6); S6="$T/f6.sent"; mk "$F6/tracks/_audit/weekly_audit_x.md" 1; mk "$F6/tracks/_meta/sim_x_area_B.md" 3
58
+ mk "$S6/projA_mapping_skipped" 100; mk "$S6/projB_wizard_done" 121; mk "$S6/projC_wizard_declined" 100
59
+ mk "$S6/projD_wizard_reminder_muted" 100; mk "$S6/myproj_pfd" 100
60
+ # F7: empty sentinels dir (zsh unmatched-glob error class)
61
+ F7=$(hub f7); S7="$T/f7.sent"; mk "$F7/tracks/_audit/weekly_audit_x.md" 1; mk "$F7/tracks/_meta/sim_x_area_B.md" 3
62
+ # F8: frontier — only an old diagnosis file (100d), a fresh digest (1d)
63
+ F8=$(hub f8); mk "$F8/tracks/_audit/weekly_audit_x.md" 1; mk "$F8/tracks/_meta/sim_x_area_B.md" 3
64
+ mk "$F8/knowledge/shared/harness-core/harness_frontier_diagnosis_x.md" 100; mk "$F8/tracks/_meta/frontier_digest_x.md" 1
65
+ # F10: two weekly audits — newest 1d, older 17d. Under the caller's KSH_ARRAYS a `[1]` index picks the older
66
+ F10=$(hub f10); mk "$F10/tracks/_audit/weekly_audit_old.md" 17; mk "$F10/tracks/_audit/weekly_audit_new.md" 1; mk "$F10/tracks/_meta/frontier_digest_x.md" 1; mk "$F10/tracks/_meta/sim_x_area_B.md" 3
67
+ # F9: frontier digest genuinely overdue (10d)
68
+ F9=$(hub f9); mk "$F9/tracks/_audit/weekly_audit_x.md" 1; mk "$F9/tracks/_meta/sim_x_area_B.md" 3; mk "$F9/tracks/_meta/frontier_digest_x.md" 10
69
+
70
+ # ORIG aborts the whole function on ANY unmatched glob (zsh NOMATCH: `ls -t …diagnosis_*.md` and
71
+ # `for f in dir/*` on an empty dir) — so for a fail-before to test the line it names, the other
72
+ # globs must match. Seed a fresh (1d) diagnosis file and a fresh custom sentinel everywhere except F7.
73
+ for h in f1 f2 f3 f4 f5 f6 f8 f9; do
74
+ [ "$h" = f8 ] || mk "$T/$h/knowledge/shared/harness-core/harness_frontier_diagnosis_seed.md" 1 # F8 keeps ONLY its 100d file
75
+ mk "$T/$h.sent/fresh_pfd" 1
76
+ done
77
+ # control: fixture mtimes actually landed (a dead touch would make every «silent» lane vacuous)
78
+ c=$(( ( $(date +%s) - $(stat -c %Y "$S6/myproj_pfd" 2>/dev/null || stat -f %m "$S6/myproj_pfd") ) / 86400 ))
79
+ echo "control: myproj_pfd fixture age = ${c}d (expect 100)"
80
+ [ "$c" -ge 99 ] && [ "$c" -le 101 ] || { echo "HARNESS-ERROR: fixture mtime did not land"; exit 3; }
81
+
82
+ run_new() {
83
+ local S="$1"
84
+ echo "── ① weekly audit"
85
+ hasnt "$S" "$F1" "$T/f1.sent" "harvest" "L1 fresh weekly audit, no harvest_* → no harvest line"
86
+ hasnt "$S" "$F1" "$T/f1.sent" "weekly_audit" "L1b fresh weekly audit → no weekly line"
87
+ has "$S" "$F2" "$T/f2.sent" "weekly_audit 10d" "L2 KP: weekly audit 10d → warns"
88
+ has "$S" "$F3" "$T/f3.sent" "No weekly audit history" "L3 KP: no weekly audit → warns (not-found ≠ zero)"
89
+ echo "── ② frontier digest"
90
+ hasnt "$S" "$F8" "$T/f8.sent" "frontier" "L8 old diagnosis file, fresh digest → silent"
91
+ has "$S" "$F9" "$T/f9.sent" "frontier_digest 10d" "L9 KP: digest 10d → warns"
92
+ echo "── ③ sim Area B"
93
+ has "$S" "$F4" "$T/f4.sent" "FH internal sim 40d" "L4 area_D run does not reset Area B clock"
94
+ has "$S" "$F5" "$T/f5.sent" "FH internal sim 116d" "L5 KP: Area B 116d → warns (true alarm kept)"
95
+ hasnt "$S" "$F1" "$T/f1.sent" "FH internal sim" "L5b Area B 3d → silent"
96
+ echo "── ④ sentinels"
97
+ for m in projA_mapping_skipped projB_wizard_done projC_wizard_declined projD_wizard_reminder_muted; do
98
+ hasnt "$S" "$F6" "$S6" "$m sentinel" "L6 state marker $m not aged"
99
+ done
100
+ has "$S" "$F6" "$S6" "myproj_pfd sentinel 100d" "L6b KP: custom audit sentinel 100d → warns"
101
+ hasnt "$S" "$F7" "$S7" "no matches found" "L7 empty sentinels dir → no zsh glob error"
102
+ hasntk "$S" "$F10" "$T/f10.sent" "weekly_audit" "L10 caller KSH_ARRAYS does not flip newest→older (emulate -L zsh)"
103
+ }
104
+
105
+ echo "=== script under test: $NEW"
106
+ run_new "$NEW"
107
+
108
+ if [ -n "$ORIG" ]; then
109
+ echo "=== fail-before against ORIG: $ORIG (each MUST reproduce the false/missed line)"
110
+ has "$ORIG" "$F1" "$T/f1.sent" "No harvest history found" "FB① ORIG emits unsatisfiable harvest line on fresh hub"
111
+ has "$ORIG" "$F8" "$T/f8.sent" "frontier_diagnosis 100d" "FB② ORIG ages a file /frontier-digest never writes"
112
+ hasnt "$ORIG" "$F4" "$T/f4.sent" "FH internal sim" "FB③ ORIG misses overdue Area B (area_D reset the clock)"
113
+ has "$ORIG" "$F6" "$S6" "projA_mapping_skipped sentinel" "FB④ ORIG ages a state marker (mapping_skipped)"
114
+ has "$ORIG" "$F6" "$S6" "projB_wizard_done sentinel" "FB④b ORIG ages a state marker (wizard_done)"
115
+ has "$ORIG" "$F7" "$S7" "no matches found" "FB⑤ ORIG raises zsh NOMATCH (empty sentinels dir / no diagnosis file) and aborts"
116
+ fi
117
+
118
+ # ── revert probes: undo ONE fix in a copy → apply-check → run the lane → must go RED → discard ──
119
+ echo "=== revert probes (each mutant must turn its lane red)"
120
+ probe() { # name sed-expr lane-fn
121
+ local m="$T/mutant_$1.zsh"
122
+ sed "$2" "$NEW" > "$m"
123
+ if cmp -s "$m" "$NEW"; then bad "RP-$1 mutant did not apply (sed matched nothing) — HARNESS-ERROR" ""; return; fi
124
+ local before=$FAIL; "$3" "$m" >/dev/null
125
+ if [ "$FAIL" -gt "$before" ]; then FAIL=$before; ok "RP-$1 revert turns lane red"; else bad "RP-$1 revert stayed GREEN — lane is decorative" ""; fi
126
+ rm -f "$m"
127
+ }
128
+ lane1() { hasnt "$1" "$F1" "$T/f1.sent" "weekly audit history" "L1-probe"; }
129
+ lane2() { hasnt "$1" "$F8" "$T/f8.sent" "frontier" "L8-probe"; has "$1" "$F9" "$T/f9.sent" "frontier_digest 10d" "L9-probe"; }
130
+ lane3() { has "$1" "$F4" "$T/f4.sent" "FH internal sim 40d" "L4-probe"; }
131
+ lane4() { hasnt "$1" "$F6" "$S6" "projA_mapping_skipped sentinel" "L6-probe"; }
132
+ probe weekly 's#tracks/_audit"/weekly_audit_\*\.md#tracks/_audit"/harvest_*.md#' lane1
133
+ probe frontier 's#tracks/_meta"/frontier_digest_\*\.md#knowledge/shared/harness-core"/harness_frontier_diagnosis_*.md#' lane2
134
+ probe sim 's#sim_\*_area_B\*\.md#sim_*.md#' lane3
135
+ probe sentinel '/\*_wizard_done|\*_mapping_skipped/d' lane4
136
+ lane5() { hasntk "$1" "$F10" "$T/f10.sent" "weekly_audit" "L10-probe"; }
137
+ probe emulate '/^ emulate -L zsh$/d' lane5
138
+
139
+ echo "=== RESULT: PASS=$PASS FAIL=$FAIL"
140
+ [ "$FAIL" -eq 0 ]
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env bash
2
+ # test_hook_drift_lanes.sh — lanes for scripts/hook_drift_check.sh and its consumer, ④-e of
3
+ # scripts/session_close_check.sh. Fixtures only (mktemp): never reads or writes the operator's
4
+ # real ~/.claude or this repo's gitignored settings.
5
+ #
6
+ # The defect these lanes pin (2026-09-26): ④-e treated «a SubagentStop hook exists» as «the tally
7
+ # is measured». An install still carrying the pre-2026-09-25 INLINE hook passed that test while
8
+ # over-counting. The revert probe at the end puts the presence grep back and requires the lane to
9
+ # go red on exactly that fixture — otherwise this file would be green whether or not the fix exists.
10
+ #
11
+ # Runs under bash 3.2 (/bin/bash) and bash 5.
12
+ set -uo pipefail
13
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+ ROOT="$(cd "$HERE/.." && pwd)"
15
+ SUBJ="$ROOT/scripts/hook_drift_check.sh"
16
+ CLOSE="$ROOT/scripts/session_close_check.sh"
17
+ T="$(mktemp -d 2>/dev/null || mktemp -d -t hookdrift)"
18
+ [ -n "$T" ] && [ -d "$T" ] || { echo "HARNESS-ERROR: mktemp failed"; exit 2; }
19
+ trap 'chmod -R u+rw "$T" 2>/dev/null; rm -rf "$T"' EXIT
20
+ pass=0; fail=0
21
+ chk() { if [ "$1" -eq 0 ]; then echo " ✅ $2"; pass=$((pass+1)); else echo " ❌ $2"; fail=$((fail+1)); fi; }
22
+
23
+ [ -f "$SUBJ" ] || { echo "HARNESS-ERROR: subject missing: $SUBJ"; exit 2; }
24
+ PY="$(command -v python3 2>/dev/null || echo /usr/bin/python3)"
25
+
26
+ mkdir -p "$T/tpl"
27
+ cp "$ROOT"/templates/*.json "$T/tpl/" || { echo "HARNESS-ERROR: cannot copy templates"; exit 2; }
28
+
29
+ # ── fixtures ──
30
+ # (a) CURRENT: the template's own SubagentStop block, byte-for-byte
31
+ "$PY" - "$ROOT/templates/subagent-tally-hook.json" "$T/current.json" <<'PY' || { echo "HARNESS-ERROR: fixture build"; exit 2; }
32
+ import json, sys
33
+ d = json.load(open(sys.argv[1]))
34
+ json.dump({"hooks": d["hooks"]}, open(sys.argv[2], "w"))
35
+ PY
36
+ # (b) STALE: the pre-2026-09-25 inline form (date-only append, no script)
37
+ cat > "$T/old_inline.json" <<'JSON'
38
+ {"hooks":{"SubagentStop":[{"matcher":"","hooks":[{"type":"command","command":"bash -c 'HUB=\"${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel)}\"; T=\"$HUB/tracks/_meta/.subagent_dispatch_tally\"; printf \"%s\\n\" \"$(date +%Y-%m-%d)\" >> \"$T\"; exit 0'","timeout":5}]}]}}
39
+ JSON
40
+ # (c) matcher drift: same command, different matcher
41
+ "$PY" - "$T/current.json" "$T/matcher.json" <<'PY'
42
+ import json, sys
43
+ d = json.load(open(sys.argv[1])); d["hooks"]["SubagentStop"][0]["matcher"] = "general-purpose"
44
+ json.dump(d, open(sys.argv[2], "w"))
45
+ PY
46
+ # (d) unrelated SubagentStop hook only → ABSENT, not STALE (same event is not the same hook)
47
+ echo '{"hooks":{"SubagentStop":[{"matcher":"","hooks":[{"type":"command","command":"echo hi"}]}]}}' > "$T/unrelated.json"
48
+ # (e) malformed JSON → UNKNOWN
49
+ echo '{"hooks": {"SubagentStop": [' > "$T/broken.json"
50
+ # (f) template form AND the old inline form installed side by side — CC runs BOTH, old behaviour lives
51
+ "$PY" - "$T/current.json" "$T/old_inline.json" "$T/both.json" <<'PY'
52
+ import json, sys
53
+ cur = json.load(open(sys.argv[1])); old = json.load(open(sys.argv[2]))
54
+ cur["hooks"]["SubagentStop"][0]["hooks"] += old["hooks"]["SubagentStop"][0]["hooks"]
55
+ json.dump(cur, open(sys.argv[3], "w"))
56
+ PY
57
+ # (g) an installed hook entry with no command — unidentifiable, so not evidence of absence
58
+ echo '{"hooks":{"SubagentStop":[{"matcher":"","hooks":[{"type":"command"}]}]}}' > "$T/nocmd.json"
59
+
60
+ v() { bash "$SUBJ" --settings "$1" --templates "$T/tpl" --only subagent_tally_hook.sh --verdict 2>/dev/null; }
61
+ vr() { bash "$SUBJ" --settings "$1" --templates "$T/tpl" --only subagent_tally_hook.sh --verdict >/dev/null 2>&1; echo $?; }
62
+
63
+ echo "── verdicts (known pair + the two degrade cases) ──"
64
+ [ "$(v "$T/current.json")" = CURRENT ]; chk $? "template-identical hook → CURRENT"
65
+ [ "$(vr "$T/current.json")" = 0 ]; chk $? " … rc 0"
66
+ [ "$(v "$T/old_inline.json")" = STALE ]; chk $? "old inline hook → STALE (the defect: presence grep called this installed)"
67
+ [ "$(vr "$T/old_inline.json")" = 1 ]; chk $? " … rc 1"
68
+ [ "$(v "$T/matcher.json")" = STALE ]; chk $? "same command, different matcher → STALE"
69
+ [ "$(v "$T/unrelated.json")" = ABSENT ]; chk $? "unrelated SubagentStop hook → ABSENT (event match is not identity match)"
70
+ [ "$(v "$T/nonexistent.json")" = ABSENT ]; chk $? "no settings file → ABSENT"
71
+ [ "$(v "$T/broken.json")" = UNKNOWN ]; chk $? "malformed settings → UNKNOWN (not folded into CURRENT)"
72
+ [ "$(vr "$T/broken.json")" = 3 ]; chk $? " … rc 3"
73
+ if [ "$(id -u)" != 0 ]; then
74
+ cp "$T/current.json" "$T/noread.json"; chmod 000 "$T/noread.json"
75
+ [ "$(v "$T/noread.json")" = UNKNOWN ]; chk $? "unreadable settings (mode 000) → UNKNOWN even though its content is CURRENT"
76
+ else
77
+ echo " ⏭️ unreadable lane skipped (running as root — mode 000 is readable; not a pass)"
78
+ fi
79
+ [ "$(bash "$SUBJ" --settings "$T/current.json" --templates "$T/tpl" --only no_such_hook.sh --verdict 2>/dev/null)" = UNKNOWN ]
80
+ chk $? "--only with no matching template entry → UNKNOWN (nothing compared is not CURRENT)"
81
+ [ "$(bash "$SUBJ" --settings "$T/current.json" --templates "$T/empty_tpl" --verdict 2>/dev/null)" = UNKNOWN ]
82
+ chk $? "no templates found → UNKNOWN"
83
+ bash "$SUBJ" --settings "" >/dev/null 2>&1; [ $? -eq 2 ]; chk $? "empty --settings path refused (usage rc 2)"
84
+ tbl=$(bash "$SUBJ" --settings "$T/old_inline.json" --templates "$T/tpl" 2>/dev/null)
85
+ printf '%s\n' "$tbl" | grep -q '^STALE SubagentStop .*re-merge needed'; chk $? "table names the STALE hook and says re-merge"
86
+ printf '%s\n' "$tbl" | grep -q 'MODE_D_ONLY not compared'; chk $? "private-path Mode D block is reported as not compared (not silently dropped)"
87
+
88
+ # ── consumer: ④-e of session_close_check.sh, run on a scratch root ──
89
+ mk_root() { # $1 = root dir, $2 = settings fixture, $3 = close-check script to install
90
+ mkdir -p "$1/scripts" "$1/templates" "$1/.claude"
91
+ cp "$SUBJ" "$1/scripts/"; cp "$3" "$1/scripts/session_close_check.sh"; cp "$T/tpl/"*.json "$1/templates/"
92
+ cp "$2" "$1/.claude/settings.json"
93
+ }
94
+ # capture first, filter second — a pipe here would let the checker's own failure hide behind grep/head
95
+ e_line() { local _o; _o=$(bash "$1/scripts/session_close_check.sh" "$1" 2>&1); awk '/④-e/ && n<3 {print; n++}' <<<"$_o"; }
96
+ echo "── duplicate install · malformed entry (cross-family 2026-09-26) ──"
97
+ [ "$(v "$T/both.json")" = STALE ]; chk $? "template + old inline installed together → STALE (both run; was CURRENT via any())"
98
+ _dup=$(bash "$SUBJ" --settings "$T/both.json" --templates "$T/tpl" --only subagent_tally_hook.sh 2>/dev/null)
99
+ printf '%s\n' "$_dup" | grep -q '중복 설치'
100
+ chk $? " … says duplicate install (remove the old entry)"
101
+ [ "$(v "$T/nocmd.json")" = UNKNOWN ]; chk $? "installed entry without a command → UNKNOWN (형식 불량), not ABSENT"
102
+ # revert probes on the subject itself — each mutation must be confirmed applied, then flip its lane
103
+ sed 's/if exact and len(related) <= 1 and len(exact) == 1:/if exact: # MUTANT-ANY/' "$SUBJ" > "$T/mut_any.sh"
104
+ grep -q 'MUTANT-ANY' "$T/mut_any.sh"; chk $? "revert probe (any): mutation applied"
105
+ [ "$(bash "$T/mut_any.sh" --settings "$T/both.json" --templates "$T/tpl" --only subagent_tally_hook.sh --verdict 2>/dev/null)" = CURRENT ]
106
+ chk $? "revert probe (any): old any() rule calls the duplicate install CURRENT → the STALE lane would be RED"
107
+ sed 's/ if ev in inst_bad:/ if False: # MUTANT-NOBAD/' "$SUBJ" > "$T/mut_bad.sh"
108
+ grep -q 'MUTANT-NOBAD' "$T/mut_bad.sh"; chk $? "revert probe (malformed): mutation applied"
109
+ [ "$(bash "$T/mut_bad.sh" --settings "$T/nocmd.json" --templates "$T/tpl" --only subagent_tally_hook.sh --verdict 2>/dev/null)" = ABSENT ]
110
+ chk $? "revert probe (malformed): without the guard the entry folds to ABSENT → the UNKNOWN lane would be RED"
111
+
112
+ echo "── consumer ④-e ──"
113
+ mk_root "$T/r_old" "$T/old_inline.json" "$CLOSE"
114
+ out=$(e_line "$T/r_old")
115
+ printf '%s\n' "$out" | grep -q 'NOT MEASURED — 옛 훅'; chk $? "old inline hook → ④-e says NOT MEASURED (옛 훅, re-merge)"
116
+ mk_root "$T/r_cur" "$T/current.json" "$CLOSE"
117
+ out=$(e_line "$T/r_cur")
118
+ printf '%s\n' "$out" | grep -q 'NOT MEASURED'; [ $? -ne 0 ]; chk $? "current hook → ④-e measured (control: the lane can go green)"
119
+ mk_root "$T/r_miss" "$T/current.json" "$CLOSE"; rm -f "$T/r_miss/scripts/hook_drift_check.sh"
120
+ out=$(e_line "$T/r_miss")
121
+ printf '%s\n' "$out" | grep -q 'NOT MEASURED — could not determine'; chk $? "checker missing → NOT MEASURED (not a pass)"
122
+
123
+ # ── revert probe: put the presence grep back; the old-inline lane must go RED ──
124
+ echo "── revert probe ──"
125
+ "$PY" - "$CLOSE" "$T/mutant_close.sh" <<'PY'
126
+ import re, sys
127
+ s = open(sys.argv[1], encoding="utf-8").read()
128
+ start = s.index("HOOK_OK=0\nHOOK_STATE=UNKNOWN")
129
+ end = s.index("esac\n", s.index("case \"$HOOK_STATE\" in\n (STALE)")) + len("esac\n")
130
+ mut = ('HOOK_OK=0\nif [ -f "$FH/.claude/settings.json" ]; then\n'
131
+ ' grep -q \'"SubagentStop"\' "$FH/.claude/settings.json" 2>/dev/null && HOOK_OK=1\nfi\n'
132
+ '# MUTANT-PRESENCE-GREP\n')
133
+ open(sys.argv[2], "w", encoding="utf-8").write(s[:start] + mut + s[end:])
134
+ PY
135
+ grep -q 'MUTANT-PRESENCE-GREP' "$T/mutant_close.sh"; chk $? "mutation applied (control for the probe itself)"
136
+ mk_root "$T/r_mut" "$T/old_inline.json" "$T/mutant_close.sh"
137
+ out=$(e_line "$T/r_mut")
138
+ printf '%s\n' "$out" | grep -q 'NOT MEASURED'; [ $? -ne 0 ]
139
+ chk $? "with the presence grep restored, the old inline hook is treated as measured → the consumer lane above would be RED"
140
+
141
+ echo
142
+ if [ "$fail" -eq 0 ]; then echo "HOOK-DRIFT LANES: PASS ($pass/$pass)"; exit 0; fi
143
+ echo "HOOK-DRIFT LANES: FAIL ($fail failed, $pass passed)"; exit 1