@chrono-meta/fh-gate 3.20.1 → 3.21.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.
@@ -11,25 +11,25 @@
11
11
  "plugins": [
12
12
  {
13
13
  "name": "fh-meta",
14
- "version": "3.20.1",
14
+ "version": "3.21.0",
15
15
  "description": "New in 2.2.0: BREAKING (gate): chamber step 6 now reads ACTUAL.md, not BUDGET.md — an in-flight chamber run whose actual cost sits in BUDGET.md blocks until the ACTUAL: line moves to tracks/_chamber/<slug>/ACTUAL.md (the runner prints the path). Why: BUDGET.md's pre-verdict hash IS the ordering witness, and step 6 hard-blocked until that same file changed, so every run that reached COMPLETE necessarily mutated a witnessed artifact and verify returned TAMPERED — the chamber's promotion condition was unsatisfiable by construction, not by strictness. Two roles (immutable witness / post-verdict calibration sink) had collided in one file; each was correct alone, so neither side's code showed the conflict. Also: ko-tech-writer Step 2/4-b scans are now calibration-backed (known-pair fixtures + reproducible command, shipped) — discrimination is proven, 'zero residue' is explicitly NOT; chamber lane suite 12 -> 33 including the runner x witness seam no test covered; chamber_run.sh now teaches the two-commit discipline (gate hashes and verdict hash must land in separate commits/PRs — it previously advised the opposite). New in 2.1.0: BREAKING (gate): `crossfamily: declined` in an Axes 2-3 marker now requires grounds naming a record path that RESOLVES on disk — bare `declined`, and `declined` justified by author judgment, are blocked at commit. Remedy: cite where the operator decision lives (e.g. `.. — operator declined sidecars, per knowledge/shared/rules/operational_adaptation.md`), or use `DEGRADED_PANEL_UNUSED` if a panel was reachable and you chose not to recruit it — which is what author judgment actually is. `declined` was the only enum value with no grounds requirement; a cross-family review then broke the first (vocabulary-grep) fix three ways — self-validating on the value's own token, vacuous keyword passes, and over-blocking real declinations in natural prose — so the check asserts a resolvable record instead of words. Also: standpoint axis gains `tier1b` (a STATIC read of a target repo, executed nothing) plus a decide-in-order procedure, after blind floor-tier sims graded pure cold-reads as `tier2` three rounds running; steel-quench Wave 1's sixth angle (gate-locality) gains the output-template row it never had, so a mandatory angle stops being structurally unreportable; verify-bidirectional gains category 5 (prescriptive doctrine statement); Sister Asset Protocol gains an active-adoption trigger; new resident doctrine — Mechanization Boundary, Local Execution First, Skeleton-not-Muscle, Expedition track, and this package's versioning policy. Hub meta-operations toolkit — 35 skills + 7 agents. New in 2.0.1: harness-doctor cadence hook, portability lint wired into pre-commit, branch_claim.sh claim-count-vs-tree-count warning, louder confidentiality-scan fail-open notice, fh-gate.sh missing-package.json survival, identity ① reclassified 🟢 (cross-harness adapters + relay argument channel). New in 1.4.53: `fh-codex-doctor` (npm bin) — Codex adapter drift scanner; reads the documented M1/M2/M3 skill tier map + skill/agent source and reports codex-native/adapter-required/claude-native/unclassified per unit, wired into `npm test`/`prepublishOnly` (fail-closed on unclassified Claude-native primitives). New in 1.4.49: steel-quench gains Step 0.6 Verdict-Invariance Probe (groundedness axis — a load-bearing judged gate's verdict must track behavior, not rubric phrasing; measured flip-count over cross-family paraphrases; arXiv:2605.06161 Policy Invariance anchor); multi_model_sidecar_strategy §Vendor-native harness (a model is strongest in its own vendor CLI — Claude/CC, GPT/codex, Gemini/Antigravity; a universal router degrades all of them, so it stays an autocomplete/QA sidecar, never orchestration); predelete_check.sh fail-closed rewrite; memory-hygiene A-TMA anchor. New in 1.4.48: phantom-quench + steel-quench gain external frontier anchors (arXiv:2607.02052 package-hallucination; arXiv:2607.02057 prompt-coverage-adequacy); README model-flat claim reframed from a per-release point-curve to structural invariants (operation flattens across tiers; depth tier-order fixed within a generation). New in 1.4.47: onboarding step ① surfaces the Mode D companion-store session-start load in the auto-read salience anchor (previously only in the local binding + rules, so a greeting could skip the load). New in 1.4.46: context-doctor command-output axis (route to rtk/proxy for verbose CLI stdout, complementing .claudeignore; risk-gated to token-scarce envs). New in 1.4.41: context-doctor 2026 trigger vocab (context engineering/rot/collapse) + phantom-citation hardening; hub measurement-integrity-checklist (cross-model measurement pre-flight: display-name pin/reps≥3/discriminating probe). New in 1.4.40: install-wizard queryable-wiki scaffold (INDEX + session-start read + R/W/C ingest). New in 1.4.39: auto-decorrelation (cross-family verifier sidecar recruitment) + video-ingest (capability-routed video ingestion). New in 1.4.x: verify-axis check-class taxonomy (mandatory-pass/measured/judged), no-reinvention Tier-0 inventory, 7-class failure taxonomy, Destructive-Op Gate, Wave-T (Temper), tier-floor governance, Mode D Model Notice, FC consent lane, default-Sonnet guidance. New in 1.3.0: public-surface-audit, field-harvest Mode B auto-trigger, 4-axis gate scope ext. Validated cross-CLI: Claude Code, Codex, Gemini.",
16
16
  "source": "./plugins/fh-meta"
17
17
  },
18
18
  {
19
19
  "name": "fh-commons",
20
- "version": "3.20.1",
20
+ "version": "3.21.0",
21
21
  "description": "Project-agnostic utility skills — 6 skills (convergence-loop · deliberation · mcp-circuit-breaker · token-budget-gate · ko-tech-writer · persona-cast) + 7 agents (quench-challenger + the web-review cast: designer · ux-writer · fe-dev · be-dev · qa · a11y). Domain-independent utilities transplantable into any project.",
22
22
  "source": "./plugins/fh-commons"
23
23
  },
24
24
  {
25
25
  "name": "fh-qp",
26
- "version": "3.20.1",
26
+ "version": "3.21.0",
27
27
  "description": "QP (Quality Platform) — the generic edition of a field QA harness's Prepare→Automation→Regression loop as an FH plugin: 4 skills (qp router · qp-plan · qp-run · qp-regress) + qp_tools.sh (target-class · adapter-probe · mask · surface-reach · mtm-check · run-verbs, typed exit codes) + a zero-domain-constant profile slot + 29 known-pair lanes. Drives web targets through the session's Playwright MCP and desktop targets through computer-use MCP (mobile deferred); calls a registered qasp typed capability when one exists (strictest-wins) — none is registered today, so the MCP fallback is the first edition. Verdict contract: a MACHINE closure requires a recorded assertion; a failed first step is attributed BLOCKED, not FAIL; surface_reach counts every TC in the denominator. Born as chamber run #18 (EMIT, 2026-09-05).",
28
28
  "source": "./plugins/fh-qp"
29
29
  },
30
30
  {
31
31
  "name": "fh-preprep",
32
- "version": "3.20.1",
32
+ "version": "3.21.0",
33
33
  "description": "preprep — a presentation-preparation harness. 1 skill. One CLI over 17 lanes (7 built-in + 10 module) that reads a declared surface manifest and checks a talk's assets against each other: canonical terms, jargon glosses, retired vocabulary, inter-slide dependencies, pacing, get/put round-trips, adjacent duplication, slide relations, geometry, attribute consistency, fonts, diagrams, slide refs, and screen-parity between manuscript and deck. Verdict contract: exit 0 pass / 1 findings / 2 cannot-judge — a surface that could not be read is UNMEASURED, never 0. Promoted out of fh-commons 2026-09-13 after the skill grew past one role (routing / lane modules / fixtures).",
34
34
  "source": "./plugins/fh-preprep"
35
35
  }
package/CATALOG.md CHANGED
@@ -35,6 +35,11 @@ is, for any session that does not already know its filename, indistinguishable f
35
35
  ENFORCE·EVIDENCE·PATTERN 층은 안 온다. 두 체크아웃 실측 15행, 세 갈림 방향, 그리고 이 측정이
36
36
  **주장하지 않는 것**. 계기 = `scripts/env_layer_fingerprint.sh`. **드리프트나 «게이트 통과»를
37
37
  근거로 쓰기 전에 읽어라.**
38
+ - `knowledge/shared/harness-core/hook_channel_visibility.md` — #hooks, #auto-approve, #visibility.
39
+ 훅 출력 채널(systemMessage · additionalContext · permissionDecisionReason · updatedInput ·
40
+ OSC 777 · exit 2) × 표면(질문 · 계획 승인 · 권한 · 대화) × 시점(고르기 전/후) 실측표. 🟥 자동승인
41
+ 아래에서 PreToolUse **ask 는 삼켜진다**(5/5) — 멈추는 것은 deny / exit 2. **ask 를 fail-closed 로
42
+ 인용하기 전에 읽어라.**
38
43
  - `knowledge/shared/harness-core/harness_terminal_correlation_and_recommendations.md` —
39
44
  #correlation, #terminal, #recommendations.
40
45
  - `knowledge/shared/rules/knowledge_layer_seam.md` — #seam, #org-knowledge, #unwired. Names FH's own
package/CLAUDE.md CHANGED
@@ -837,7 +837,10 @@ deletions (`scripts/finding_verify.py` refuses to complete a run whose drops wer
837
837
  A gate guarding an irreversible boundary that silently proceeds when its tooling is down is **fail-open**
838
838
  — by this floor's definition, not a gate. (The same reflex already ships piecewise — `mcp_tool_gating
839
839
  §unlisted → ask (fail-closed)`, corpus-grounding's fail-closed-no-generator — this section names the
840
- floor they share.)
840
+ floor they share.) 🟥 **ask is fail-closed only while a human answers it**: under an auto-approver (a
841
+ `PermissionRequest` allow hook) a hook's ask ran **5/5**, deny stopped it (interactive, 2026-09-25) — so
842
+ on an irreversible surface the closed direction is **deny / exit 2**; `permissions.ask` rules unmeasured
843
+ (`hook_channel_visibility.md`).
841
844
 
842
845
  **Salience residual** (corrected 2026-06-27 — the surfaces split, they are not uniformly un-hookable):
843
846
  the **pre-commit** hook cannot catch either irreversible surface *at commit time*. But "pre-commit can't"
@@ -168,3 +168,4 @@ Throughout the session, when conversation signals match the table in CLAUDE.md:
168
168
  - `harness_6axis_framework.md` — Full 6-axis decision tree
169
169
  - `hub_compounding_loop.md` — Session close → harvest-loop → weekly cycle
170
170
  - `knowledge/shared/rules/operations.md` — Sub-agent invocation log format + weekly scanner
171
+ - `knowledge/shared/harness-core/hook_channel_visibility.md` — Which hook output reaches the human before they choose, and why a hook's `ask` does not stop a call under an auto-approver (only deny / exit 2 does)
@@ -299,3 +299,20 @@ ASCII 범위로만 묻는다. 계기를 짜는 쪽도 같은 함정을 밟는다
299
299
  🟥 **두 결함이 서로 반대 팔에서만 보였다.** 절대경로 과차단은 `core.hooksPath` 가 이미 잡힌
300
300
  기계에서만, 셈법 어긋남은 훅이 먼저 바뀐 쪽에서만 난다. **어느 한쪽만 돌렸으면 둘 다
301
301
  놓쳤다** — 8-a 가 세운 명제가 자기 자신에게 두 번 적용된 자리다.
302
+
303
+ ## 9. Config-Overwrite-Recovery — 설정 파일이 세션 중에 바뀌었을 때 (2026-09-26)
304
+
305
+ 계기: `scripts/session_config_fingerprint.sh` — 세션 시작(`fh_session_load.sh`)에 여섯 파일의
306
+ sha256+mtime 을 떠 두고, 마감(`session_close_check.sh` ④-f)이 바뀐 파일을 **이름으로** 댄다.
307
+ advisory 다(세션이 스스로 설정을 바꾸는 건 정당하다). 스냅이 없으면 «안 바뀜» 이 아니라
308
+ «측정 안 됨» 이다. 계기의 층 대조 짝은 `scripts/hook_drift_check.sh`(설치된 훅이 템플릿과 같은가
309
+ — 있다/없다가 아니라 **현행인가**).
310
+
311
+ **의도하지 않은 변경이면 이 순서로** — gitignored 설정은 `git checkout` 되돌림이 없다:
312
+ 1. **지금 사본을 먼저 떠라** (`cp <파일> <파일>.overwritten.$(date +%s)`) — 덮어쓴 쪽 내용도 증거다.
313
+ 2. **추적 파일**(`CLAUDE.md`)은 `git diff CLAUDE.md` 로 보고 `git show HEAD:CLAUDE.md` 로 대조해 되돌린다.
314
+ 3. **gitignored 설정**(`.claude/settings*.json`)은 기억으로 다시 쓰지 말고 **출하 스니펫에서 다시
315
+ 짓는다**(`templates/settings.*.snippet.json` · `templates/subagent-tally-hook.json`), 그 뒤
316
+ `bash scripts/hook_drift_check.sh` 로 CURRENT 인지 확인한다. 🟥 복구를 핑계로 원래 없던 훅을
317
+ 넣지 마라 — 스니펫에 없는 로컬 항목은 세션 전사본에서 원래 값을 찾아 대조한다.
318
+ 4. **홈 설정**(`~/.claude/...`)은 이 레포 소유가 아니다 — 무엇이 바뀌었는지만 보고하고 사람이 판단한다.
@@ -0,0 +1,80 @@
1
+ ---
2
+ title: Hook channel visibility — which hook output reaches whom, and when
3
+ tags: [hooks, permissions, auto-approve, visibility, measured]
4
+ status: measured (partial — unmeasured cells are named, not filled)
5
+ created: 2026-09-26
6
+ ---
7
+
8
+ # Hook channel visibility — 훅 출력은 «누구에게, 언제» 닿는가
9
+
10
+ > **한 줄**: 훅이 무언가를 «냈다» 와 사람이 그것을 «고르기 전에 봤다» 는 다른 명제다. 그리고
11
+ > 훅이 **ask** 를 냈다고 호출이 멈추는 것도 아니다 — 누군가 권한 프롬프트에 대신 답하면 ask 는
12
+ > 삼켜진다. 멈추는 것은 **deny / exit 2** 다.
13
+
14
+ 출처: 필드 하네스(데스크톱 펫 게이트 — 권한 요청을 사람 대신 자동승인하는 앱에 FH 게이트를 싣는
15
+ 프로젝트)를 만들며 2026-09-25~26 에 잰 대화형 pty 실측 세 건. 원장은 로컬(`tracks/_meta/result_2026-09-25_gate-vs-autoapprove_INTERACTIVE.md`
16
+ · `result_2026-09-25_hook-answers-questions.md` · `result_2026-09-26_boost-visibility-2.1.283.md`,
17
+ gitignored)이고, 이 문서는 그 판정만 옮긴다. 모델은 전부 sonnet, 격리는
18
+ `--setting-sources project,local --strict-mcp-config`.
19
+
20
+ ## 1. 가장 먼저 — ask 는 자동승인 앞에서 fail-closed 가 아니다
21
+
22
+ | 팔 (대화형, CLI 2.1.282, 명령 `git push origin main`) | reps | 착지 |
23
+ |---|---|---|
24
+ | 게이트 PreToolUse **ask** + PermissionRequest 훅 **allow** (auto 3 · acceptEdits 2) | 5 | **5/5 실행됨** — ask 가 삼켜졌다 |
25
+ | 게이트 PreToolUse **deny** + PermissionRequest 훅 allow (acceptEdits) | 2 | **0/2** — 멈췄다, PermissionRequest 미호출 |
26
+ | 게이트 ask, 자동승인 훅 없음 (대조, auto 1 · acceptEdits 1) | 2 | 0/2 |
27
+
28
+ - ⇒ 자동승인(PermissionRequest allow 훅, 그런 훅을 쓰는 데스크톱 승인 앱, «예» 를 대신 누르는
29
+ 래퍼) 아래에서 비가역 호출을 멈추려면 게이트는 **deny** 를 내야 한다.
30
+ - 🟥 **표면마다 다르다**: 헤드리스(`-p`)에서는 ask 뒤에 PermissionRequest 가 안 불렸다. 헤드리스
31
+ 초록을 대화형으로 옮겨 적지 마라.
32
+ - **미측정**: ⓐ 자동승인 훅 없이 auto 모드 **단독**이 ask 를 삼키는가(대조 1판은 안 삼킴 — 바 미달)
33
+ ⓑ `permissions.ask` **규칙**(훅이 아니라 설정 규칙)이 같은 부류인가 ⓒ `exit 2` 는 deny 와 같은
34
+ 방향이라고 문서가 말하지만 이 조합에서 직접 재지 않았다 ⓓ deny 팔은 reps 2 로 바 미달.
35
+ - 이 사실이 고친 문서: `templates/.claude/rules/mcp_tool_gating.md` §2 주석 · CLAUDE.md
36
+ §Irreversibility Gates · goal-quench rung ②.
37
+
38
+ ## 2. 채널 × 표면 × 시점
39
+
40
+ «앞» = 사람이 고르기(답·승인) **전**에 화면/알림에 나타남 · «뒤» = 고른 **뒤**에만 · «없음» = 끝까지 안 그려짐.
41
+ 각 칸: 결과 · reps · CLI 버전.
42
+
43
+ | 채널 | 질문 창 (AskUserQuestion) | 계획 승인 (ExitPlanMode) | 권한 프롬프트 (Bash 등) | 대화 / 모델 |
44
+ |---|---|---|---|---|
45
+ | PreToolUse `systemMessage` | **뒤** 9/9 (5초 창 6 · 25초 창 3) · 2.1.283 | 화면 표시 0/3 · 2.1.283 | 컨트롤로 쓴 Bash 쪽은 질문 창 **앞**에 18/18 · 2.1.283 | 미측정 |
46
+ | PermissionRequest `systemMessage` | **없음** 3/3 · 2.1.283 | 미측정 | 미측정 | 미측정 |
47
+ | PreToolUse `additionalContext` | **없음** 3/3 (모델도 되풀이 안 함) · 2.1.283 | 미측정 | 미측정 | 모델 쪽 도달 미측정 |
48
+ | PreToolUse ask + `permissionDecisionReason` | **없음** 3/3 — 권한 창도 안 뜨고 질문 창이 그대로 · 2.1.283 | 미측정 | ask 는 자동승인에 삼켜짐 5/5 (§1) · 2.1.282 | 미측정 |
49
+ | PreToolUse deny + 사유 | 모델이 사유의 값을 답으로 따름 3/3 (`hook error` 로 표시) · 2.1.282 | 계획 **수정 요구**로 쓰면 **0/6** 착지 — 모델이 «훅 주입» 으로 의심하고 되물음 · 2.1.282 | deny 는 멈춤 0/2 착지 (§1) · 2.1.282 | 사유는 모델에게 보인다 |
50
+ | `updatedInput` (+ allow) | `answers` 주입 = **답이 된다** 3/3 (PreToolUse) · 3/3 (PermissionRequest), «User answered» 로 렌더 · allow **단독**은 0/2 · 2.1.282 | 원 입력 echo = 승인 UI 없이 진행 3/3 (PreToolUse) · 3/3 (PermissionRequest) · allow 단독 0/2 · 2.1.282 | 미측정 | 사람이 답한 것처럼 보인다 — 출처 표시 없음 |
51
+ | PermissionRequest deny + `message` | 미측정 | 수정 요구 착지 1/3 (1 수용 · 1 확인 요청 · 1 «suspicious» 무시) · 2.1.282 | 미측정 | 미측정 |
52
+ | `terminalSequence` (OSC 777 알림) | **미측정** (같은 필드라 같을 가능성은 높다 — 선언 전 3판 필요) | 승인 화면 **앞** 3/3 (설치본 증폭기 사본) · 합성 양성 3/3 · known-negative 0/3 · 2.1.283 | 미측정 | 해당 없음 (터미널 알림) |
53
+ | `exit 2` + stderr | 미측정 | 미측정 | 미측정 | 미측정 |
54
+
55
+ ## 3. 계기 함정 — CLI 도 자기 OSC 777 을 낸다
56
+
57
+ - 계획 승인 화면 **뒤**: `Claude Code needs your approval for the plan` (9/9, 2.1.283).
58
+ - 질문 창을 25초 열어 두면: `Claude needs your permission` (3/3). 5초 창에서는 0/15 — 5~25초 사이에 나온다.
59
+ - ⇒ «OSC 777 이 몇 개 나왔나» 로 세는 계기는 known-negative 에서도 1 을 센다(거짓 양성). **판정은
60
+ 본문 접두(예: `FH 게이트;`)로** 한다. 개수는 맞는데 지시 대상이 틀리는 부류다 —
61
+ `measurement-integrity-checklist.md` 표의 같은 줄.
62
+ - 알림이 사람의 터미널에 **착지**하는지는 pty 바이트까지만 쟀다(터미널마다 다르다 — 받는 터미널에서만 뜬다).
63
+
64
+ ## 4. 설계 함의
65
+
66
+ 1. **비가역을 멈추는 채널은 deny / exit 2 뿐이다.** ask 는 «사람이 프롬프트 앞에 있을 때» 의 채널이다.
67
+ 2. **질문 창에서 사람을 돕는 부스트는 지금 없다.** systemMessage 는 고른 뒤에 그려지고, 나머지는
68
+ 안 그려진다. 후보: OSC 777(질문 쪽 미측정) · `updatedInput` 으로 선택지 설명에 싣기(질문을
69
+ «바꾸는» 것이라 경계를 넘는다 — 운영자 결정) · 바깥 표면(펫 말풍선·상태표시줄).
70
+ 3. **`updatedInput.answers` 는 훅이 사람 대신 답하게 한다** — 그리고 화면은 «사람이 답했다» 고
71
+ 말한다. 가역 질문에 한해 규칙으로 답하고, 선택지에 비가역이 섞이면 사람에게 남겨라(실측: 그렇게
72
+ 짠 훅이 3회 연속 질문 루프를 사람 입력 0 으로 완주 3/3, 비가역 선택지에서 멈춤 3/3).
73
+ 4. **계획 수정 요구는 PreToolUse deny 사유로는 안 먹는다(0/6).** 모델이 그것을 주입으로 읽는다 —
74
+ 그 판단은 옳은 방어이고, 우회하려 하지 마라.
75
+
76
+ ## 5. 이 문서가 주장하지 않는 것
77
+
78
+ - sonnet 한 모델, 팔당 2~3판(부록 포함 최대 9). 한 머신·한 터미널.
79
+ - CLI 버전이 바뀌면 칸이 바뀔 수 있다 — 각 칸의 버전을 같이 인용해라.
80
+ - 미측정 칸을 «없다» 로 읽지 마라. 비어 있는 것은 결과가 아니라 측정이다.
@@ -237,6 +237,15 @@ here.** Three shapes, all observed 2026-07-20 in a single session:
237
237
  | n+10 | **Accepted into the scanned set, but no probe matches that shape** — the instrument counts the file as covered and reports it *clean* | `degrade_direction_scan.sh` collected `.sh` files while every probe was Python-shaped (`except:` / `.get(k, True)` / `if not x:`). A known-positive bash file with four default-toward-PASS constructs scored **0/4**, and the output read `no default-toward-PASS smells in 1 scanned py/sh file` (2026-07-28) | The known-positive of *that shape* scores 0 while the summary says "scanned" — the tell is coverage claimed without detection demonstrated |
238
238
  | n+11 | **The collection predicate, not the probe, is what silently drops the target** | Same scan: git hooks are named `pre-push` (no extension) under `.git-hooks` (dotted directory), and the extension test ran against the **full path**, so FH's own mechanical floor reported `no scannable (py/sh) target files`, exit 0 | Point the instrument at a directory you *know* holds a positive; an empty file list is the finding, not a clean result |
239
239
  | n+12 | **The measured axis does not vary with the arm — and equal scores are read as "no difference"** | External name: **frozen-replay defect** (`001TMF/harness-forge`, absorbed 2026-08-23 — *"the single most common way a harness search produces a confident, meaningless result"*). Their instance: a scorer replaying cached outputs makes quality **constant across candidates**, so the search happily returns a winner while measuring only cost. **Ours is not that instance** — see the note below | A **known-pair on the actual pair being compared**, not on a fixture: inject an arm that MUST score differently. If it does not, the equal scores were the instrument standing still, not the arms being alike |
240
+ | n+13 | **A live instrument judges by COUNT — the count is right, the referent is wrong** | A pty probe counted OSC 777 notifications to decide «the hook's alert reached the terminal». The CLI emits its own OSC 777 (`…needs your approval for the plan`), so the known-negative (hook without the alert field) scored 1 — a true count of the wrong thing (2026-09-26, field harness, CLI 2.1.283) | The known-negative scores non-zero. Judge by **prefix / identity** (the body starts with the hook's own title), never by how many arrived — `hook_channel_visibility.md` §3 |
241
+ | n+14 | **The defect axis is two-sided, and the instrument minimizes along it** | A loop-seam ratio (last→first frame gap ÷ neighbour step) was minimized to pick the cut point; 0.00–0.02 read as «perfect» but meant a duplicated frame — a freeze. `≫1` = skip, `≈1` = normal, `≈0` = freeze, so minimizing *produces* the other defect (2026-09-23, field harness) | One known-negative is not enough: a two-sided axis needs **a negative on each side**. Target the normal value in log distance, or judge «is this value precedented inside this target's own distribution» instead of a threshold |
242
+
243
+ **After fixing how an instrument READS, grep the repo for the symptom string** (the API call or
244
+ token the broken reading used, e.g. `getComputedStyle(..).fontSize`), and dispose of every hit as
245
+ ⓐ same defect → fix in the same commit · ⓑ not affected → one line saying why · ⓒ undecided → name it
246
+ in a signal. Grep the *string*, not «the same class» — the author is the one who just failed to
247
+ generalize (2026-09-24, field harness: the same dead reading, fixed in one probe, was still live in the
248
+ neighbouring probe and broke two legs in opposite directions).
240
249
 
241
250
  🟥 **n+12 is the class every *comparative* measurement is exposed to — A/B arms, ablation, before/after,
242
251
  tier batteries** — and it is the one shape on this list where **the instrument's silence looks exactly
@@ -4397,3 +4397,22 @@
4397
4397
  고치고 재현은 레인 파일 안에만** 두는 것이었다. 두 병렬 팔이 같은 게이트 번호(G30)를 각자 써서
4398
4398
  cherry-pick 에서 충돌했다 — 병렬 팔에 번호 대역을 미리 나눠 주지 않은 발주 결함.
4399
4399
  ⚠️ 보고 없이 끝난 팔 둘은 «커밋 있음» 이 곧 «검증됨» 이 아니다 — 매번 거버너 재실행으로 닫았다.
4400
+
4401
+ - date: 2026-09-25
4402
+ session: 16a11bc6 (FH 로컬 거버너 · Opus 5.5 · 클라우드 인계 처리 → FoD 게이트 야간)
4403
+ agent: general-purpose ×9 · Explore ×1
4404
+ task: >-
4405
+ FoD 연속 PR 팔 — #120 로컬 검증·머지 · #121 언어 수리 라이브 레인 · #122 증폭기 상태칸+번역투+증폭기 결함 ·
4406
+ #123 자기검사 홈 격리+증폭기 소실 범인 · #124 headless 라이브 레인 · #125 자동승인 하 deny+래퍼 커버리지 ·
4407
+ #126 옛 게이트 사본 치유 · 읽기 전용 headless 조사 · 훅이 질문에 답하나 실측(48런)
4408
+ count: 10
4409
+ outcome: partial
4410
+ evidence: >-
4411
+ 7 PR 전부 머지·설치(각 머지 재실행 게이트 초록) · 실측 결과 파일 둘. 🟥 partial 인 이유: 팔 셋이 운영자 실제 홈을
4412
+ 건드렸다(#122 팔 자기검사가 ~/.claude/fh-gate 시드 — 그 뒤 G0 로 기계화) · headless 팔 개발 중 운영자 화면에 불투명 창
4413
+ ~9분 · #125 팔이 야간 dock=1 로 라이브 9개 미실행 BLOCKED(거버너가 재실행해 해소) · 두 팔이 슬립·연결 끊김으로 stall.
4414
+ learning: >-
4415
+ 🟥 격리 조건은 디스패치 **첫 줄**에 — 사고 뒤에 넣었다(feedback_fod_work_must_not_touch_real_home).
4416
+ 팔의 «실제 홈 영향 없음» 보고는 두 번 틀렸다(스크립트 시드 · 원인 모름) — 거버너가 mtime·heal 로그로 직접 대조해야 했다.
4417
+ 같은 체크아웃 팔은 직렬로, 읽기 전용 조사·임시 폴더 실험만 병렬로 — 충돌 0. «앱 설치» 와 «게이트 사본 갱신» 은 다른
4418
+ 사건이었다(설치본이 16:11 옛 판) — 설치 검증은 번들 cmp 가 아니라 **실행 중 훅의 판정** 을 찔러 봐야 했다.
@@ -63,6 +63,13 @@ gh run view <id> --log-failed | grep -E '❌|FAIL|not ok' | head -20 #
63
63
  Record the lane name in the session log even if the re-run goes green — **a flake that cannot be named
64
64
  cannot be fixed**, and the second occurrence is the one that gets fixed only if the first was named.
65
65
 
66
+ **Before calling it flaky, check the classifier's state axis.** An intermittent failure can be a
67
+ classification defect that only *looks* random: the verdict depends on state keyed per PID or per
68
+ session (a process that started a moment earlier, a session id reused across runs), and the timing
69
+ of the sample decides which state it sees. Measured 2026-09-26 on a field harness: an «intermittent»
70
+ misclassification reproduced **30/30** once sampled at a 0.01 s interval — it was deterministic in
71
+ the state axis, not flaky. Name the key the classifier reads its state by before re-running.
72
+
66
73
  This is prose on purpose. N=1: one flake, one lost diagnosis. The mechanization threshold in this repo
67
74
  is N≥3 or the same class recurring on another surface; a scheduled log-capture job built on a single
68
75
  occurrence would be the speculative build the evidence-threshold rule forbids.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrono-meta/fh-gate",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "description": "FH runtime adapters — run FH governance, skills, and agents via Claude or Codex with machine-parseable gates.",
5
5
  "homepage": "https://github.com/chrono-meta/forge-harness#readme",
6
6
  "bugs": {
@@ -250,6 +250,10 @@
250
250
  "scripts/test_dispatch_log_lanes.sh",
251
251
  "scripts/test_subagent_tally_hook_lanes.sh",
252
252
  "scripts/subagent_tally_hook.sh",
253
+ "scripts/hook_drift_check.sh",
254
+ "scripts/test_hook_drift_lanes.sh",
255
+ "scripts/session_config_fingerprint.sh",
256
+ "scripts/test_session_config_fingerprint_lanes.sh",
253
257
  "scripts/test_doc_claim_triad_lanes.sh",
254
258
  "scripts/test_env_layer_fingerprint_lanes.sh",
255
259
  "scripts/test_env_purity_lanes.sh",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-commons",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-meta",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -1,5 +1,24 @@
1
1
  # forge-harness (fh-meta) Changelog
2
2
 
3
+ ### [3.21.0] — 2026-09-26 — 마감 게이트가 옛 훅과 세션 중 설정 덮어쓰기를 이름으로 말한다
4
+
5
+ **minor — 새 출하 스크립트 둘 + 마감 체인 동작 변경.** 소비자의 게이트 수용은 안 깬다
6
+ (④-e 는 옛 훅에서 «측정됨» → «NOT MEASURED + 재병합 경고» 로 바뀌어 막는 쪽이 아니라 알리는 쪽이다 · ④-f 는 advisory).
7
+
8
+ - **`scripts/hook_drift_check.sh`** (신규 출하) — 출하 템플릿 훅과 설치된 `.claude/settings.json` 을 이벤트별로 대조:
9
+ CURRENT / STALE / ABSENT / UNKNOWN. 같은 훅이 여럿 설치됐으면(현+옛 공존) STALE, 형식 불량 항목은 UNKNOWN —
10
+ CURRENT 로 접지 않는다. 마감 ④-e 는 이 판정이 CURRENT 일 때만 집계를 «측정됨» 으로 본다
11
+ (종전엔 «SubagentStop» 낱말만 있으면 옛 인라인 훅도 통과했다). 레인 27/0(bash 3.2·5).
12
+ - **`scripts/session_config_fingerprint.sh`** (신규 출하) — 세션 시작에 설정 6종(레포 settings·settings.local·
13
+ CLAUDE.local.md·CLAUDE.md · 사용자 settings·CLAUDE.md) 해시를 스냅하고 마감 ④-f 에서 바뀐 파일을 이름으로.
14
+ 스냅 부재 = NOT MEASURED. 🟥 스냅은 지금 `fh_session_load.sh`(로컬 SessionStart)에서만 뜬다 —
15
+ 그 훅이 없는 install 은 ④-f 가 NOT MEASURED 로 남는다. 레인 25/0.
16
+ - **문서 정정** — «ask 는 fail-closed» 는 사람이 답할 때만 참: 자동승인 훅 아래 PreToolUse ask 는 실행됐고(5/5),
17
+ deny 는 멈췄다(대화형 실측). `CLAUDE.md` Irreversibility · `mcp_tool_gating.md` · goal-quench. `permissions.ask` 규칙은 미측정.
18
+ - **`knowledge/shared/harness-core/hook_channel_visibility.md`** (신규) — 훅 채널 × 표면 × 시점 실측 표
19
+ (질문 창엔 고르기 전 훅 출력 0 · 훅이 질문에 답 가능 · OSC 777 도달 · CLI 자체 OSC 777).
20
+ - 측정 체크리스트 n+13·n+14 · flaky 분류 단락 · 집계 훅 레인 타이밍 ms 화.
21
+
3
22
  ### [3.20.1] — 2026-09-26 — 마감 게이트 ④-e 가 Claude Code 내부 에이전트를 디스패치로 세지 않는다
4
23
 
5
24
  **patch — 오탐 수리.** 소비자의 게이트 수용은 안 깬다(과다 계수 → 정확 계수 방향).
@@ -90,7 +90,7 @@ Three rungs, climbed one at a time:
90
90
  | **③ unattended** | the loop runs on its own | reviews after the fact |
91
91
 
92
92
  - **Graduation threshold (measured):** a loop climbs one rung only after **K consecutive clean rounds across a 2+ session/run window** — the *2+ window* reuses `operations.md`'s promotion-window discipline (`accepted ≥ 60%` / recurrence `N=3`). **`K=2` is a provisional default, not yet calibrated** — no loop-run data exists yet; revisit once it does (same honesty as this SKILL's `N=10` budget baseline). "Clean" = the round's Done-When passed **AND** a positive downstream verdict (pipeline-conductor / sidecar = CLEAN) **AND zero S/M-grade governor-catch and zero post-ship correction** — *not merely* the absence of a governor-catch, so a quieter or weaker governor cannot manufacture graduation. **The streak is recorded per round in a local autonomy ledger** (the hub keeps it at `tracks/_meta/autonomy_ledger.yaml`; a plugin-only user keeps their own — anywhere in their project, the path is theirs): date · task · done-when · verdict · governor-catch grades · `clean:` bool. Graduation reads that ledger. A *computation script* (`scripts/`) that auto-derives the current rung from the ledger is **deliberately deferred** until enough entries exist to compute over — building the meter before there is a stream to measure is the speculative-infra the evidence-threshold discipline forbids. *Check class: a **measured count** (ledger grep) over a **judged per-round grade** — and the grade must be bound to the round's own challenger / steel-quench S/M verdict (the upstream adversarial artifact), **never an author self-grade** (else "measured" laundering a judge-only path). Until ≥~5 entries make a computation script worth writing, the streak is judged-and-hand-recorded — provisional by construction.*
93
- - **Irreversible carve-out (non-negotiable — the FH increment over the video):** any action whose effect **cannot be undone within the loop** — not only the two examples (Destructive-Op delete/rewrite · Pre-Publish go-public) but **any irreversible side-effecting write** (an MCP `ask`-tier send, a payment, an outbound publish) — **never reaches rung ③**. Membership is the **mechanical surface test** of CLAUDE.md's Surface-Class Degrade Invariant + `mcp_tool_gating` (grep the action surface; do **not** self-label), not a match against the two examples. Such actions stay at rung ② (HITL) **permanently**, regardless of clean-round count. The video graduates a loop to fully unattended; FH caps graduation at the irreversible boundary. *Check class: judged — pair: a target-tier blind sim per CLAUDE.md §Target-tier sim gate (run 2026-06-27, Sonnet, PASS — a remote-branch-delete loop correctly held at rung ② despite 4 clean rounds). **Prose-enforced, not hook-enforced** — accepted residual, named not silent.*
93
+ - **Irreversible carve-out (non-negotiable — the FH increment over the video):** any action whose effect **cannot be undone within the loop** — not only the two examples (Destructive-Op delete/rewrite · Pre-Publish go-public) but **any irreversible side-effecting write** (an MCP `ask`-tier send, a payment, an outbound publish) — **never reaches rung ③**. Membership is the **mechanical surface test** of CLAUDE.md's Surface-Class Degrade Invariant + `mcp_tool_gating` (grep the action surface; do **not** self-label), not a match against the two examples. Such actions stay at rung ② (HITL) **permanently**, regardless of clean-round count. ⚠️ Rung ② assumes a **human** answers the prompt: under an auto-approver (a `PermissionRequest` allow hook) a hook's `ask` was answered for you and the call ran 5/5, while `deny` stopped it (interactive, 2026-09-25) — so where one is installed, rung ② must be enforced with **deny / exit 2**, not ask (`knowledge/shared/harness-core/hook_channel_visibility.md`). The video graduates a loop to fully unattended; FH caps graduation at the irreversible boundary. *Check class: judged — pair: a target-tier blind sim per CLAUDE.md §Target-tier sim gate (run 2026-06-27, Sonnet, PASS — a remote-branch-delete loop correctly held at rung ② despite 4 clean rounds). **Prose-enforced, not hook-enforced** — accepted residual, named not silent.*
94
94
  - **Demotion (fail toward oversight, with a liveness floor):** any governor-catch, failed Done-When, or correction **resets the clean-round counter and drops the loop one rung** — autonomy is earned per-window, surrendered on the first miss, never sticky. A failed **dry-run (①)** has no lower rung: it **blocks graduation and surfaces to the operator**, it does not demote. A loop that **flips promote/demote ≥ `N=3` times in a window** (reusing operations.md's recurrence-escalation) is a noisy boundary — **freeze at the lower rung and surface**, do not keep oscillating.
95
95
 
96
96
  ### Two paths to autonomous completion (by surface reversibility)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-preprep",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fh-qp",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "engines": {
5
5
  "claudeCode": ">=1.0.0"
6
6
  },
@@ -138,9 +138,12 @@ fi
138
138
  # Reported ONCE per pull (it is an event). Distinguishes "no change" from "could not measure".
139
139
  INFRA=""; INFRA_NOTE=""
140
140
  if [ -n "$PREV_HEAD" ] && [ "$PREV_HEAD" != "$HEAD_NOW" ]; then
141
+ # templates/*hook*.json + templates/*settings*.json added 2026-09-26: subagent-tally-hook.json
142
+ # changed its body (RE-MERGE required) and this delta never announced it — `templates/settings\.`
143
+ # only covers the snippets. (A comment INSIDE the `\`-continued pipe below would break it.)
141
144
  if INFRA_RAW="$(git -C "$FH" diff --name-only "${PREV_HEAD}..HEAD" 2>/dev/null)"; then
142
145
  INFRA="$(printf '%s\n' "$INFRA_RAW" \
143
- | grep -E '^(templates/\.git-hooks/|templates/settings\.|scripts/fh_|plugins/[^/]+/skills/install-(wizard|doctor)/)' \
146
+ | grep -E '^(templates/\.git-hooks/|templates/settings\.|templates/[^/]*(hook|settings)[^/]*\.json$|scripts/fh_|plugins/[^/]+/skills/install-(wizard|doctor)/)' \
144
147
  | head -6)"
145
148
  else
146
149
  INFRA_NOTE="UNMEASURED — cannot reach the previously seen commit ($PREV_HEAD), so the infra delta was not computed (rebase, shallow clone, or GC). Not the same as 'nothing changed'."
@@ -317,6 +317,15 @@ fi
317
317
  ( cd "$FH" && bash scripts/branch_claim.sh reap >/dev/null 2>&1 ) || true
318
318
  }
319
319
 
320
+ # ── 세션 설정 지문 스냅 (2026-09-26) ─────────────────────────────────────────────
321
+ # WHY: 2026-09-26 서브에이전트의 측정 실행(빈 작업경로)이 이 체크아웃의 .claude/settings.json 과 CLAUDE.md 를 덮어썼고
322
+ # FH 는 못 잡았다(settings 는 gitignored 라 git 이 안 보고, undo 도 없다). 시작 시 해시+mtime 을
323
+ # 떠 두면 마감(session_close_check.sh ④-f)이 «무엇이 바뀌었나» 를 이름으로 댈 수 있다.
324
+ # WHY HERE (early exit 위): Mode D 전용 사고가 아니다. /clear·compact 는 같은 세션의 연속이라
325
+ # 기존 스냅을 유지한다(다시 뜨면 그 사이 변경 증거가 지워진다). 실패해도 세션을 막지 않는다.
326
+ [ -f "$FH/scripts/session_config_fingerprint.sh" ] && \
327
+ bash "$FH/scripts/session_config_fingerprint.sh" snap --fh "$FH" --source "$_FH_HOOK_SRC" >/dev/null 2>&1 || true
328
+
320
329
  # ── 매핑된 프로젝트의 capability 표면화 (2026-08-18) ───────────────────────────
321
330
  # WHY HERE (branch-claim 과 같은 자리, early exit **위**): 이건 Mode D 전용이 아니다.
322
331
  # companion store 가 없는 설치에서도 프로젝트는 매핑되고, 그때도 형제 하네스의 스킬은
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env bash
2
+ # hook_drift_check.sh — are the hooks INSTALLED in .claude/settings.json the ones the tracked
3
+ # templates currently ship? Per template hook entry: CURRENT / STALE / ABSENT / UNKNOWN.
4
+ #
5
+ # WHY (2026-09-25/26, measured on this repo): session_close_check.sh ④-e used to decide «the tally
6
+ # hook is installed» with `grep -q '"SubagentStop"'`. That is a PRESENCE test. The template's body
7
+ # had just moved into scripts/subagent_tally_hook.sh (it now skips Claude Code's internal agents),
8
+ # and templates/subagent-tally-hook.json says «RE-MERGE — an existing inline hook keeps the old
9
+ # behaviour». An install still carrying the OLD inline hook therefore passed ④-e as «measured»
10
+ # while it was over-counting. `.claude/settings.json` is gitignored, so git never tells you the
11
+ # installed copy has drifted from the tracked source; nothing else in the repo compared them.
12
+ #
13
+ # The sibling instrument, env_layer_fingerprint.sh, answers «is a layer PRESENT»; this one answers
14
+ # «is the present thing the CURRENT thing». They are different questions — a present-but-stale hook
15
+ # is exactly what a presence check renders as green.
16
+ #
17
+ # VERDICTS (per template entry, keyed by event):
18
+ # CURRENT an installed hook in that event has the same matcher AND the same command string
19
+ # STALE an installed hook in that event is the SAME hook (shares an identity token — a
20
+ # scripts/<name>.sh|py it runs, or a tracks/_meta/.<file> it writes) but its command or
21
+ # matcher differs from the template → re-merge needed
22
+ # ABSENT no installed hook in that event is related (includes: settings file does not exist)
23
+ # UNKNOWN the settings file or the template could not be read/parsed, or python3 is missing.
24
+ # 🟥 UNKNOWN is never folded into CURRENT — a checker that cannot read is not a pass.
25
+ #
26
+ # SCOPE: compares `project_settings_json` (and a template's top-level `hooks`) against
27
+ # .claude/settings.json. The SessionStart snippet's `settings_local_json_MODE_D_ONLY` block carries
28
+ # an operator-private path by design and is NOT compared (reported as a note, not as a verdict).
29
+ # READ-ONLY: never writes to any settings file.
30
+ #
31
+ # Usage:
32
+ # bash scripts/hook_drift_check.sh [--settings FILE] [--templates DIR] [--only TOKEN] [--verdict]
33
+ # --only TOKEN restrict to template entries whose identity contains TOKEN
34
+ # (e.g. --only subagent_tally_hook.sh — what ④-e asks)
35
+ # --verdict print ONE aggregate word instead of the table
36
+ # (priority UNKNOWN > STALE > ABSENT > CURRENT)
37
+ # Exit: 0 all CURRENT · 1 some STALE/ABSENT · 3 UNKNOWN · 2 usage error
38
+ set -uo pipefail
39
+
40
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
41
+ ROOT="$(cd "$HERE/.." && pwd)"
42
+ SETTINGS="$ROOT/.claude/settings.json"
43
+ TEMPLATES="$ROOT/templates"
44
+ ONLY=""
45
+ VERDICT_ONLY=0
46
+
47
+ while [ $# -gt 0 ]; do
48
+ case "$1" in
49
+ --settings) [ -n "${2:-}" ] || { echo "usage: --settings needs a non-empty path" >&2; exit 2; }; SETTINGS="$2"; shift 2 ;;
50
+ --templates) [ -n "${2:-}" ] || { echo "usage: --templates needs a non-empty path" >&2; exit 2; }; TEMPLATES="$2"; shift 2 ;;
51
+ --only) [ -n "${2:-}" ] || { echo "usage: --only needs a non-empty token" >&2; exit 2; }; ONLY="$2"; shift 2 ;;
52
+ --verdict) VERDICT_ONLY=1; shift ;;
53
+ -h|--help) sed -n '2,40p' "$0"; exit 0 ;;
54
+ *) echo "usage: unknown argument: $1" >&2; exit 2 ;;
55
+ esac
56
+ done
57
+
58
+ PY="$(command -v python3 2>/dev/null || true)"
59
+ [ -n "$PY" ] || PY=/usr/bin/python3
60
+ if [ ! -x "$PY" ]; then
61
+ if [ "$VERDICT_ONLY" -eq 1 ]; then echo UNKNOWN; else echo "UNKNOWN * * python3 not found — cannot compare (not a pass)"; fi
62
+ exit 3
63
+ fi
64
+
65
+ "$PY" - "$SETTINGS" "$TEMPLATES" "$ONLY" "$VERDICT_ONLY" <<'PY'
66
+ import glob, json, os, re, sys
67
+
68
+ settings_path, tdir, only, verdict_only = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] == "1"
69
+ ID_RE = re.compile(r"scripts/([A-Za-z0-9_.-]+\.(?:sh|py))|tracks/_meta/(\.[A-Za-z0-9_.-]+)")
70
+
71
+ def ident(cmd):
72
+ return {a or b for a, b in ID_RE.findall(cmd or "")}
73
+
74
+ def flatten(hooks, bad=None):
75
+ # bad: optional list collecting events whose hook entries are malformed (no/empty command).
76
+ # 🟥 2026-09-26 (cross-family): such an entry used to be read as command "" → never related →
77
+ # ABSENT. An entry we cannot identify is not evidence of absence; the caller renders UNKNOWN.
78
+ out = [] # (event, matcher, command)
79
+ if not isinstance(hooks, dict):
80
+ return None
81
+ for ev, groups in hooks.items():
82
+ if not isinstance(groups, list):
83
+ return None
84
+ for g in groups:
85
+ if not isinstance(g, dict):
86
+ return None
87
+ m = g.get("matcher", "")
88
+ for h in g.get("hooks", []) or []:
89
+ if isinstance(h, dict) and h.get("type", "command") == "command":
90
+ cmd = h.get("command")
91
+ if not isinstance(cmd, str) or not cmd.strip():
92
+ if bad is not None:
93
+ bad.append(ev)
94
+ continue
95
+ out.append((ev, m or "", cmd))
96
+ elif not isinstance(h, dict) and bad is not None:
97
+ bad.append(ev)
98
+ return out
99
+
100
+ rows, notes = [], []
101
+
102
+ # ── templates ──
103
+ tfiles = sorted(set(glob.glob(os.path.join(tdir, "*hook*.json")) +
104
+ glob.glob(os.path.join(tdir, "settings.*.snippet.json"))))
105
+ tentries = [] # (event, matcher, command, template-name)
106
+ if not tfiles:
107
+ rows.append(("UNKNOWN", "*", "*", "no templates found under %s" % tdir))
108
+ for tf in tfiles:
109
+ name = os.path.basename(tf)
110
+ try:
111
+ with open(tf, encoding="utf-8") as fh:
112
+ d = json.load(fh)
113
+ except Exception as e:
114
+ rows.append(("UNKNOWN", "*", "*", "%s unreadable: %s" % (name, e.__class__.__name__)))
115
+ continue
116
+ if "settings_local_json_MODE_D_ONLY" in d:
117
+ notes.append("note: %s settings_local_json_MODE_D_ONLY not compared (private path by design)" % name)
118
+ block = d.get("project_settings_json", d)
119
+ fl = flatten(block.get("hooks", {}) if isinstance(block, dict) else None)
120
+ if fl is None:
121
+ rows.append(("UNKNOWN", "*", "*", "%s: hooks block malformed" % name))
122
+ continue
123
+ for ev, m, c in fl:
124
+ tentries.append((ev, m, c, name))
125
+
126
+ # ── installed ──
127
+ installed, inst_err, inst_bad = None, None, []
128
+ if not os.path.exists(settings_path):
129
+ installed = [] # no file = no hooks installed = ABSENT (not a read failure)
130
+ else:
131
+ try:
132
+ with open(settings_path, encoding="utf-8") as fh:
133
+ sd = json.load(fh)
134
+ installed = flatten(sd.get("hooks", {}) if isinstance(sd, dict) else None, inst_bad)
135
+ if installed is None:
136
+ inst_err = "hooks block malformed"
137
+ except Exception as e:
138
+ inst_err = "unreadable: %s" % e.__class__.__name__
139
+
140
+ for ev, m, c, name in tentries:
141
+ tid = ident(c)
142
+ label = ",".join(sorted(tid)) or "(inline)"
143
+ if only and not any(only in t for t in tid):
144
+ continue
145
+ if inst_err:
146
+ rows.append(("UNKNOWN", ev, label, "%s — settings %s" % (name, inst_err)))
147
+ continue
148
+ if ev in inst_bad:
149
+ rows.append(("UNKNOWN", ev, label, "%s — settings has a malformed %s entry (형식 불량 항목: no command)" % (name, ev)))
150
+ continue
151
+ same_ev = [(im, ic) for (iev, im, ic) in installed if iev == ev]
152
+ related = [(im, ic) for im, ic in same_ev if tid and (ident(ic) & tid)]
153
+ exact = [(im, ic) for im, ic in same_ev if im == m and ic == c]
154
+ # 🟥 2026-09-26 (cross-family, real fail-open): `any(exact)` called this CURRENT even when the
155
+ # OLD inline form was installed alongside the template form. Claude Code runs every matching
156
+ # hook, so the old behaviour stayed live. CURRENT now means: the same hook is installed
157
+ # EXACTLY ONCE, and that one copy is the template's.
158
+ if exact and len(related) <= 1 and len(exact) == 1:
159
+ rows.append(("CURRENT", ev, label, name))
160
+ continue
161
+ if exact:
162
+ rows.append(("STALE", ev, label, "%s — duplicate install (%d copies of this hook); 중복 설치 — remove the old entries" % (name, max(len(related), len(exact)))))
163
+ continue
164
+ if related:
165
+ why = "matcher differs" if any(ic == c for _, ic in related) else "command differs"
166
+ rows.append(("STALE", ev, label, "%s — %s; re-merge needed" % (name, why)))
167
+ else:
168
+ rows.append(("ABSENT", ev, label, name))
169
+
170
+ if only and not any(r[2] != "*" for r in rows):
171
+ rows.append(("UNKNOWN", "*", only, "no template entry carries this identity"))
172
+
173
+ order = {"UNKNOWN": 3, "STALE": 2, "ABSENT": 1, "CURRENT": 0}
174
+ worst = max((order[r[0]] for r in rows), default=3)
175
+ word = [k for k, v in order.items() if v == worst][0]
176
+
177
+ if verdict_only:
178
+ print(word)
179
+ else:
180
+ for r in rows:
181
+ print("\t".join(r))
182
+ for n in notes:
183
+ print(n)
184
+ cnt = {k: sum(1 for r in rows if r[0] == k) for k in order}
185
+ print("hook-drift: current=%d stale=%d absent=%d unknown=%d (settings=%s)"
186
+ % (cnt["CURRENT"], cnt["STALE"], cnt["ABSENT"], cnt["UNKNOWN"], settings_path))
187
+ sys.exit({"CURRENT": 0, "ABSENT": 1, "STALE": 1, "UNKNOWN": 3}[word])
188
+ PY
@@ -2225,6 +2225,36 @@ if [ -f scripts/test_dispatch_log_lanes.sh ]; then
2225
2225
  fail=1
2226
2226
  fi
2227
2227
  fi
2228
+ # ④-e's «hook installed» verdict + the checker behind it (2026-09-26): a PRESENT-but-STALE tally
2229
+ # hook (the pre-2026-09-25 inline form) used to pass as measured. Revert probe inside the lane.
2230
+ if [ ! -f scripts/hook_drift_check.sh ]; then
2231
+ _absent_subject_verdict "hook-drift lanes" "scripts/hook_drift_check.sh" || fail=1
2232
+ elif [ -f scripts/test_hook_drift_lanes.sh ]; then
2233
+ if _out=$(bash scripts/test_hook_drift_lanes.sh 2>&1); then
2234
+ echo "PASS test_hook_drift_lanes.sh (CURRENT/STALE/ABSENT/UNKNOWN + ④-e consumer + revert probe)"
2235
+ else
2236
+ echo "FAIL test_hook_drift_lanes.sh: installed-hook drift would be misjudged"
2237
+ _show_failure "$_out"
2238
+ fail=1
2239
+ fi
2240
+ else
2241
+ echo "FAIL hook-drift lanes: hook_drift_check.sh present but its anchor is missing"; fail=1
2242
+ fi
2243
+ # ④-f session config fingerprint (2026-09-26): a mid-session overwrite of settings/CLAUDE.md went
2244
+ # unnoticed on 2026-09-25. Advisory at close; the lane pins «no snapshot = NOT MEASURED».
2245
+ if [ ! -f scripts/session_config_fingerprint.sh ]; then
2246
+ _absent_subject_verdict "config-fingerprint lanes" "scripts/session_config_fingerprint.sh" || fail=1
2247
+ elif [ -f scripts/test_session_config_fingerprint_lanes.sh ]; then
2248
+ if _out=$(bash scripts/test_session_config_fingerprint_lanes.sh 2>&1); then
2249
+ echo "PASS test_session_config_fingerprint_lanes.sh (snap/compare + ④-f consumer + revert probe)"
2250
+ else
2251
+ echo "FAIL test_session_config_fingerprint_lanes.sh: a config overwrite would go unnamed"
2252
+ _show_failure "$_out"
2253
+ fail=1
2254
+ fi
2255
+ else
2256
+ echo "FAIL config-fingerprint lanes: session_config_fingerprint.sh present but its anchor is missing"; fail=1
2257
+ fi
2228
2258
  # The tally hook's BODY (2026-09-25): SubagentStop also fires for Claude Code's internal agents
2229
2259
  # (compaction → agent_type ""), and the date-only inline hook counted them as dispatches.
2230
2260
  if [ -f scripts/test_subagent_tally_hook_lanes.sh ]; then
@@ -470,15 +470,34 @@ fi
470
470
  # from. Installable snippet: templates/subagent-tally-hook.json.
471
471
  TALLY="$FH/tracks/_meta/.subagent_dispatch_tally"
472
472
  LOG="$FH/knowledge/shared/learnings/subagent_invocations_log.yaml"
473
+ # 🟥 2026-09-26 — «installed» means CURRENT, not PRESENT. The old test was
474
+ # `grep -q '"SubagentStop"'`, which also passed an install still carrying the pre-2026-09-25
475
+ # INLINE hook (date-only append, counts Claude Code's internal agents as dispatches). The template
476
+ # itself says «RE-MERGE», and nothing compared the gitignored installed copy against it. So the
477
+ # verdict now comes from hook_drift_check.sh: CURRENT → measured · STALE → old hook, re-merge ·
478
+ # ABSENT → none · UNKNOWN (read failure / checker missing) → NOT MEASURED, never folded into OK.
479
+ # Lane: scripts/test_hook_drift_lanes.sh (incl. a revert probe back to the presence grep).
473
480
  HOOK_OK=0
474
- if [ -f "$FH/.claude/settings.json" ]; then
475
- grep -q '"SubagentStop"' "$FH/.claude/settings.json" 2>/dev/null && HOOK_OK=1
476
- fi
477
- if [ "$HOOK_OK" -eq 0 ]; then
478
- echo "⚠️ ④-e dispatch log NOT MEASURED — no SubagentStop tally hook in .claude/settings.json"
479
- echo " (that file is gitignored, so a fresh clone has none). An unmeasured dispatch count is"
480
- echo " NOT a count of zero. Install: templates/subagent-tally-hook.json → .claude/settings.json"
481
+ HOOK_STATE=UNKNOWN
482
+ if [ -f "$FH/scripts/hook_drift_check.sh" ]; then
483
+ HOOK_STATE=$(bash "$FH/scripts/hook_drift_check.sh" --settings "$FH/.claude/settings.json" \
484
+ --templates "$FH/templates" --only subagent_tally_hook.sh --verdict 2>/dev/null)
485
+ case "$HOOK_STATE" in (CURRENT|STALE|ABSENT|UNKNOWN) ;; (*) HOOK_STATE=UNKNOWN ;; esac
481
486
  fi
487
+ [ "$HOOK_STATE" = CURRENT ] && HOOK_OK=1
488
+ case "$HOOK_STATE" in
489
+ (STALE)
490
+ echo "⚠️ ④-e dispatch log NOT MEASURED — 옛 훅: the SubagentStop tally hook in .claude/settings.json"
491
+ echo " differs from templates/subagent-tally-hook.json (re-merge needed — an old inline hook"
492
+ echo " counts internal agents as dispatches). Re-merge that block, then re-run." ;;
493
+ (ABSENT)
494
+ echo "⚠️ ④-e dispatch log NOT MEASURED — no SubagentStop tally hook in .claude/settings.json"
495
+ echo " (that file is gitignored, so a fresh clone has none). An unmeasured dispatch count is"
496
+ echo " NOT a count of zero. Install: templates/subagent-tally-hook.json → .claude/settings.json" ;;
497
+ (UNKNOWN)
498
+ echo "⚠️ ④-e dispatch log NOT MEASURED — could not determine whether the tally hook is current"
499
+ echo " (settings unreadable, or scripts/hook_drift_check.sh missing). Not a pass." ;;
500
+ esac
482
501
  # `grep -c` PRINTS 0 and EXITS 1 when the count is zero. Under `set -o pipefail` (line 16) that
483
502
  # makes the pipeline fail, `|| echo 0` appends a SECOND line, and the value becomes "0\n0" — which
484
503
  # `[ -eq ]` rejects as a bash error, so the branch it guards is skipped. The guard was therefore
@@ -549,6 +568,24 @@ elif [ "$HOOK_OK" -eq 1 ]; then
549
568
  echo "✅ ④-e dispatch log: no sub-agent dispatches tallied today"
550
569
  fi
551
570
 
571
+ # ④-f CONFIG FINGERPRINT (advisory, never blocks) — 2026-09-26.
572
+ # A sub-agent's measurement run overwrote this checkout's .claude/settings.json and CLAUDE.md on 2026-09-26 and
573
+ # nothing noticed: settings is gitignored (no status line, no undo). fh_session_load.sh snaps
574
+ # sha256+mtime of six config files at SessionStart; this compares and NAMES what changed.
575
+ # Advisory because a session may change its own settings on purpose. No snapshot → NOT MEASURED
576
+ # (never «unchanged»). Lane: scripts/test_session_config_fingerprint_lanes.sh.
577
+ if [ -f "$FH/scripts/session_config_fingerprint.sh" ]; then
578
+ # Capture FIRST, then decorate — piping into sed hid the checker's rc (2026-09-26, cross-family).
579
+ _FP_OUT=$(bash "$FH/scripts/session_config_fingerprint.sh" compare --fh "$FH" 2>&1); _FP_RC=$?
580
+ printf '%s\n' "$_FP_OUT" | sed 's/^/④-f /'
581
+ case "$_FP_RC" in
582
+ (0|1|3) ;; # unchanged · changed (advisory) · NOT MEASURED — all already printed above
583
+ (*) echo "⚠️ ④-f config fingerprint NOT MEASURED — checker exited $_FP_RC (instrument error, not «unchanged»)" ;;
584
+ esac
585
+ else
586
+ echo "⚠️ ④-f config fingerprint NOT MEASURED — scripts/session_config_fingerprint.sh missing"
587
+ fi
588
+
552
589
  # ⑤ CARD-LAST invariant — the card must be the NEWEST close artifact. A card older than
553
590
  # fh_completed / signal files written this session = ⑤ ran before ①–④ finished (the bug class).
554
591
  if [ -f "$CARD" ]; then
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env bash
2
+ # session_config_fingerprint.sh — snapshot the session's config files at start, compare at close.
3
+ #
4
+ # WHY (2026-09-26, measured on this repo): a sub-agent's measurement run (empty work-dir path →
5
+ # `cd "" ` succeeded in place) overwrote this checkout's
6
+ # .claude/settings.json and CLAUDE.md mid-session, and FH did not notice. The settings file is
7
+ # gitignored (no `git status`, no `git checkout` undo), and the only existing guard —
8
+ # sim_isolated_run.sh — compares ~/.claude/settings.json mtime around ITS OWN runs, nothing else.
9
+ # So a silent config rewrite by anything else in the session had no detector at all.
10
+ #
11
+ # WHAT: `snap` records sha256 + mtime of six files (below) into a gitignored snapshot with the
12
+ # session id. `compare` recomputes and NAMES every file that changed. It is ADVISORY by design —
13
+ # a session may legitimately change its own settings — so it never blocks; it makes a change
14
+ # visible, and says where the recovery procedure lives.
15
+ #
16
+ # Files: <FH>/.claude/settings.json · <FH>/.claude/settings.local.json · <FH>/CLAUDE.local.md ·
17
+ # <FH>/CLAUDE.md (tracked, but an overwrite target on 2026-09-26) ·
18
+ # <HOME>/.claude/settings.json · <HOME>/.claude/CLAUDE.md
19
+ #
20
+ # 🟥 No snapshot → NOT MEASURED, never «no change». A compare against nothing is not a zero.
21
+ # READ-ONLY on every file it fingerprints; writes only its own snapshot file.
22
+ #
23
+ # Usage:
24
+ # bash scripts/session_config_fingerprint.sh snap [--fh DIR] [--home DIR] [--out FILE] [--source SRC]
25
+ # bash scripts/session_config_fingerprint.sh compare [--fh DIR] [--home DIR] [--out FILE]
26
+ # --source clear|compact keeps an existing snapshot of the SAME session (a /clear or compaction
27
+ # is the same session continuing — re-snapping there would erase the evidence).
28
+ # Exit (compare): 0 unchanged · 1 changed (advisory) · 3 NOT MEASURED · 2 usage
29
+ # Exit (snap): 0 written or kept · 3 could not write · 2 usage
30
+ set -uo pipefail
31
+
32
+ MODE="${1:-}"; shift 2>/dev/null || true
33
+ FH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
34
+ H="${HOME:-}"
35
+ OUT=""
36
+ SRC="unknown"
37
+ while [ $# -gt 0 ]; do
38
+ case "$1" in
39
+ --fh) [ -n "${2:-}" ] || { echo "usage: --fh needs a path" >&2; exit 2; }; FH="$2"; shift 2 ;;
40
+ --home) [ -n "${2:-}" ] || { echo "usage: --home needs a path" >&2; exit 2; }; H="$2"; shift 2 ;;
41
+ --out) [ -n "${2:-}" ] || { echo "usage: --out needs a path" >&2; exit 2; }; OUT="$2"; shift 2 ;;
42
+ --source) SRC="${2:-unknown}"; shift 2 ;;
43
+ *) echo "usage: unknown argument: $1" >&2; exit 2 ;;
44
+ esac
45
+ done
46
+ [ -n "$OUT" ] || OUT="$FH/tracks/_meta/.session_config_fingerprint"
47
+ SID="${CLAUDE_CODE_SESSION_ID:-pid-${PPID:-$$}}"
48
+
49
+ _mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo "?"; }
50
+ _hash() {
51
+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" 2>/dev/null | awk '{print $1}'
52
+ elif command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" 2>/dev/null | awk '{print $1}'
53
+ else cksum "$1" 2>/dev/null | awk '{print "cksum-"$1"-"$2}'; fi
54
+ }
55
+ # label<TAB>path — labels are what the report prints, so they never carry an absolute home path.
56
+ _targets() {
57
+ printf 'repo:.claude/settings.json\t%s\n' "$FH/.claude/settings.json"
58
+ printf 'repo:.claude/settings.local.json\t%s\n' "$FH/.claude/settings.local.json"
59
+ printf 'repo:CLAUDE.local.md\t%s\n' "$FH/CLAUDE.local.md"
60
+ printf 'repo:CLAUDE.md\t%s\n' "$FH/CLAUDE.md"
61
+ printf 'home:~/.claude/settings.json\t%s\n' "$H/.claude/settings.json"
62
+ printf 'home:~/.claude/CLAUDE.md\t%s\n' "$H/.claude/CLAUDE.md"
63
+ }
64
+ # one line per target: label<TAB>state<TAB>hash<TAB>mtime (state PRESENT|ABSENT|UNREADABLE)
65
+ _measure() {
66
+ _targets | while IFS="$(printf '\t')" read -r label path; do
67
+ if [ ! -e "$path" ]; then printf '%s\tABSENT\t-\t-\n' "$label"
68
+ elif [ ! -r "$path" ]; then printf '%s\tUNREADABLE\t-\t-\n' "$label"
69
+ else
70
+ h="$(_hash "$path")"
71
+ if [ -n "$h" ]; then printf '%s\tPRESENT\t%s\t%s\n' "$label" "$h" "$(_mtime "$path")"
72
+ else printf '%s\tUNREADABLE\t-\t-\n' "$label"; fi
73
+ fi
74
+ done
75
+ }
76
+
77
+ case "$MODE" in
78
+ snap)
79
+ if [ -f "$OUT" ]; then
80
+ prev_sid="$(sed -n '/^session=/{s/^session=//p;q;}' "$OUT" 2>/dev/null)"
81
+ case "$SRC" in
82
+ clear|compact) if [ "$prev_sid" = "$SID" ]; then exit 0; fi ;;
83
+ esac
84
+ fi
85
+ mkdir -p "$(dirname "$OUT")" 2>/dev/null
86
+ tmp="$OUT.tmp.$$"
87
+ { printf 'session=%s\nat=%s\nsource=%s\n' "$SID" "$(date +%s)" "$SRC"; _measure; } > "$tmp" 2>/dev/null \
88
+ && mv "$tmp" "$OUT" 2>/dev/null && exit 0
89
+ rm -f "$tmp" 2>/dev/null; exit 3 ;;
90
+ compare)
91
+ if [ ! -r "$OUT" ]; then
92
+ echo "⚠️ config fingerprint NOT MEASURED — no session-start snapshot ($(basename "$OUT"))."
93
+ echo " No snapshot is not «no change». The snap runs from scripts/fh_session_load.sh at SessionStart."
94
+ exit 3
95
+ fi
96
+ snap_sid="$(sed -n '/^session=/{s/^session=//p;q;}' "$OUT")"
97
+ now="$(_measure)"
98
+ changed=""; n=0; touched=""
99
+ while IFS="$(printf '\t')" read -r label state hash mt; do
100
+ [ -n "$label" ] || continue
101
+ old="$(awk -F'\t' -v l="$label" '$1==l {print $2"\t"$3"\t"$4; exit}' "$OUT")"
102
+ if [ -z "$old" ]; then changed="$changed
103
+ ↳ $label — not in snapshot (NOT MEASURED)"; n=$((n+1)); continue; fi
104
+ old_state="${old%% *}"; _rest="${old#* }"; old_hash="${_rest%% *}"; old_mt="${_rest#* }"
105
+ if [ "$state" = UNREADABLE ] || [ "$old_state" = UNREADABLE ]; then
106
+ changed="$changed
107
+ ↳ $label — unreadable now or at start (NOT MEASURED)"; n=$((n+1))
108
+ elif [ "$state" != "$old_state" ]; then
109
+ changed="$changed
110
+ ↳ $label — $old_state → $state"; n=$((n+1))
111
+ elif [ "$hash" != "$old_hash" ]; then
112
+ changed="$changed
113
+ ↳ $label — content changed"; n=$((n+1))
114
+ elif [ "$state" = PRESENT ] && [ "$mt" != "$old_mt" ]; then
115
+ # 🟥 2026-09-26 (cross-family): mtime was snapped and never compared. Decision: the content
116
+ # hash is the verdict (a rewrite with identical bytes restores nothing and loses nothing),
117
+ # but a touch is still a sign something wrote there — so it is REPORTED separately and
118
+ # NOT counted as a change. Folding it into «changed» would cry wolf on every editor save;
119
+ # dropping it would hide the one trace a same-bytes rewrite leaves.
120
+ touched="$touched
121
+ ↳ $label — touched (내용 동일, mtime only)"
122
+ fi
123
+ done <<EOF_NOW
124
+ $now
125
+ EOF_NOW
126
+ note=""
127
+ [ "$snap_sid" = "$SID" ] || note=" (snapshot belongs to session $snap_sid, not this one — baseline may be older)"
128
+ if [ "$n" -eq 0 ]; then
129
+ echo "✅ config fingerprint: none of the 6 config files changed since session start$note"
130
+ [ -z "$touched" ] || echo " ⓘ written without content change (advisory, not counted):$touched"
131
+ exit 0
132
+ fi
133
+ echo "⚠️ config fingerprint: $n config file(s) changed since session start$note$changed"
134
+ [ -z "$touched" ] || echo " ⓘ written without content change (advisory, not counted):$touched"
135
+ echo " Intended change → ignore. Not yours → back it up now and recover per"
136
+ echo " knowledge/shared/harness-core/checkout_layer_drift.md §Config-Overwrite-Recovery"
137
+ exit 1 ;;
138
+ *) sed -n '2,30p' "$0"; exit 2 ;;
139
+ esac
@@ -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
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env bash
2
+ # test_session_config_fingerprint_lanes.sh — lanes for scripts/session_config_fingerprint.sh and
3
+ # its consumer ④-f of scripts/session_close_check.sh. Uses a scratch FH root and a scratch HOME
4
+ # only — the operator's real ~/.claude and this repo's gitignored files are never read or written.
5
+ #
6
+ # Defect pinned (2026-09-26): a sub-agent's measurement run overwrote this checkout's .claude/settings.json and
7
+ # CLAUDE.md mid-session and nothing noticed. Revert probe at the end: a mutant compare that only
8
+ # checks «file present» must go red on the one-file-changed fixture.
9
+ # Runs under bash 3.2 (/bin/bash) and bash 5.
10
+ set -uo pipefail
11
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
12
+ ROOT="$(cd "$HERE/.." && pwd)"
13
+ SUBJ="$ROOT/scripts/session_config_fingerprint.sh"
14
+ CLOSE="$ROOT/scripts/session_close_check.sh"
15
+ T="$(mktemp -d 2>/dev/null || mktemp -d -t cfgfp)"
16
+ [ -n "$T" ] && [ -d "$T" ] || { echo "HARNESS-ERROR: mktemp failed"; exit 2; }
17
+ trap 'rm -rf "$T"' EXIT
18
+ pass=0; fail=0
19
+ chk() { if [ "$1" -eq 0 ]; then echo " ✅ $2"; pass=$((pass+1)); else echo " ❌ $2"; fail=$((fail+1)); fi; }
20
+ [ -f "$SUBJ" ] || { echo "HARNESS-ERROR: subject missing: $SUBJ"; exit 2; }
21
+
22
+ FHR="$T/fh"; HM="$T/home"
23
+ mkdir -p "$FHR/.claude" "$FHR/scripts" "$HM/.claude"
24
+ echo '{"a":1}' > "$FHR/.claude/settings.json"
25
+ echo 'local' > "$FHR/CLAUDE.local.md"
26
+ echo '# hub' > "$FHR/CLAUDE.md"
27
+ echo '{"h":1}' > "$HM/.claude/settings.json"
28
+ cp "$SUBJ" "$FHR/scripts/"
29
+ export CLAUDE_CODE_SESSION_ID="lane-session-1"
30
+ fp() { bash "$FHR/scripts/session_config_fingerprint.sh" "$@" --fh "$FHR" --home "$HM"; }
31
+ SNAP="$FHR/tracks/_meta/.session_config_fingerprint"
32
+
33
+ echo "── no snapshot ──"
34
+ out=$(fp compare 2>&1); rc=$?
35
+ [ "$rc" -eq 3 ]; chk $? "no snapshot → rc 3"
36
+ printf '%s\n' "$out" | grep -q 'NOT MEASURED'; chk $? "no snapshot → says NOT MEASURED (not «unchanged»)"
37
+
38
+ echo "── snapshot + unchanged ──"
39
+ fp snap >/dev/null 2>&1; [ -f "$SNAP" ]; chk $? "snap writes the snapshot under tracks/_meta"
40
+ grep -q '^session=lane-session-1$' "$SNAP"; chk $? "snapshot carries the session id"
41
+ [ "$(grep -c ' ' "$SNAP")" -eq 6 ]; chk $? "snapshot has one row per target (6)"
42
+ grep -q "$HM" "$SNAP"; [ $? -ne 0 ]; chk $? "snapshot rows carry labels, not the absolute home path"
43
+ out=$(fp compare 2>&1); rc=$?
44
+ [ "$rc" -eq 0 ]; chk $? "nothing changed → rc 0 (quiet)"
45
+ printf '%s\n' "$out" | grep -q '↳'; [ $? -ne 0 ]; chk $? "nothing changed → names no file"
46
+
47
+ echo "── one file changed ──"
48
+ echo '{"a":2}' > "$FHR/.claude/settings.json"
49
+ out=$(fp compare 2>&1); rc=$?
50
+ [ "$rc" -eq 1 ]; chk $? "one change → rc 1 (advisory)"
51
+ printf '%s\n' "$out" | grep -q 'repo:.claude/settings.json — content changed'; chk $? "names the changed file"
52
+ [ "$(printf '%s\n' "$out" | grep -c '↳')" -eq 1 ]; chk $? "names ONLY that file"
53
+ printf '%s\n' "$out" | grep -q '§Config-Overwrite-Recovery'; chk $? "points at the recovery procedure (repo doc, not memory)"
54
+ grep -q '^## 9. Config-Overwrite-Recovery' "$ROOT/knowledge/shared/harness-core/checkout_layer_drift.md"
55
+ chk $? "the pointed-at section exists"
56
+ echo '{"a":1}' > "$FHR/.claude/settings.json"
57
+
58
+ echo "── home file appears / clear keeps baseline ──"
59
+ echo 'x' > "$HM/.claude/CLAUDE.md"
60
+ out=$(fp compare 2>&1)
61
+ printf '%s\n' "$out" | grep -q 'home:~/.claude/CLAUDE.md — ABSENT → PRESENT'; chk $? "a home config file appearing is named"
62
+ fp snap --source clear >/dev/null 2>&1
63
+ out=$(fp compare 2>&1); rc=$?
64
+ [ "$rc" -eq 1 ]; chk $? "/clear in the same session keeps the baseline (evidence not erased)"
65
+ CLAUDE_CODE_SESSION_ID="lane-session-2" bash "$FHR/scripts/session_config_fingerprint.sh" snap --fh "$FHR" --home "$HM" --source clear >/dev/null 2>&1
66
+ grep -q '^session=lane-session-2$' "$SNAP"; chk $? "a NEW session re-snaps even on source=clear"
67
+ rm -f "$HM/.claude/CLAUDE.md"
68
+ export CLAUDE_CODE_SESSION_ID="lane-session-2"
69
+ fp snap >/dev/null 2>&1
70
+
71
+ echo "── touched, same bytes (cross-family 2026-09-26) ──"
72
+ cp "$FHR/CLAUDE.local.md" "$T/cl.bak"; touch -t 202001010000 "$FHR/CLAUDE.local.md"
73
+ out=$(fp compare 2>&1); rc=$?
74
+ [ "$rc" -eq 0 ] && printf '%s\n' "$out" | grep -q 'repo:CLAUDE.local.md — touched (내용 동일'
75
+ chk $? "mtime-only change → rc 0, reported separately as touched (not counted as a change)"
76
+ printf '%s\n' "$out" | grep -q 'content changed'; [ $? -ne 0 ]; chk $? " … and not reported as content changed"
77
+ fp snap >/dev/null 2>&1
78
+
79
+ echo "── unreadable is not unchanged ──"
80
+ if [ "$(id -u)" != 0 ]; then
81
+ chmod 000 "$FHR/CLAUDE.local.md"
82
+ out=$(fp compare 2>&1); rc=$?
83
+ chmod 644 "$FHR/CLAUDE.local.md"
84
+ [ "$rc" -eq 1 ] && printf '%s\n' "$out" | grep -q 'CLAUDE.local.md — unreadable'
85
+ chk $? "file turned unreadable → named as NOT MEASURED, not folded into «unchanged»"
86
+ else
87
+ echo " ⏭️ unreadable lane skipped (root) — not a pass"
88
+ fi
89
+
90
+ echo "── consumer ④-f ──"
91
+ cp "$CLOSE" "$FHR/scripts/session_close_check.sh"
92
+ echo '# hub changed' > "$FHR/CLAUDE.md"
93
+ out=$(bash "$FHR/scripts/session_close_check.sh" "$FHR" 2>&1)
94
+ printf '%s\n' "$out" | grep -q '^④-f .*repo:CLAUDE.md — content changed'; chk $? "close check ④-f names the overwritten CLAUDE.md"
95
+ echo '# hub' > "$FHR/CLAUDE.md"
96
+ rm -f "$SNAP"
97
+ out=$(bash "$FHR/scripts/session_close_check.sh" "$FHR" 2>&1)
98
+ printf '%s\n' "$out" | grep -q '^④-f .*NOT MEASURED'; chk $? "close check ④-f with no snapshot → NOT MEASURED"
99
+ mkdir -p "$T/stubroot/scripts"; cp "$CLOSE" "$T/stubroot/scripts/session_close_check.sh"
100
+ printf '#!/bin/sh\necho stub-output\nexit 7\n' > "$T/stubroot/scripts/session_config_fingerprint.sh"
101
+ out=$(bash "$T/stubroot/scripts/session_close_check.sh" "$T/stubroot" 2>&1)
102
+ printf '%s\n' "$out" | grep -q '④-f .*checker exited 7'; chk $? "④-f keeps the checker's rc (exit 7 → instrument error named, not hidden by the sed decoration)"
103
+ wired=$(grep -c 'session_config_fingerprint.sh" snap' "$ROOT/scripts/fh_session_load.sh")
104
+ [ "$wired" -ge 1 ]; chk $? "snap is wired into fh_session_load.sh (SessionStart)"
105
+
106
+ echo "── revert probe: compare that only checks presence ──"
107
+ sed 's/elif \[ "\$hash" != "\$old_hash" \]; then/elif false; then # MUTANT-NO-HASH/' "$SUBJ" > "$T/mutant.sh"
108
+ grep -q 'MUTANT-NO-HASH' "$T/mutant.sh"; chk $? "mutation applied (control for the probe itself)"
109
+ fp snap >/dev/null 2>&1
110
+ echo '{"a":9}' > "$FHR/.claude/settings.json"
111
+ bash "$T/mutant.sh" compare --fh "$FHR" --home "$HM" >/dev/null 2>&1; mrc=$?
112
+ [ "$mrc" -eq 0 ]; chk $? "mutant reports «unchanged» on the one-file-changed fixture → the «names the changed file» lane would be RED"
113
+
114
+ echo
115
+ if [ "$fail" -eq 0 ]; then echo "CONFIG-FINGERPRINT LANES: PASS ($pass/$pass)"; exit 0; fi
116
+ echo "CONFIG-FINGERPRINT LANES: FAIL ($fail failed, $pass passed)"; exit 1
@@ -63,27 +63,31 @@ old() { printf '%s\n' "$(date +%Y-%m-%d)" >> "$1"; }
63
63
  f="$T/old"; printf '%s' "$P_INTERNAL" | old "$f"
64
64
  [ "$(grep -c "^$TODAY$" "$f")" = 1 ] ; chk $? "control alive: date-only append DOES count compaction — the defect this lane exists for"
65
65
 
66
+ # 🟥 millisecond timer — whole-second `date +%s` rounds a 3.2 s run up to 4 or 5 across a second boundary,
67
+ # and under full-selfcheck load that alone turned the deadline lane red (2026-09-26, 607/608). perl is on
68
+ # every macOS/Linux runner this repo supports; missing perl → 99999 (loud red, never a silent pass).
69
+ now_ms() { perl -MTime::HiRes=time -e 'printf "%d", time*1000' 2>/dev/null || echo 0; }
66
70
  echo "── stdin never closed (the caller keeps the pipe open) → still counts, within the limit"
67
71
  f="$T/open"
68
72
  # 🟥 time the HOOK only — timing the whole pipeline also waits for the producer's `sleep`.
69
- ( sleep 5 ) | { s0=$(date +%s); FH_TALLY_FILE="$f" bash "$SUBJ"; echo $(( $(date +%s) - s0 )) > "$f.dur"; }
70
- dur=$(cat "$f.dur" 2>/dev/null || echo 99)
73
+ ( sleep 5 ) | { s0=$(now_ms); FH_TALLY_FILE="$f" bash "$SUBJ"; s1=$(now_ms); [ "$s0" -gt 0 ] && [ "$s1" -gt 0 ] && echo $(( s1 - s0 )) > "$f.dur" || echo 99999 > "$f.dur"; }
74
+ dur=$(cat "$f.dur" 2>/dev/null || echo 99999)
71
75
  [ "$(grep -c "^$TODAY$" "$f" 2>/dev/null || echo 0)" = 1 ] ; chk $? "open, silent stdin → counted (a bare \`cat\` blocked here until the hook was killed)"
72
- [ "$dur" -le 4 ] ; chk $? "and the hook returned by its read limit, not at the caller's EOF (${dur}s)"
76
+ [ "$dur" -le 4000 ] ; chk $? "and the hook returned by its read limit, not at the caller's EOF (${dur} ms)"
73
77
  f="$T/open2"; ( printf '%s' "$P_INTERNAL"; sleep 5 ) | FH_TALLY_FILE="$f" bash "$SUBJ"
74
78
  [ "$(grep -c "^$TODAY$" "$f" 2>/dev/null || echo 0)" = 0 ] ; chk $? "payload delivered but pipe left open → still classified (internal skipped)"
75
79
 
76
80
  f="$T/nul"; printf '%s\0 ' "$P_INTERNAL" | FH_TALLY_FILE="$f" bash "$SUBJ"
77
81
  [ "$(grep -c "^$TODAY$" "$f" 2>/dev/null || echo 0)" = 1 ] ; chk $? "raw NUL after an internal payload → counted (OUTCOME lane: json rejects NUL — the bash reader that turned it into whitespace is gone; codex 2026-09-25)"
78
- f="$T/big"; { printf '{"agent_type":"","pad":"'; head -c 9000000 /dev/zero | tr '\0' x; printf '"}'; } | { s0=$(date +%s); FH_TALLY_FILE="$f" bash "$SUBJ"; echo $(( $(date +%s) - s0 )) > "$f.dur"; }; e=$(cat "$f.dur" 2>/dev/null || echo 99)
82
+ f="$T/big"; { printf '{"agent_type":"","pad":"'; head -c 9000000 /dev/zero | tr '\0' x; printf '"}'; } | { s0=$(now_ms); FH_TALLY_FILE="$f" bash "$SUBJ"; s1=$(now_ms); [ "$s0" -gt 0 ] && [ "$s1" -gt 0 ] && echo $(( s1 - s0 )) > "$f.dur" || echo 99999 > "$f.dur"; }; e=$(cat "$f.dur" 2>/dev/null || echo 99999)
79
83
  [ "$(grep -c "^$TODAY$" "$f" 2>/dev/null || echo 0)" = 1 ] ; chk $? "payload over the 8 MiB cap → truncated → DOUBT → counted"
80
- [ "$e" -le 8 ] ; chk $? "and the cap bounds the read time (${e}s)"
84
+ [ "$e" -le 8000 ] ; chk $? "and the cap bounds the read time (${e} ms)"
81
85
 
82
86
  # 🟥 time the HOOK only (see the «stdin never closed» lane above) — CI runners ignore SIGPIPE, so the
83
87
  # producer keeps sleeping after the hook exits and a whole-pipeline timer read 8 s there (4 s on macOS).
84
- f="$T/trickle"; ( for i in 1 2 3 4 5 6 7 8; do printf ' '; sleep 1; done; printf '%s' "$P_INTERNAL" ) | { s0=$(date +%s); FH_TALLY_FILE="$f" bash "$SUBJ"; echo $(( $(date +%s) - s0 )) > "$f.dur"; }; e=$(cat "$f.dur" 2>/dev/null || echo 99)
88
+ f="$T/trickle"; ( for i in 1 2 3 4 5 6 7 8; do printf ' '; sleep 1; done; printf '%s' "$P_INTERNAL" ) | { s0=$(now_ms); FH_TALLY_FILE="$f" bash "$SUBJ"; s1=$(now_ms); [ "$s0" -gt 0 ] && [ "$s1" -gt 0 ] && echo $(( s1 - s0 )) > "$f.dur" || echo 99999 > "$f.dur"; }; e=$(cat "$f.dur" 2>/dev/null || echo 99999)
85
89
  [ "$(grep -c "^$TODAY$" "$f" 2>/dev/null || echo 0)" = 1 ] ; chk $? "slow trickle (1 byte/s, never idle 2 s) → deadline cuts it → counted"
86
- [ "$e" -le 4 ] ; chk $? "and the deadline lands inside the settings.json hook timeout (5 s) with margin (${e}s — a 5 s deadline raced the kill, which lands BEFORE the append)"
90
+ [ "$e" -le 4500 ] ; chk $? "and the deadline lands inside the settings.json hook timeout (5 s) with margin (${e} ms — a 5 s deadline raced the kill, which lands BEFORE the append)"
87
91
 
88
92
  echo "── wiring: EXECUTE the shipped template command (a grep for the path matched the _readme text)"
89
93
  TPL="$SCRIPT_DIR/../templates/subagent-tally-hook.json"
@@ -112,6 +112,17 @@ Unlisted tool name → **ask** (fail-closed), then add it to the table. Listed-b
112
112
  is the same case: a name in the table earns its allow tier from confirmed behavior (§1),
113
113
  not from sounding harmless.
114
114
 
115
+ > ⚠️ **"ask" stops a call only if nothing answers the prompt for you** (measured 2026-09-25,
116
+ > Claude Code 2.1.282, interactive): a `PreToolUse` hook returning **ask** was *swallowed* when a
117
+ > `PermissionRequest` hook answered **allow** — the call ran **5/5** (auto mode 3 · acceptEdits 2).
118
+ > A hook returning **deny** stopped it **0/2** landed. Headless runs went the other way (the
119
+ > `PermissionRequest` hook was not called after ask), so the result is surface-specific. So under
120
+ > any auto-approver (a `PermissionRequest` allow hook, a desktop approval app, a wrapper that
121
+ > clicks "yes"), an ask-tier call is **not** fail-closed — only **deny / exit 2** stops it. Not
122
+ > measured: auto mode *without* such a hook (one run, did not land — below bar), and whether a
123
+ > `permissions.ask` **rule** (step 4 below) is swallowed the same way. Detail:
124
+ > `knowledge/shared/harness-core/hook_channel_visibility.md`.
125
+
115
126
  ## 3. Per-server table ([CUSTOMIZE] — fill at mount time)
116
127
 
117
128
  | Server | Tool name | Tier | Note |
@@ -127,7 +138,10 @@ not from sounding harmless.
127
138
  3. Anything that writes outside the repo, or grants/answers an approval → ask.
128
139
  4. Where supported, mirror the ask-tier into the platform's permission config
129
140
  (e.g. Claude Code `permissions.ask` entries for `mcp__{server}__{tool}`) so the
130
- gate is mechanical, not prose-only. This rule file is the fallback for hosts
141
+ gate is mechanical, not prose-only. ⚠️ Mechanical against a human at the prompt — whether an
142
+ auto-approver answers a `permissions.ask` rule the way it answered a hook's ask (§2 note)
143
+ is **unmeasured**; where one is installed, use a `permissions.deny` entry for calls that
144
+ must never run unattended. This rule file is the fallback for hosts
131
145
  without per-tool permission config.
132
146
  5. For `http`/`sse`-transport servers, record the resolved endpoint address at mount
133
147
  (host + path) in the §3 table's Note column. This checklist gates tool *behavior*
@@ -151,6 +165,8 @@ Done When (per mounted server):
151
165
  - §3 table filled, every enumerated tool name present (check class: mandatory-pass — file inspection)
152
166
  - ask-tier tools wired to a per-call approval surface: host per-tool permission entry exists,
153
167
  or this rule file is installed and loaded in the session (check class: mandatory-pass)
168
+ — and if the session runs under an auto-approver, the surface is a **deny** entry, not ask
169
+ (§2 note; check class: mandatory-pass — grep the settings for a `PermissionRequest` hook)
154
170
  - non-ask tiers assigned only with a behavior-confirmation note in the §3 Note column
155
171
  (check class: judged — pair with an adversarial pass asking "could this name mislead?")
156
172
  - for `http`/`sse`-transport servers, the mounted endpoint address is recorded in §3