@chrono-meta/fh-gate 3.22.2 → 3.24.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.
@@ -0,0 +1,371 @@
1
+ #!/usr/bin/env python3
2
+ # resident_cost.py — 세션 시작 «전» 상주 비용을 한 번에 재는 읽기 전용 계기 (2026-10-01 신설).
3
+ #
4
+ # 왜: 경량화를 논의하기 전에 «얼마인가» 를 같은 정의로 재야 한다. 2026-09-30 하루에 두 번 틀렸다 —
5
+ # ① CLAUDE.md 를 `wc -c`(바이트)로 재서 «153k 자» 라고 말했다(실제 136,889자 — 한글 1자 = 3바이트)
6
+ # ② 스킬 설명 합을 한 줄 파싱으로 재서 25,488 이라 적었다(YAML 파싱 = 19,473 — 접힌 블록 `>-` 를 못 읽음)
7
+ # 둘 다 계기가 없어서 생긴 오류다(tracks/_meta/research_2026-09-30_fh-lightweight-environment.md 부록).
8
+ #
9
+ # 무엇을 세나 — 줄마다 «이름 · 문자 · 바이트 · 출처».
10
+ # 문자 = UTF-8 디코드 후 len(). Claude Code 의 150.0k 경고와 MEMORY 절단이 문자 단위다(아래 보정).
11
+ # 1 레포 CLAUDE.md (tracked) — 150,000자 경고선까지 여유
12
+ # 2 CLAUDE.local.md (gitignored) — 없으면 «없음»(0 아님)
13
+ # 3 사용자 전역 ~/.claude/CLAUDE.md + 그 파일들이 `@경로` 로 import 하는 파일(재귀, 깊이 5, 순환 차단)
14
+ # 4 자동 메모리 MEMORY.md — 전체 · 공식 상한(첫 200줄 또는 25KB) · 이 머신 실측 상한(25,000자)
15
+ # 5 스킬 목록 — plugins/*/skills/*/SKILL.md frontmatter 의 name + description, YAML 파싱(접힌 블록 포함).
16
+ # 한 줄 파싱 값이 다르면 둘 다 낸다
17
+ # 6 .claude/rules/*.md 중 `paths:` 가 없는 것(세션 시작에 상주). paths: 가 있으면 조건부라 0 이 아니라 «조건부»
18
+ # 합계 — 측정 못 한 칸은 0 으로 접지 않고 «미측정 N칸» 을 옆에 적는다.
19
+ #
20
+ # MEMORY 상한 보정 (known-pair, 실물 1건 — 2026-10-01): 이 세션의 로더가 «147 of 285 lines were cut off,
21
+ # starting at "[컨트롤 있음 ≠ 판별력 있음]"» 를 보고했다. 같은 파일에 규칙 셋을 대 보면
22
+ # 25,000 **문자** → 첫 절단 줄 = 바로 그 항목(147줄 절단, 일치) · 25,000 바이트 → 91번째 줄 · 25,600 바이트 → 94번째 줄.
23
+ # ⇒ 이 머신의 실제 상한은 «줄 단위로 25,000자» 다. 공식 문서 문구(200줄/25KB)도 같이 계산해 보인다 — 어긋남 자체가 정보다.
24
+ # 🟥 N=1 이다. 로더가 바뀌면 이 상수부터 다시 재라(--memory-cap-chars).
25
+ #
26
+ # 범위 밖(이름으로 남긴다): 시스템 프롬프트 · 이 레포 밖 플러그인의 스킬 목록 · MCP 도구 설명 · 토큰 수.
27
+ # 그래서 «합계» 는 «FH 가 좌우하는 상주분» 이지 세션 전체 비용이 아니다.
28
+ # CLAUDE.md 크기 «가드» 는 scripts/test_claude_md_size_lanes.sh 가 따로 한다(한계 145,000). 이건 계기지 게이트가 아니다.
29
+ #
30
+ # 사용: python3 scripts/resident_cost.py [--json] [--repo DIR] [--user-claude FILE] [--memory-dir DIR]
31
+ # [--memory-cap-chars N] [--no-user]
32
+ # 환경변수: RESIDENT_COST_REPO · RESIDENT_COST_USER_CLAUDE · RESIDENT_COST_MEMORY_DIR (레인이 픽스처로 돌린다)
33
+ # 종료 코드: 0 = 전 칸 측정 · 3 = 미측정 칸 있음(합계는 나오지만 «전부» 가 아니다) · 2 = 인자 오류
34
+ import argparse
35
+ import glob
36
+ import json
37
+ import os
38
+ import re
39
+ import sys
40
+
41
+ CC_WARN_CHARS = 150000 # Claude Code: «CLAUDE.md is over the 150.0k-char limit»
42
+ MEM_CAP_CHARS_MEASURED = 25000 # 이 머신 실측(위 보정)
43
+ MEM_CAP_LINES_OFFICIAL = 200 # 공식 문서: 첫 200줄
44
+ MEM_CAP_BYTES_OFFICIAL = 25 * 1024 # 공식 문서: 25KB (KiB 로 읽음 — 문서가 단위를 안 밝힌다)
45
+ IMPORT_MAX_DEPTH = 5
46
+
47
+
48
+ def nchars(s):
49
+ return len(s)
50
+
51
+
52
+ def nbytes(s):
53
+ return len(s.encode("utf-8"))
54
+
55
+
56
+ HOME = os.path.expanduser("~")
57
+ _OTHER_HOME = re.compile(r"^(/Users/|/home/)[^/]+")
58
+
59
+
60
+ def show(path, mangled=None):
61
+ """출력용 경로 — 홈은 ~ 로, 메모리 디렉터리의 cwd 변환 이름은 <project> 로 가린다(residency)."""
62
+ p = os.path.abspath(path)
63
+ if mangled and mangled in p:
64
+ p = p.replace(mangled, "<project>")
65
+ if p == HOME or p.startswith(HOME + os.sep):
66
+ return "~" + p[len(HOME):]
67
+ # 남의 홈 경로(인자로 넘어온 것)도 사용자명을 가린다(cross-family R1 #3)
68
+ return _OTHER_HOME.sub(r"\1<user>", p)
69
+
70
+
71
+ def read_text(path):
72
+ """(status, text, err). status ∈ ok · absent · unmeasured."""
73
+ if not os.path.exists(path):
74
+ return "absent", None, None
75
+ try:
76
+ with open(path, encoding="utf-8") as f:
77
+ return "ok", f.read(), None
78
+ except (OSError, UnicodeDecodeError) as e:
79
+ return "unmeasured", None, f"{type(e).__name__}: {e}"
80
+
81
+
82
+ def row(name, path, status, text=None, err=None, mangled=None, **extra):
83
+ r = {"name": name, "source": show(path, mangled), "status": status,
84
+ "chars": None, "bytes": None}
85
+ if status == "ok":
86
+ r["chars"] = nchars(text)
87
+ r["bytes"] = nbytes(text)
88
+ if err:
89
+ r["error"] = err
90
+ r.update(extra)
91
+ return r
92
+
93
+
94
+ # ── @import ────────────────────────────────────────────────────────────────────────────────────────
95
+ _FENCE = re.compile(r"^\s*(```|~~~)")
96
+ _INLINE_CODE = re.compile(r"`[^`]*`")
97
+ _IMPORT = re.compile(r"(?:(?<=\s)|^)@((?:~|\.{1,2})?/?[A-Za-z0-9_.\-/]+)")
98
+
99
+
100
+ def import_tokens(text):
101
+ out, fenced = [], False
102
+ for line in text.splitlines():
103
+ if _FENCE.match(line):
104
+ fenced = not fenced
105
+ continue
106
+ if fenced:
107
+ continue
108
+ for m in _IMPORT.finditer(_INLINE_CODE.sub("", line)):
109
+ tok = m.group(1).rstrip(".,;:)")
110
+ if tok:
111
+ out.append(tok)
112
+ return out
113
+
114
+
115
+ def path_shaped(tok):
116
+ """대상이 없을 때 «해석 실패» 로 보고할 만큼 경로처럼 생겼나. `@me` 같은 맨 낱말은 대상이 없으면 조용히 무시한다.
117
+ 대상이 «있으면» 모양과 무관하게 import 로 센다 — 확장자 없는 `@LICENSE` 도 import 다(cross-family R1 #1)."""
118
+ return "/" in tok or "." in tok
119
+
120
+
121
+ def resolve_import(tok, base_dir):
122
+ if tok.startswith("~"):
123
+ return os.path.expanduser(tok)
124
+ if os.path.isabs(tok):
125
+ return tok
126
+ return os.path.normpath(os.path.join(base_dir, tok))
127
+
128
+
129
+ def follow_imports(path, text, label, rows, unresolved, seen, depth=1):
130
+ if depth > IMPORT_MAX_DEPTH:
131
+ return
132
+ for tok in import_tokens(text):
133
+ target = resolve_import(tok, os.path.dirname(os.path.abspath(path)))
134
+ key = os.path.realpath(target)
135
+ if key in seen:
136
+ continue
137
+ st, t, err = read_text(target)
138
+ if st == "absent":
139
+ if path_shaped(tok):
140
+ unresolved.append({"from": show(path), "token": "@" + tok})
141
+ continue
142
+ seen.add(key)
143
+ rows.append(row(f"{label} → @{tok}", target, st, t, err, depth=depth))
144
+ if st == "ok":
145
+ follow_imports(target, t, label, rows, unresolved, seen, depth + 1)
146
+
147
+
148
+ def claude_file(name, path, rows, unresolved, seen):
149
+ st, t, err = read_text(path)
150
+ r = row(name, path, st, t, err)
151
+ rows.append(r)
152
+ if st == "ok":
153
+ seen.add(os.path.realpath(path))
154
+ follow_imports(path, t, name, rows, unresolved, seen)
155
+ return r
156
+
157
+
158
+ # ── MEMORY.md ──────────────────────────────────────────────────────────────────────────────────────
159
+ def prefix_lines(lines, limit, measure):
160
+ """상한 안에 «통째로» 들어가는 줄 수. 줄 단위로 자른다(로더가 줄을 반으로 자르지 않는다 — 보정 실측)."""
161
+ acc = 0
162
+ for i, ln in enumerate(lines):
163
+ n = measure(ln)
164
+ if acc + n > limit:
165
+ return i
166
+ acc += n
167
+ return len(lines)
168
+
169
+
170
+ def memory_row(mem_dir, cap_chars, mangled):
171
+ path = os.path.join(mem_dir, "MEMORY.md")
172
+ st, t, err = read_text(path)
173
+ r = row("MEMORY.md (자동 메모리)", path, st, t, err, mangled=mangled)
174
+ if st != "ok":
175
+ return r
176
+ lines = t.splitlines(keepends=True)
177
+ n_meas = prefix_lines(lines, cap_chars, nchars)
178
+ loaded = "".join(lines[:n_meas])
179
+ n_line_cap = min(len(lines), MEM_CAP_LINES_OFFICIAL)
180
+ n_byte_cap = prefix_lines(lines, MEM_CAP_BYTES_OFFICIAL, nbytes)
181
+ n_off = min(n_line_cap, n_byte_cap)
182
+ official_binds = ("없음(전체 적재)" if n_off == len(lines)
183
+ else "200줄" if n_line_cap < n_byte_cap
184
+ else "25KB" if n_byte_cap < n_line_cap else "200줄=25KB 동시")
185
+ off = "".join(lines[:n_off])
186
+ r.update({
187
+ "lines": len(lines),
188
+ "loaded_chars": nchars(loaded), "loaded_bytes": nbytes(loaded),
189
+ "loaded_lines": n_meas, "cut_lines": len(lines) - n_meas,
190
+ "cap_rule": f"줄 단위 {cap_chars:,}자 (이 머신 실측)",
191
+ "official": {"lines": n_off, "chars": nchars(off), "bytes": nbytes(off),
192
+ "binds_first": official_binds,
193
+ "rule": f"첫 {MEM_CAP_LINES_OFFICIAL}줄 또는 25KB({MEM_CAP_BYTES_OFFICIAL:,} bytes)"},
194
+ })
195
+ return r
196
+
197
+
198
+ # ── skills ─────────────────────────────────────────────────────────────────────────────────────────
199
+ _FM = re.compile(r"\A---\r?\n(.*?)\r?\n---\r?\n", re.S)
200
+
201
+
202
+ def oneline_value(fm_text, key):
203
+ for line in fm_text.splitlines():
204
+ if line.startswith(key + ":"):
205
+ return line[len(key) + 1:].strip()
206
+ return ""
207
+
208
+
209
+ def skills_row(repo):
210
+ pattern = os.path.join(repo, "plugins", "*", "skills", "*", "SKILL.md")
211
+ files = sorted(glob.glob(pattern))
212
+ src = os.path.join(repo, "plugins", "*", "skills", "*", "SKILL.md")
213
+ if not files:
214
+ return row("스킬 목록 (name+description)", src, "absent", files=0)
215
+ try:
216
+ import yaml # noqa: WPS433 — 없으면 YAML 칸만 미측정, 한 줄 값은 그대로 낸다
217
+ except ImportError:
218
+ yaml = None
219
+ y_name = y_desc = o_name = o_desc = 0
220
+ y_bytes = 0
221
+ bad = []
222
+ for p in files:
223
+ st, t, err = read_text(p)
224
+ m = _FM.match(t or "") if st == "ok" else None
225
+ if not m:
226
+ bad.append(show(p) + (f" ({err})" if err else " (frontmatter 없음)"))
227
+ continue
228
+ fm = m.group(1)
229
+ o_name += nchars(oneline_value(fm, "name"))
230
+ o_desc += nchars(oneline_value(fm, "description"))
231
+ if yaml is not None:
232
+ try:
233
+ d = yaml.safe_load(fm) or {}
234
+ except yaml.YAMLError as e:
235
+ bad.append(f"{show(p)} (YAML: {str(e).splitlines()[0]})")
236
+ continue
237
+ nm, ds = str(d.get("name", "") or ""), str(d.get("description", "") or "")
238
+ y_name += nchars(nm)
239
+ y_desc += nchars(ds)
240
+ y_bytes += nbytes(nm) + nbytes(ds)
241
+ r = {"name": "스킬 목록 (name+description)", "source": show(src), "files": len(files),
242
+ "oneline": {"chars": o_name + o_desc, "desc_chars": o_desc}}
243
+ if yaml is None:
244
+ r.update(status="unmeasured", chars=None, bytes=None,
245
+ error="PyYAML 없음 — YAML 파싱 칸 미측정(한 줄 파싱 값은 접힌 블록을 못 읽으니 대신 쓰지 않는다)")
246
+ elif bad:
247
+ r.update(status="unmeasured", chars=None, bytes=None, error="파싱 실패: " + "; ".join(bad))
248
+ else:
249
+ r.update(status="ok", chars=y_name + y_desc, bytes=y_bytes, desc_chars=y_desc)
250
+ r["oneline_differs"] = (o_name + o_desc) != (y_name + y_desc)
251
+ return r
252
+
253
+
254
+ # ── rules ──────────────────────────────────────────────────────────────────────────────────────────
255
+ def rules_rows(repo):
256
+ out = []
257
+ for p in sorted(glob.glob(os.path.join(repo, ".claude", "rules", "*.md"))):
258
+ st, t, err = read_text(p)
259
+ r = row(".claude/rules/" + os.path.basename(p), p, st, t, err)
260
+ if st == "ok":
261
+ m = _FM.match(t)
262
+ if m and re.search(r"^paths\s*:", m.group(1), re.M):
263
+ r["status"] = "conditional" # 그 경로를 읽을 때만 실린다 — 시작 상주 아님
264
+ out.append(r)
265
+ return out
266
+
267
+
268
+ def mangle(cwd):
269
+ return re.sub(r"[^A-Za-z0-9]", "-", os.path.abspath(cwd))
270
+
271
+
272
+ def main(argv):
273
+ ap = argparse.ArgumentParser(description="세션 시작 상주 비용 계기(읽기 전용)")
274
+ ap.add_argument("--json", action="store_true")
275
+ ap.add_argument("--repo", default=os.environ.get("RESIDENT_COST_REPO"))
276
+ ap.add_argument("--user-claude", default=os.environ.get("RESIDENT_COST_USER_CLAUDE"))
277
+ ap.add_argument("--memory-dir", default=os.environ.get("RESIDENT_COST_MEMORY_DIR"))
278
+ ap.add_argument("--memory-cap-chars", type=int, default=MEM_CAP_CHARS_MEASURED)
279
+ ap.add_argument("--no-user", action="store_true", help="사용자 전역 CLAUDE.md 줄을 뺀다")
280
+ a = ap.parse_args(argv)
281
+
282
+ repo = a.repo or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
283
+ if not os.path.isdir(repo):
284
+ print(f"resident_cost: --repo 가 디렉터리가 아니다: {repo}", file=sys.stderr)
285
+ return 2
286
+ repo = os.path.abspath(repo)
287
+ mangled = mangle(repo)
288
+ mem_dir = a.memory_dir or os.path.join(HOME, ".claude", "projects", mangled, "memory")
289
+ user_claude = a.user_claude or os.path.join(HOME, ".claude", "CLAUDE.md")
290
+
291
+ rows, unresolved, seen = [], [], set()
292
+ main_row = claude_file("CLAUDE.md (레포, tracked)", os.path.join(repo, "CLAUDE.md"), rows, unresolved, seen)
293
+ claude_file("CLAUDE.local.md (gitignored)", os.path.join(repo, "CLAUDE.local.md"), rows, unresolved, seen)
294
+ if not a.no_user:
295
+ claude_file("~/.claude/CLAUDE.md (사용자 전역)", user_claude, rows, unresolved, seen)
296
+ mem = memory_row(mem_dir, a.memory_cap_chars, mangled)
297
+ rows.append(mem)
298
+ rows.append(skills_row(repo))
299
+ rows.extend(rules_rows(repo))
300
+
301
+ total_c = total_b = 0
302
+ unmeasured = []
303
+ for r in rows:
304
+ if r["status"] == "unmeasured":
305
+ unmeasured.append(r["name"])
306
+ elif r["status"] == "ok":
307
+ c = r.get("loaded_chars", r["chars"])
308
+ b = r.get("loaded_bytes", r["bytes"])
309
+ total_c += c
310
+ total_b += b
311
+ headroom = (CC_WARN_CHARS - main_row["chars"]) if main_row["status"] == "ok" else None
312
+ result = {
313
+ "rows": rows, "unresolved_imports": unresolved,
314
+ "claude_md_warn_line": CC_WARN_CHARS, "claude_md_headroom": headroom,
315
+ "total": {"chars": total_c, "bytes": total_b, "unmeasured_cells": len(unmeasured),
316
+ "unmeasured": unmeasured,
317
+ "note": "MEMORY 는 적재분만 · rules 는 paths 없는 것만 · 스킬은 이 레포 것만"},
318
+ "scope_excluded": ["시스템 프롬프트", "이 레포 밖 플러그인 스킬 목록", "MCP 도구 설명", "토큰 수"],
319
+ }
320
+ if a.json:
321
+ print(json.dumps(result, ensure_ascii=False, indent=2))
322
+ else:
323
+ render(result)
324
+ return 3 if unmeasured else 0
325
+
326
+
327
+ def fmt(n):
328
+ return "—" if n is None else f"{n:,}"
329
+
330
+
331
+ def render(res):
332
+ label = {"absent": "없음", "unmeasured": "미측정", "conditional": "조건부(paths)"}
333
+ print(f"{'이름':<44} {'문자':>9} {'바이트':>9} 출처")
334
+ for r in res["rows"]:
335
+ st = r["status"]
336
+ if st == "ok":
337
+ c, b = fmt(r["chars"]), fmt(r["bytes"])
338
+ else:
339
+ c, b = label[st], ""
340
+ print(f"{r['name']:<44} {c:>9} {b:>9} {r['source']}")
341
+ if "loaded_chars" in r:
342
+ o = r["official"]
343
+ print(f"{' └ 적재분 (' + r['cap_rule'] + ')':<44} {fmt(r['loaded_chars']):>9} {fmt(r['loaded_bytes']):>9}"
344
+ f" {r['loaded_lines']}/{r['lines']}줄 · 절단 {r['cut_lines']}줄")
345
+ print(f"{' └ 공식 문구 (' + o['rule'] + ')':<44} {fmt(o['chars']):>9} {fmt(o['bytes']):>9}"
346
+ f" {o['lines']}/{r['lines']}줄 · 먼저 걸리는 쪽 = {o['binds_first']}")
347
+ if "oneline" in r:
348
+ ol = r["oneline"]
349
+ if st == "ok" and r.get("oneline_differs"):
350
+ print(f"{' └ 한 줄 파싱 (접힌 블록 못 읽음)':<44} {fmt(ol['chars']):>9} {'':>9}"
351
+ f" {r['files']}파일 · YAML 설명만 {fmt(r['desc_chars'])} / 한 줄 설명만 {fmt(ol['desc_chars'])}")
352
+ elif st == "ok":
353
+ print(f"{' └ 한 줄 파싱 = YAML 파싱 (일치)':<44} {'':>9} {'':>9} {r['files']}파일")
354
+ else:
355
+ print(f"{' └ 한 줄 파싱 (참고용)':<44} {fmt(ol['chars']):>9}")
356
+ if r.get("error"):
357
+ print(f" ! {r['error']}")
358
+ for u in res["unresolved_imports"]:
359
+ print(f" (import 해석 실패 — 적재 안 됨: {u['token']} in {u['from']})")
360
+ if res["claude_md_headroom"] is not None:
361
+ print(f"CLAUDE.md 150,000자 경고선까지 여유: {res['claude_md_headroom']:,}자")
362
+ t = res["total"]
363
+ tail = f" · 미측정 {t['unmeasured_cells']}칸 ({', '.join(t['unmeasured'])})" if t["unmeasured_cells"] else " · 미측정 0칸"
364
+ if res["unresolved_imports"]:
365
+ tail += f" · 대상 없는 import 후보 {len(res['unresolved_imports'])}개(적재 안 됨 — CC 파서와 대조 안 함)"
366
+ print(f"합계 (FH 가 좌우하는 상주분): {t['chars']:,}자 / {t['bytes']:,} bytes{tail}")
367
+ print(f" ({t['note']} · 범위 밖: {', '.join(res['scope_excluded'])})")
368
+
369
+
370
+ if __name__ == "__main__":
371
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bash
2
+ # 이름 누출 — «생성기 + 백스톱». 검사기가 판정하지 않는다.
3
+ #
4
+ # 🟥 초판은 자기 논지를 반증했다. 헤더가 「목록은 안 본다」고 적어놓고
5
+ # `ASSIGN_RE='…(ARM|CTRL|arm|ctrl)…'` 로 **낱말 4개를 열거**했고,
6
+ # `OPAQUE_RE='^[0-9a-z_]+$'` 가 소문자면 통과시켜서 실측으로 뚫렸다:
7
+ # treatment · baseline · placebo · control_a · exposed → 전부 rc=0 «불투명» 🟥
8
+ # ⇒ «4낱말 대신 4낱말»이었다. 열거를 늘리는 수리는 REFUSE_RE 의 네 번째 수리와 같은 형태다.
9
+ # ([[feedback_citing_a_rule_is_not_obeying_it]] — 적는 행위가 «지켰다는 감각»을 만든다.
10
+ # 저자도 검토자도 못 잡았고 세 번째 팔이 잡았다.)
11
+ #
12
+ # 🟥 그래서 방향을 뒤집는다 — **화이트리스트**다:
13
+ # 「나쁜 낱말이 없으면 통과」 ✗ 열거는 언제나 불완전하다
14
+ # 「생성기가 낸 형태가 아니면 차단」 ✓ 사람이 고른 이름은 전부 막힌다
15
+ # 그리고 더 근본적으로: **라벨을 사람이 고르지 않게 한다.** `gen` 이 그 자리다.
16
+ # 검사기는 «생성이 안 쓰였을 때» 무는 백스톱으로만 남는다 —
17
+ # §1 결론(«사람의 읽기에 안 맡긴다»)의 라벨 판이다.
18
+ #
19
+ # 🟥 seal 파일명은 다른 근거로 판정한다 — 실물 규약을 **관측**했다(19건 전수,
20
+ # tracks/_meta/compaction/): `seal_<8hex>-<3hex>_<YYYYMMDD>-<HHMMSS>.md`.
21
+ # 그건 열거가 아니라 **형태 일치**이므로 이 문제가 없다.
22
+ #
23
+ # 🟥 시야 판별자 — 검사 «대상»을 이름 문자열 셋으로 좁힌다. 파일 전체 grep 을 안 한다.
24
+ # ⇒ `context_continuity_score.sh:481·728·729`(같은 basename 이지만 `echo` 로 운영자
25
+ # 콘솔에 간다)는 **애초에 입력이 아니다** = 구조적으로 오조준 불가.
26
+ # 필터는 뚫리고 형태는 안 뚫린다.
27
+ #
28
+ # 사용
29
+ # nameleak_check.sh gen → 회차가 쓸 라벨 하나를 «생성»해서 찍는다
30
+ # nameleak_check.sh <seal> <out-dir> <라벨> → rc 0 통과 · 1 누출 · 2 인자오류
31
+ # 🟥 판정은 rc 로 한다. 출력 문구를 grep 하지 마라 — 요약줄이 같이 잡혀서 개수가 틀린다(실측).
32
+ set -uo pipefail
33
+
34
+ # ── 생성 형태 (이 한 줄이 «불투명»의 정의다) ─────────────────────────────────
35
+ # w + 8자리 이상 hex. 길이가 8이면 사전 단어와 우연히 겹칠 확률이 사실상 0이다.
36
+ # 🟥 잔여를 이름으로 남긴다: `wdeadbeef` 같은 hex-단어는 형태를 통과한다. 막지 않는다 —
37
+ # 막으려면 다시 «낱말 열거»가 되고, 그게 이 파일이 폐기한 방식이다. 확률로 산다.
38
+ GEN_RE='^w[0-9a-f]{8,}$'
39
+ gen_one(){ printf 'w%s\n' "$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')"; }
40
+
41
+ # ── seal 이름 (관측한 실물 규약, 2026-09-01) ─────────────────────────────────
42
+ # 🟥 정규식이 «정본»이고 생성기는 그것에 «검정»된다. 두 곳에 따로 적으면 갈린다 —
43
+ # 오늘 그 축(「갈라 적을 수 있으면 다시 갈린다」)이라 생성 직후 SEAL_RE 로 자기검사한다.
44
+ # 통과 못 하면 이름을 «안 내고» 실패한다: 틀린 이름을 내면 회차가 통째로 무효다.
45
+ SEAL_RE='^seal_[0-9a-f]{8}-[0-9a-f]{3}_[0-9]{8}-[0-9]{6}\.md$'
46
+ gen_seal(){
47
+ local n
48
+ n="seal_$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')-$(od -An -N2 -tx1 /dev/urandom | tr -d ' \n' | cut -c1-3)_$(date +%Y%m%d-%H%M%S).md"
49
+ if printf '%s' "$n" | grep -qE "$SEAL_RE"; then printf '%s\n' "$n"; return 0; fi
50
+ echo "🟥 gen-seal 이 자기 검사기를 통과 못 했다: $n" >&2; return 1
51
+ }
52
+
53
+ if [ "${1:-}" = gen ]; then gen_one; exit $?; fi
54
+ if [ "${1:-}" = gen-seal ]; then gen_seal; exit $?; fi
55
+
56
+ SEAL_NAME="${1:-}"; OUTDIR_NAME="${2:-}"; ARM_LABEL="${3:-}"
57
+ [ -n "$SEAL_NAME" ] && [ -n "$OUTDIR_NAME" ] && [ -n "$ARM_LABEL" ] || {
58
+ echo "usage: nameleak_check.sh gen | <seal-basename> <out-dir-basename> <arm-label>" >&2; exit 2; }
59
+
60
+ # 🟥 SEAL_RE 는 위에서 «한 번만» 정의한다 — 생성기와 검사기가 같은 상수를 쓴다
61
+ bad=0
62
+ say(){ printf ' %s %s\n' "$1" "$2"; }
63
+
64
+ # ① seal 파일명 — 관측한 실물 규약과 «구분 불가»한가
65
+ if printf '%s' "$SEAL_NAME" | grep -qE "$SEAL_RE"; then
66
+ say 🟢 "seal $SEAL_NAME"
67
+ else
68
+ say 🟥 "seal $SEAL_NAME — 실물 규약과 다르다 (seal_<8hex>-<3hex>_<YYYYMMDD>-<HHMMSS>.md)"
69
+ bad=$((bad+1))
70
+ fi
71
+
72
+ # ② out-dir · ③ 팔 라벨 — 둘 다 팔의 cwd 조상/자신이라 시야 «안»이다.
73
+ # 🟥 실물 규약이 없으므로 «생성 형태»만 통과시킨다. 사람이 고른 이름은 전부 막힌다.
74
+ for _pair in "outdir:$OUTDIR_NAME" "arm:$ARM_LABEL"; do
75
+ _k="${_pair%%:*}"; _v="${_pair#*:}"
76
+ if printf '%s' "$_v" | grep -qE "$GEN_RE"; then
77
+ say 🟢 "$_k $_v"
78
+ else
79
+ say 🟥 "$_k $_v — 생성 형태가 아니다 — 'nameleak_check.sh gen' 을 써라"
80
+ bad=$((bad+1))
81
+ fi
82
+ done
83
+
84
+ [ "$bad" -gt 0 ] && { echo "🟥 이름 누출 ${bad}건 — 회차를 열지 않는다"; exit 1; }
85
+ echo "🟢 이름 누출 0건"; exit 0
@@ -58,6 +58,30 @@ SHIPPY
58
58
  # repo above node_modules and call their install a checkout. A worktree's `.git` is a file; -e covers it.
59
59
  _package_mode() { [ ! -e .git ]; }
60
60
 
61
+ # ── Consumer profile (2026-09-29) — what `npm test` runs inside an installed package ──────────────
62
+ # `npm test` = `FH_SELFCHECK_PROFILE=consumer bash scripts/selfcheck.sh`; `npm run test:full` and CI
63
+ # run the full suite. Eight suites below measure things only a git CHECKOUT has (a clone to make,
64
+ # `.git/fh-claims`, docs/map, .github/workflows, .gitignore, `git ls-files`) — inside a tarball they
65
+ # are not failing, they are unmeasurable. A suite that is MOSTLY consumer-relevant stays in and skips
66
+ # only its checkout-bound lanes itself, by name (test_verdict_watermark_lanes.sh · test_probe_live_eval_lanes.sh do this). The consumer profile names each one it skips and prints
67
+ # the list again at the end; it never counts them as PASS.
68
+ # 🟥 The profile is honoured ONLY in package mode. Set in a checkout (CI, the author) it is ignored
69
+ # with a warning — otherwise one env var would silently shrink the required check.
70
+ _CONSUMER=0
71
+ if [ "${FH_SELFCHECK_PROFILE:-full}" = consumer ]; then
72
+ if _package_mode; then _CONSUMER=1
73
+ else echo "⚠️ FH_SELFCHECK_PROFILE=consumer IGNORED — this tree is a git checkout; running the full suite"; fi
74
+ fi
75
+ CHECKOUT_ONLY_SUITES="test_package_coverage_lanes.sh test_files_manifest_shipping_lanes.sh test_map_postprocess_lanes.sh test_remote_marker_gate_lanes.sh test_worktree_reclaim_lanes.sh test_sim_isolated_run_lanes.sh test_utterance_intake_lanes.sh test_precommit_pointer_index_lanes.sh"
76
+ CONSUMER_SKIPPED=""
77
+ _consumer_skip() { # $1 = suite basename · rc 0 = skip it (and it has been named)
78
+ [ "$_CONSUMER" -eq 1 ] || return 1
79
+ case " $CHECKOUT_ONLY_SUITES " in *" $1 "*) ;; *) return 1 ;; esac
80
+ case " $CONSUMER_SKIPPED " in *" $1 "*) ;; *) CONSUMER_SKIPPED="$CONSUMER_SKIPPED $1" ;; esac
81
+ echo "SKIP $1 (consumer profile — needs a git checkout; run \`npm run test:full\` in a clone)"
82
+ return 0
83
+ }
84
+
61
85
  # ── The single verdict for "my subject is not here" ───────────────────────────────────────────
62
86
  # Measured 2026-08-12 (card §🔱⑮ A2): **18 blocks in this file** rendered a green SKIP when their
63
87
  # subject was absent, and **all 18 subjects are declared in package.json files[] and present in the
@@ -494,6 +518,20 @@ else
494
518
  fail=1
495
519
  fi
496
520
 
521
+ # resident-cost meter — read-only instrument for session-start resident cost (chars vs bytes · MEMORY
522
+ # loaded share · YAML-parsed skill listing). Built 2026-10-01 after two same-day mis-measurements
523
+ # (`wc -c` bytes reported as chars · one-line frontmatter parse missing folded `>-` descriptions).
524
+ if [ ! -f scripts/resident_cost.py ]; then
525
+ _absent_subject_verdict "resident-cost lanes" "scripts/resident_cost.py" || fail=1
526
+ elif [ -f scripts/test_resident_cost_lanes.sh ]; then
527
+ if ! bash scripts/test_resident_cost_lanes.sh; then
528
+ fail=1
529
+ fi
530
+ else
531
+ echo "FAIL resident-cost lanes: scripts/resident_cost.py present but its anchor is missing"
532
+ fail=1
533
+ fi
534
+
497
535
  # terminal audit banner — templates/fh_audit_check.zsh (sourced from every user's ~/.zshrc by install-wizard)
498
536
  # fired 2 false lines forever (harvest glob nothing writes · state-marker sentinels aged as audits) and
499
537
  # aborted whole on zsh NOMATCH for a fresh install. Lane = false lines gone · real overdue audits still warn.
@@ -761,7 +799,8 @@ fi
761
799
  if [ ! -f scripts/package_coverage_check.sh ]; then
762
800
  _absent_subject_verdict "test_package_coverage_lanes.sh" "scripts/package_coverage_check.sh" || fail=1
763
801
  elif [ -f scripts/test_package_coverage_lanes.sh ]; then
764
- if ! bash scripts/test_package_coverage_lanes.sh; then
802
+ if _consumer_skip test_package_coverage_lanes.sh; then :
803
+ elif ! bash scripts/test_package_coverage_lanes.sh; then
765
804
  fail=1
766
805
  fi
767
806
  # The CHECKER's semantics are deliberately fail-closed and must not be softened: given a git
@@ -801,7 +840,8 @@ fi
801
840
  if [ ! -f scripts/files_manifest_shipping_check.sh ]; then
802
841
  _absent_subject_verdict "test_files_manifest_shipping_lanes.sh" "scripts/files_manifest_shipping_check.sh" || fail=1
803
842
  elif [ -f scripts/test_files_manifest_shipping_lanes.sh ]; then
804
- if ! bash scripts/test_files_manifest_shipping_lanes.sh; then
843
+ if _consumer_skip test_files_manifest_shipping_lanes.sh; then :
844
+ elif ! bash scripts/test_files_manifest_shipping_lanes.sh; then
805
845
  fail=1
806
846
  fi
807
847
  # Same applicability guard as package-coverage directly above, same reason: a repo with no npm
@@ -1013,6 +1053,8 @@ do
1013
1053
  _subj="${_pair%%|*}"; _anc="${_pair##*|}"; _lbl="${_anc##*/}"
1014
1054
  if [ ! -f "$_subj" ]; then
1015
1055
  _absent_subject_verdict "$_lbl" "$_subj" || fail=1
1056
+ elif [ -f "$_anc" ] && _consumer_skip "$_lbl"; then
1057
+ :
1016
1058
  elif [ -f "$_anc" ]; then
1017
1059
  # `< /dev/null` and the timeout are not decoration: test_frontier_digest_retry.sh deliberately
1018
1060
  # plants a `sleep 300` stub and asserts a 3s watchdog kills it. If that watchdog ever regresses
@@ -1542,7 +1584,8 @@ done
1542
1584
  if [ ! -f scripts/sim_isolated_run.sh ]; then
1543
1585
  _absent_subject_verdict "test_sim_isolated_run_lanes.sh" "scripts/sim_isolated_run.sh" || fail=1
1544
1586
  elif [ -f scripts/test_sim_isolated_run_lanes.sh ]; then
1545
- if ! bash scripts/test_sim_isolated_run_lanes.sh; then
1587
+ if _consumer_skip test_sim_isolated_run_lanes.sh; then :
1588
+ elif ! bash scripts/test_sim_isolated_run_lanes.sh; then
1546
1589
  fail=1
1547
1590
  fi
1548
1591
  else
@@ -1718,6 +1761,16 @@ else
1718
1761
  fail=1
1719
1762
  fi
1720
1763
 
1764
+ # main-commit guard (2026-09-29) — FH assets never land on main/master by a local commit. Same
1765
+ # subject/anchor shape as branch_claim above; both ship, so an absent subject is a deletion, not a skip.
1766
+ if [ ! -f scripts/main_commit_guard.sh ]; then
1767
+ _absent_subject_verdict "test_main_commit_guard_lanes.sh" "scripts/main_commit_guard.sh" || fail=1
1768
+ elif [ -f scripts/test_main_commit_guard_lanes.sh ]; then
1769
+ bash scripts/test_main_commit_guard_lanes.sh || fail=1
1770
+ else
1771
+ echo "FAIL test_main_commit_guard_lanes.sh: main_commit_guard.sh present but its anchor is missing"; fail=1
1772
+ fi
1773
+
1721
1774
  # prless_delta_scan lanes — «커밋은 됐는데 착륙 경로에 안 올라간» 델타를 세는 advisory 계기.
1722
1775
  # 🟥 레인의 하중선은 **음성 컨트롤**이다: 이 레포는 squash 머지를 쓰므로 순진한 per-commit 비교는
1723
1776
  # 이미 착륙한 브랜치를 «미착륙» 으로 읽는다(2026-09-19 실측: naive 33/40 · git cherry 17/40 ·
@@ -2628,8 +2681,12 @@ else
2628
2681
  echo "SKIP rules-dotfile (package mode: .git 없음 — 소스 트리 전용 검사)"
2629
2682
  fi
2630
2683
 
2684
+ if [ "$_CONSUMER" -eq 1 ]; then
2685
+ _n=$(printf '%s\n' $CONSUMER_SKIPPED | grep -c .)
2686
+ echo "CONSUMER PROFILE — $_n checkout-only suite(s) NOT measured here (not a pass):$CONSUMER_SKIPPED"
2687
+ fi
2631
2688
  if [ "$fail" -ne 0 ]; then
2632
2689
  echo "SELFCHECK: FAIL"
2633
2690
  exit 1
2634
2691
  fi
2635
- echo "SELFCHECK: PASS"
2692
+ if [ "$_CONSUMER" -eq 1 ]; then echo "SELFCHECK: PASS (consumer profile)"; else echo "SELFCHECK: PASS"; fi