@chrono-meta/fh-gate 3.26.2 → 3.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/AGENTS.md +2 -1
  3. package/CLAUDE.md +84 -1329
  4. package/README.ja.md +2 -4
  5. package/README.ko.md +2 -4
  6. package/README.md +19 -19
  7. package/README.zh.md +2 -4
  8. package/knowledge/shared/dialogue/memory_intent_recall.md +35 -0
  9. package/knowledge/shared/harness-core/builtin_capability_map.md +70 -0
  10. package/knowledge/shared/harness-core/claude_md_full_reference.md +1277 -0
  11. package/knowledge/shared/harness-core/fh_module_contract.md +97 -0
  12. package/knowledge/shared/harness-core/multi_model_sidecar_strategy.md +64 -0
  13. package/knowledge/shared/learnings/subagent_invocations_log.yaml +145 -0
  14. package/package.json +14 -1
  15. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  16. package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +84 -4
  17. package/plugins/fh-commons/skills/ko-tech-writer/fh-module.yaml +19 -0
  18. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_negative.md +73 -1
  19. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_positive.md +39 -1
  20. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_unclosed.md +6 -0
  21. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  22. package/plugins/fh-meta/CHANGELOG.md +23 -0
  23. package/plugins/fh-meta/skills/context-doctor/SKILL.md +1 -1
  24. package/plugins/fh-meta/skills/frontier-digest/SKILL.md +14 -10
  25. package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +17 -1
  26. package/plugins/fh-meta/skills/install-doctor/SKILL.md +1 -1
  27. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  28. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  29. package/scripts/fh_env_delta_scan.sh +20 -4
  30. package/scripts/fh_module_check.py +686 -0
  31. package/scripts/fixtures/frontier_digest_recall.tsv +5 -0
  32. package/scripts/ko_tech_writer_calibrate.py +288 -15
  33. package/scripts/memory_gc_report.py +270 -0
  34. package/scripts/probe_live_eval.sh +19 -1
  35. package/scripts/probe_live_eval_lib.py +174 -5
  36. package/scripts/resident_cost.py +1 -1
  37. package/scripts/selfcheck.sh +34 -1
  38. package/scripts/session_checklist.py +66 -0
  39. package/scripts/session_close_check.sh +44 -0
  40. package/scripts/sim_isolated_run.sh +31 -0
  41. package/scripts/test_claude_md_size_lanes.sh +22 -7
  42. package/scripts/test_env_delta_worktree_lanes.sh +61 -0
  43. package/scripts/test_fh_module_check_lanes.sh +581 -0
  44. package/scripts/test_frontier_digest_recall.sh +26 -0
  45. package/scripts/test_frontier_digest_recall_negctl.sh +15 -0
  46. package/scripts/test_ko_tech_writer_lanes.sh +1 -1
  47. package/scripts/test_memory_gc_report_lanes.sh +210 -0
  48. package/scripts/test_probe_live_eval_lanes.sh +116 -0
  49. package/scripts/test_regression_guard_sibling_lanes.sh +193 -0
  50. package/scripts/test_resident_cost_lanes.sh +1 -1
  51. package/scripts/test_session_checklist_lanes.sh +29 -0
  52. package/scripts/test_sim_isolated_run_lanes.sh +51 -0
  53. package/scripts/test_utterance_checklist_hook_lanes.sh +175 -0
  54. package/scripts/utterance_checklist_hook.py +193 -0
  55. package/scripts/utterance_checklist_hook.sh +31 -0
  56. package/templates/regression_guard.sh +30 -12
@@ -0,0 +1,5 @@
1
+ # item<TAB>kind<TAB>announced-on channel ids (comma-separated; at least ONE must be in SKILL.md Step 1)
2
+ # Known-positive recall set. Channel assignments are the operator-reported/expected venues, not live-verified.
3
+ Aside agent browser (YC-backed) launch-yc,product-hunt
4
+ Orca agent orchestration show-hn,product-hunt,geeknews
5
+ Context7 docs MCP show-hn,product-hunt,geeknews
@@ -21,7 +21,10 @@ Python `re` 는 ⓐ 세 허용 엔진 중 **어디에나 있는 유일한 것**
21
21
  ⇒ 이걸 통과했다고 «Step 2 잔여 0» 을 주장하면
22
22
  `harness_terminal_correlation_and_recommendations.md` 의 강등 사유가 그대로 재발한다.
23
23
 
24
- exit: 0 전 레인 판별 · 1 판별 실패 · 10 harness error(픽스처 부재)
24
+ 사용: python3 ko_tech_writer_calibrate.py (보정)
25
+ python3 ko_tech_writer_calibrate.py --scan 문서.md (같은 레인·필터로 문서 스캔, 줄\t레인\t본문)
26
+
27
+ exit: 0 전 레인 판별 · 1 판별 실패(픽스처 부재 포함 — known_unclosed.md 가 없으면 1) · 3 --scan 대상에 안 닫힌 블록 · 10 harness error(입력 오류)
25
28
  """
26
29
  import os
27
30
  import re
@@ -30,6 +33,7 @@ import sys
30
33
  HERE = os.path.dirname(os.path.abspath(__file__))
31
34
  FIX = os.path.join(HERE, "..", "plugins", "fh-commons", "skills", "ko-tech-writer", "fixtures")
32
35
  POS = os.path.join(FIX, "known_positive.md")
36
+ UNC = os.path.join(FIX, "known_unclosed.md")
33
37
  NEG = os.path.join(FIX, "known_negative.md")
34
38
 
35
39
  # (라벨, 패턴) — Step 2 의 5클래스 + Step 4-b 의 2패턴.
@@ -56,27 +60,235 @@ LANES = [
56
60
  # 닫힌 명사 어휘라 **recall 이 낮다** — 낮은 쪽이 과차단보다 안전한 방향이고,
57
61
  # 넓히려면 어휘를 늘리는 게 아니라 형태소 분석이 필요하다.
58
62
  ("C4 조각문(후보·닫힌 어휘)", r"(층|것|점|축|건|뿐|바|셈)\.\s*(<!--|$)"),
59
- ("C5 소유 직역", r"(을|를) (갖|가지)"),
63
+ # 갖추다(절차를 갖춘 검토)는 «have» 직역이 아니다 — `갖(?!추|춘|출…)` 로 뺐다 (갖춘·갖출·갖춰 형태 포함 — 첫판 `갖(?!추)` 는 «갖춘» 을 못 뺐다)(tuning doc 1건에서 2건 오탐, 보고치·n=1·독립 아님).
64
+ ("C5 소유 직역", r"(을|를) ?(갖(?!추|춘|출|춤|춰|췄|춥)|가지(?!런|각|치))"), # 가지런히·가지각색·가지치기 는 소유가 아니다(2축 리뷰 B1)
60
65
  ("C6 전칭 어휘", r"전부|모두|하나도|전혀|일절|예외 없이"),
61
66
  ("C6b 부정형 전칭", r"(안|못) ?(했|만들|나오|잡히)|지 않았(다|습니다)"),
67
+ # ── 측정 클래스 (2026-10-17 수확 §4 (내부 기록) 에서 보정한 정규식)
68
+ # 🟥 아래 히트는 전부 «후보»다. 운영자 손편집이 이 패턴들과 반대로 간 사례가 있다(그것을 등).
69
+ ("C7 겹화살괄호·낫표(Y1/Y2)", r"[«»「」『』]", "skipfig"),
70
+ ("C8 절 기호(Y3)", r"§"),
71
+ # 부정 목록: 안 되/된/됩/됨/돼/함 는 정상 용례(tuning doc 1건에서 오탐 4건 전부 이 형태, 보고치·n=1·독립 아님). 그림/코드 블록 안은 편집 대상 밖.
72
+ ("C9 안/못+동사(N3·후보·노이즈 큼)", r"(?<![가-힣])(안|못) (?!(?:되|돼|됩니다|됩니까|된다|된|됨|됐다|됐습니다|되는|되나|되면|돼요|함|함으로|함을|함이|함은|함과)(?![가-힣]))[가-힣]{1,6}", "candidate", "skipfig", "neg=1"),
73
+ ("C10 구어 이유 어미(N4)", r"(니까요|고요|거든요|달라도요)[*.\s]*(<!--.*)?$"),
74
+ ("C11 당신·필요로(N5)", r"당신|필요로\s*(합|하|한)"),
75
+ ("C12 라틴 뒤 조사 띄어쓰기(N9)", r"[A-Za-z0-9)`]\s(는|은|이|가|을|를|로|로는|의|에서|에)(?![가-힣])", "skipfig"),
76
+ # ── 2026-10-17 저녁 운영자 교정 N14·N15. 합성어/복합어로만 좁혔다(일상어 겹침은 레인에서 뺌)
77
+ ("C13 내부 합성어(N14)", r"공격 배터리|이긴 기록|열화 방향 렌즈"),
78
+ ("C14 시험→테스트 복합어(N15)", r"(?<![가-힣])시험\s?(환경|결과|케이스|코드|자동화|하네스|통과)"),
79
+ # ── 경동사 «내다» 후보 (S23 변종). 🟥 UNCALIBRATED: 「판정을 내리다」는 관용구라 «내는» 도 정상 용례가 많다 → 과차단이 예상 결과.
80
+ # 판별력을 주장하지 않는다. 잡는 형태 둘: 따옴표 명사+를 냈다 / 판정을 내는.
81
+ ("C15 경동사 내다(후보·UNCALIBRATED)", r"['’”」»』\"`]\s?(을|를) (냈|낸|내는|낼|냅)|판정을 (냈|낸|내는|낼|냅)", "candidate", "uncalibrated", "neg=1"),
82
+ # ── S7 내부 조어 후보 추출기 (함수 lane — 줄 패턴이 아니라 문서 전체를 본다)
83
+ ("C16 내부 조어 후보(S7·후보)", None, "s7"),
62
84
  ]
63
85
 
86
+ # ── 줄 필터: 그림/차트 블록·코드 펜스 안의 줄은 편집 대상이 아니다 (lane 4번째 인자 "skipfig")
87
+ # 상태기계다: 펜스는 ``` 와 ~~~ 를 따로 닫고, [그림: …] 은 대괄호 깊이로 닫는다(`[그림: x[0] y]` 가 일찍 안 닫힌다).
88
+ # 🟥 안 닫힌 블록은 EOF 까지 문서를 삼킨다 → 통계에 open_fence/open_fig 로 남기고 scan 모드가 경고 + 비0 종료.
89
+ FIG_OPEN = re.compile(r"\[(?:그림|차트):")
90
+
91
+
92
+ class Blocks(object):
93
+ def __init__(self):
94
+ self.fence = None # "`" | "~" | None
95
+ self.fence_line = 0
96
+ self.depth = 0 # [그림: 대괄호 깊이
97
+ self.fig_line = 0
98
+ self.total = self.skipped = 0
99
+
100
+
101
+ def _strip(line, st, n):
102
+ """st 상태로 line 을 도려낸 나머지를 돌려준다."""
103
+ ls = line.lstrip()
104
+ if st.fence:
105
+ if ls.startswith(st.fence * 3):
106
+ st.fence = None
107
+ return ""
108
+ if st.depth == 0 and (ls.startswith("```") or ls.startswith("~~~")):
109
+ st.fence, st.fence_line = ls[0], n
110
+ return ""
111
+ out, pos = [], 0
112
+ while True:
113
+ if st.depth > 0:
114
+ while pos < len(line) and st.depth > 0:
115
+ if line[pos] == "[":
116
+ st.depth += 1
117
+ elif line[pos] == "]":
118
+ st.depth -= 1
119
+ pos += 1
120
+ if st.depth > 0:
121
+ return "".join(out)
122
+ m = FIG_OPEN.search(line, pos)
123
+ if not m:
124
+ out.append(line[pos:])
125
+ return "".join(out)
126
+ out.append(line[pos:m.start()])
127
+ st.depth, st.fig_line, pos = 1, n, m.end()
128
+
129
+
130
+ def iter_lines(lines, skipfig, st):
131
+ for i, raw in enumerate(lines, 1):
132
+ line = raw.rstrip("\n")
133
+ st.total += 1
134
+ if skipfig:
135
+ kept = _strip(line, st, i)
136
+ if kept != line:
137
+ st.skipped += 1
138
+ line = kept
139
+ yield i, line
140
+
141
+
142
+ def read_lines(path):
143
+ with open(path, encoding="utf-8") as fh:
144
+ return fh.read().split("\n")
145
+
146
+
147
+ def scan_lines(path, skipfig=False, st=None):
148
+ """(줄번호, 줄) 를 낸다. skipfig 면 펜스 · [그림:/차트: …] 블록(여러 줄 포함)을 줄에서 도려낸다. 통계는 st 에."""
149
+ return iter_lines(read_lines(path), skipfig, st or Blocks())
150
+
151
+
152
+ def unclosed(st):
153
+ out = []
154
+ if st.fence:
155
+ out.append("code fence (%s) opened at line %d" % (st.fence * 3, st.fence_line))
156
+ if st.depth > 0:
157
+ out.append("[그림:/차트: block opened at line %d" % st.fig_line)
158
+ return out
159
+
160
+
161
+ # ── S7 후보 추출기. 낱말 판정이 아니라 «첫 등장에 풀이가 있나» 만 본다. 히트는 전부 후보.
162
+ # 널리 알려진 약어는 독자층에 따라 다르다 — 기본 목록은 기술 독자 기준이고 문서마다 고쳐라(독자층 눈금이 먼저).
163
+ # `--scan FILE --s7-common LIST` 로 통째 교체한다(줄당 하나, # 주석). 기본 목록은 고정이고 픽스처가 항목 하나(MCP)를 못 박는다.
164
+ S7_COMMON = {"AI", "API", "URL", "HTTP", "HTTPS", "JSON", "YAML", "CLI", "CI", "CD", "PR", "UI", "UX",
165
+ "LLM", "SQL", "HTML", "CSS", "OS", "ID", "QA", "PDF", "CPU", "GPU", "UTF", "SDK", "MCP"}
166
+ ACRO = re.compile(r"(?<![A-Za-z0-9])[A-Z]{2,}[A-Z0-9]*(?![A-Za-z])")
167
+ HEADING = re.compile(r"^\s{0,3}#{1,6}\s")
168
+ COMMENT = re.compile(r"<!--.*?-->", re.S)
169
+
170
+
171
+ def has_gloss(term, line, heading):
172
+ """첫 등장 줄에 풀이가 있나. 괄호 풀이 TERM(한글…) / 한글(TERM) / TERM = / TERM은·는 … 입니다.
173
+ 제목 줄은 «제목 안에» 풀이가 있어야 한다 — 뒤 본문의 정의는 «정의 전에 제목에 썼다» 를 지우지 않는다."""
174
+ t = re.escape(term)
175
+ if re.search(t + r"\s?\([^)]*[가-힣][^)]*\)", line):
176
+ return True
177
+ if re.search(t + r"\s?\(\s?[A-Za-z][A-Za-z-]+(\s+[A-Za-z-]+)+\s?\)", line): # CORS(Cross-Origin Resource Sharing) — 영문 풀이도 풀이다(2축 리뷰 B3)
178
+ return True
179
+ if re.search(r"[가-힣][가-힣 ]{1,30}\(\s?" + t + r"\s?\)", line):
180
+ return True
181
+ if re.search(t + r"\s?=\s?(?![0-9])", line): # TTL=60 은 값이지 풀이가 아니다
182
+ return True
183
+ # 정의형: «TERM이란/란 …», 뜻·약자·줄임말을 말하는 «TERM은/는 …», 또는 설명이 6자 이상인 «TERM은/는 … 입니다»
184
+ # («RBAC은 필수입니다» 처럼 술어가 짧으면 정의가 아니다 — 2축 리뷰 B3. 의미 판정이라 후보 레인의 절충이다)
185
+ if not heading and (re.search(t + r"(이란|란)\s", line)
186
+ or re.search(t + r"(은|는)[^.]{0,60}(약자|줄임말|뜻합니다|뜻한다|의미합니다|의미한다|말합니다|가리킵니다|가리킨다)", line)
187
+ or re.search(t + r"(은|는)\s[^.]{6,60}(입니다|이다)", line)):
188
+ return True
189
+ return False
190
+
191
+
192
+ def load_common(path):
193
+ with open(path, encoding="utf-8") as fh:
194
+ return {l.split("#")[0].strip() for l in fh if l.split("#")[0].strip()}
195
+
196
+
197
+ def s7_candidates(path, common=None, st=None):
198
+ """[(용어, 줄번호, 종류)] — 종류: heading-before-gloss(제목 첫 등장·제목 안 풀이 없음) · unglossed-first-use.
199
+ 다른 레인과 같은 블록 필터(펜스·그림)를 쓴다."""
200
+ common = S7_COMMON if common is None else common
201
+ text = open(path, encoding="utf-8").read()
202
+ text = COMMENT.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text) # 줄번호 보존
203
+ seen, out = set(), []
204
+ for i, line in iter_lines(text.split("\n"), True, st or Blocks()):
205
+ heading = bool(HEADING.match(line))
206
+ # 코드 스팬 · URL 안의 대문자는 독자 어휘가 아니다(2축 리뷰 B2) — 같은 길이의 공백으로 지워 위치를 보존한다
207
+ scan = re.sub(r"`[^`]*`|https?://\S+", lambda mm: " " * len(mm.group(0)), line)
208
+ for m in ACRO.finditer(scan):
209
+ term = m.group(0)
210
+ if term in seen or term in common or term.rstrip("0123456789") in common: # HTTP2 → HTTP
211
+ continue
212
+ seen.add(term)
213
+ if not has_gloss(term, line, heading):
214
+ out.append((term, i, "heading-before-gloss" if heading else "unglossed-first-use"))
215
+ return out
216
+
217
+
64
218
  # 절대 잡히면 안 되는 토큰 — 「늘 잡는다」를 내는 죽은 계기 배제용
65
219
  NEVER = r"ZZZ_absent_token_ZZZ"
66
220
 
67
221
 
68
- def count(path, pattern):
222
+ def count(path, pattern, skipfig=False):
69
223
  """패턴에 매칭되는 **줄 수**. 파일 부재는 예외로 올린다(무음 0 금지)."""
70
224
  rx = re.compile(pattern, re.MULTILINE)
71
- n = 0
72
- with open(path, encoding="utf-8") as fh:
73
- for line in fh:
74
- if rx.search(line.rstrip("\n")):
75
- n += 1
76
- return n
225
+ return sum(1 for _, line in scan_lines(path, skipfig) if rx.search(line))
226
+
227
+
228
+ def scan(path, common=None):
229
+ """문서 스캔 모드: 전 레인(+S7)을 같은 필터로 돌려 (rows, stats) 를 낸다 — 레인 정의의 단일 소스.
230
+ stats = 레인별 Blocks 중 skipfig 레인의 것(모든 skipfig 레인이 같은 상태기계라 하나면 충분)."""
231
+ rows, st = [], Blocks()
232
+ for lane in LANES:
233
+ label, pat, flags = lane[0], lane[1], lane[2:]
234
+ if "s7" in flags:
235
+ for term, i, kind in s7_candidates(path, common):
236
+ rows.append((label, i, "%s [%s]" % (term, kind)))
237
+ continue
238
+ rx = re.compile(pat)
239
+ sk = "skipfig" in flags
240
+ lst = Blocks()
241
+ for i, line in scan_lines(path, sk, lst):
242
+ if rx.search(line):
243
+ rows.append((label, i, line.strip()))
244
+ if sk:
245
+ st = lst
246
+ return rows, st
247
+
248
+
249
+ def scan_main(args):
250
+ """--scan FILE [--s7-common LIST]. 입력 오류는 stderr + 10, 안 닫힌 블록은 경고 + 3."""
251
+ path = common_path = None
252
+ it = iter(args)
253
+ for a in it:
254
+ if a == "--s7-common":
255
+ common_path = next(it, None)
256
+ if not common_path:
257
+ sys.stderr.write("usage error: --s7-common needs a file\n")
258
+ return 10
259
+ elif path is None and not a.startswith("--"):
260
+ path = a
261
+ else:
262
+ sys.stderr.write("usage: ko_tech_writer_calibrate.py --scan FILE [--s7-common LIST]\n")
263
+ return 10
264
+ if path is None:
265
+ sys.stderr.write("usage: ko_tech_writer_calibrate.py --scan FILE [--s7-common LIST]\n")
266
+ return 10
267
+ try:
268
+ common = load_common(common_path) if common_path else None
269
+ rows, st = scan(path, common)
270
+ except (OSError, UnicodeDecodeError) as e:
271
+ sys.stderr.write("harness error: cannot scan %s: %s\n" % (path, e))
272
+ return 10
273
+ print("scanned: %s %d lines" % (path, st.total))
274
+ print("s7-common: %s (%d entries)" % (common_path or "default", len(common if common is not None else S7_COMMON)))
275
+ print("skipped: %d lines (fence/fig); filter applies to C7, C9, C12, C16 only" % st.skipped)
276
+ for label, i, text in rows:
277
+ print("%d\t%s\t%s" % (i, label, text[:200]))
278
+ bad = unclosed(st)
279
+ if bad:
280
+ for b in bad:
281
+ sys.stderr.write("WARNING unclosed block at EOF: %s -- everything after it was skipped; C7/C9/C12/C16 results are NOT valid\n" % b)
282
+ return 3
283
+ return 0
77
284
 
78
285
 
79
286
  def main():
287
+ if len(sys.argv) > 1:
288
+ if sys.argv[1] == "--scan":
289
+ return scan_main(sys.argv[2:])
290
+ sys.stderr.write("usage: ko_tech_writer_calibrate.py [--scan FILE [--s7-common LIST]]\n")
291
+ return 10
80
292
  for p in (POS, NEG):
81
293
  if not os.path.isfile(p):
82
294
  sys.stderr.write("harness error: fixture missing %s\n" % p)
@@ -89,10 +301,51 @@ def main():
89
301
  print("")
90
302
 
91
303
  npass = nfail = 0
92
- for label, pat in LANES:
93
- p = count(POS, pat)
94
- n = count(NEG, pat)
95
- if p >= 1 and n == 0:
304
+ ncand = []
305
+ for lane in LANES:
306
+ label, pat, flags = lane[0], lane[1], lane[2:]
307
+ candidate = "candidate" in flags
308
+ if candidate or "s7" in flags:
309
+ ncand.append(label.split()[0] + (" UNCALIBRATED" if "uncalibrated" in flags else ""))
310
+ if "s7" in flags:
311
+ p, n = len(s7_candidates(POS)), len(s7_candidates(NEG))
312
+ if p >= 1 and n == 0:
313
+ print("OK %s -- CANDIDATE-ONLY: positive %d / negative 0 (discriminates the constructed pair; "
314
+ "precision on real documents UNMEASURED, hits need per-case judgment)" % (label, p))
315
+ npass += 1
316
+ else:
317
+ print("FAIL %s -- positive %d / negative %d (needs positive >= 1 and negative 0)" % (label, p, n))
318
+ nfail += 1
319
+ continue
320
+ sk = "skipfig" in flags
321
+ p = count(POS, pat, sk)
322
+ n = count(NEG, pat, sk)
323
+ want = [int(f[4:]) for f in flags if f.startswith("neg=")]
324
+ if want and n != want[0]:
325
+ # 후보 레인도 음성 수는 고정한다: 문서화된 과차단 줄 «만» 걸려야 한다. 새 오탐(또는 부정 목록 소실)이 «예상된 과차단» 에 묻히지 않게.
326
+ print("FAIL %s -- negative count %d != documented over-block %d (a new false alarm, or the exclusion was lost)"
327
+ % (label, n, want[0]))
328
+ nfail += 1
329
+ elif "uncalibrated" in flags:
330
+ if p >= 1 and n >= 1:
331
+ print("OK %s -- UNCALIBRATED CANDIDATE: positive %d / negative %d (idiom over-block shown; "
332
+ "no discrimination claimed)" % (label, p, n))
333
+ npass += 1
334
+ else:
335
+ print("FAIL %s -- uncalibrated candidate lane lost its positive or its documented over-block "
336
+ "(positive %d / negative %d)" % (label, p, n))
337
+ nfail += 1
338
+ elif candidate:
339
+ # 후보 전용 레인: 정상 용례를 잡는 과차단이 **예상된 결과**다. 판별(discriminates)을 주장하지 않는다.
340
+ if p >= 1 and n >= 1:
341
+ print("OK %s -- CANDIDATE-ONLY: positive %d / negative %d (expected over-block; "
342
+ "does NOT discriminate, hits need per-case judgment)" % (label, p, n))
343
+ npass += 1
344
+ else:
345
+ print("FAIL %s -- candidate lane lost its documented over-block or positive "
346
+ "(positive %d / negative %d)" % (label, p, n))
347
+ nfail += 1
348
+ elif p >= 1 and n == 0:
96
349
  print("OK %s -- positive %d / negative 0 (discriminates)" % (label, p))
97
350
  npass += 1
98
351
  elif p < 1:
@@ -103,6 +356,23 @@ def main():
103
356
  % (label, n))
104
357
  nfail += 1
105
358
 
359
+ # 블록 필터 레인 — 안 닫힌 [그림: 이 «보고» 되는가(양성 픽스처) · 정상 픽스처(~~~ 펜스·중첩 대괄호 포함)는 닫힌 채 끝나는가
360
+ if not os.path.isfile(UNC):
361
+ print("FAIL BLOCK unclosed fixture missing -- %s" % UNC)
362
+ nfail += 1
363
+ else:
364
+ su, sn = Blocks(), Blocks()
365
+ list(scan_lines(UNC, True, su))
366
+ list(scan_lines(NEG, True, sn))
367
+ if unclosed(su) and not unclosed(sn) and sn.skipped >= 1:
368
+ print("OK BLOCK unclosed-block report -- positive: %s / negative: closed, %d lines skipped (discriminates)"
369
+ % ("; ".join(unclosed(su)), sn.skipped))
370
+ npass += 1
371
+ else:
372
+ print("FAIL BLOCK unclosed-block report -- positive %r / negative %r (skipped %d)"
373
+ % (unclosed(su), unclosed(sn), sn.skipped))
374
+ nfail += 1
375
+
106
376
  # META 컨트롤 1 — 없는 토큰이 양쪽 다 0인가 (계기가 «늘 잡는다» 를 내지 않는다)
107
377
  if count(POS, NEVER) == 0 and count(NEG, NEVER) == 0:
108
378
  print("OK META control -- an absent token matches nothing in either fixture")
@@ -122,9 +392,12 @@ def main():
122
392
 
123
393
  print("")
124
394
  if nfail == 0:
125
- print("CALIBRATED (%d lanes) -- Step 2 five classes + Step 4-b two patterns discriminate."
126
- % npass)
395
+ ndisc = npass - len(ncand)
396
+ print("CALIBRATED (%d discriminating incl. 2 meta controls; %d candidate-only: %s) -- Step 2 classes + Step 4-b discriminate; candidate lanes do not."
397
+ % (ndisc, len(ncand), ", ".join(ncand)))
127
398
  print(" NOT proven: 'zero residue' in any real document. That is measured per document.")
399
+ print(" C7-C12 positives are the harvest's own 'before' sentences (re-built short); C13-C14 positives are constructed (no harvest pair), so")
400
+ print(" false-positive rate on out-of-distribution text is UNMEASURED. C9 over-blocks by design.")
128
401
  print(" Citing this suite as evidence of 'zero residue' reproduces the very downgrade")
129
402
  print(" recorded in harness_terminal_correlation_and_recommendations.md.")
130
403
  return 0
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env python3
2
+ """memory_gc_report.py — read-only lifecycle report for a Claude Code memory directory.
3
+
4
+ WHY: MEMORY.md is a capped overview (the loader stops at ~25,000 chars and silently drops the
5
+ rest), but nothing decides WHICH entries stay above the cap. Ordering by recency pushes
6
+ long-confirmed feedback below the cut, and recurrence lived only in prose ("하루 3회"), so no
7
+ machine could rank by it. Generational-GC framing (imweb tech, 2026-10-06): an entry's AGE rises
8
+ only when the same observation is recorded again; recurrence across several days marks a
9
+ promotion candidate.
10
+
11
+ WHAT: reads every topic file's frontmatter and the index, and reports
12
+ · index hygiene — unlisted files · duplicate index lines · dangling local links
13
+ · loader cap — the character offset where the cap cuts, and the line it falls in
14
+ · every entry — status, type, age (from `metadata.hits`), distinct days, last hit, index line
15
+ · cold — non-user, age 1, last hit ≥ --cold-days ago → drop from the INDEX only
16
+ · promote — age ≥ --promote-age across ≥ 2 distinct days → propose a rule/hook (human approves)
17
+ · order — user entries in index order, then valid measured entries by age (ties: index
18
+ order), then the rest in index order; cold entries leave the order. Entries with an
19
+ error status never drive cold / promote / measured ranking until repaired
20
+
21
+ INVARIANTS:
22
+ · Read-only. It never edits, moves or deletes anything.
23
+ · No `hits` = UNMEASURED, never age 1, never cold. A rule that is followed well also stops
24
+ recurring; absence of a record is not a zero.
25
+ · Unreadable files, missing/unterminated frontmatter, inline or malformed `hits`, invalid or
26
+ future dates are reported as such (status / bad lines) — never folded into "no hits".
27
+ · Same-day repeats count once toward the distinct-days condition.
28
+
29
+ `hits` format (a child of the frontmatter `metadata:` block; one occurrence per item, first = founding):
30
+ metadata:
31
+ hits:
32
+ - 2026-10-15 | live lane windows covered the operator's screen
33
+ usage: memory_gc_report.py <memory_dir> [--index MEMORY.md] [--today YYYY-MM-DD]
34
+ [--cold-days 30] [--promote-age 3] [--cap 25000] [--json]
35
+ exit: 0 report printed · 2 memory dir or index unreadable (instrument error, never an empty report)
36
+ """
37
+ import argparse, datetime as dt, json, os, re, sys, urllib.parse
38
+
39
+ def link_dests(line):
40
+ """Markdown inline-link destinations with their start offset: <...> form, balanced parens, title dropped."""
41
+ out, i = [], 0
42
+ while True:
43
+ j = line.find('](', i)
44
+ if j < 0:
45
+ return out
46
+ k = j + 2
47
+ while k < len(line) and line[k] == ' ':
48
+ k += 1
49
+ start = k
50
+ if k < len(line) and line[k] == '<':
51
+ e = line.find('>', k + 1)
52
+ if e < 0:
53
+ i = j + 2; continue
54
+ out.append((line[k + 1:e], start)); i = e + 1; continue
55
+ depth, d = 0, k
56
+ while d < len(line):
57
+ c = line[d]
58
+ if c == '(':
59
+ depth += 1
60
+ elif c == ')':
61
+ if depth == 0:
62
+ break
63
+ depth -= 1
64
+ elif c in ' \t' and depth == 0:
65
+ break
66
+ d += 1
67
+ if d > k:
68
+ out.append((line[k:d], start))
69
+ i = d
70
+ HIT_RE = re.compile(r'^-\s*(\S+)\s*\|\s*(.+?)\s*$')
71
+
72
+
73
+ def indent(line):
74
+ return len(line) - len(line.lstrip(' '))
75
+
76
+
77
+ def parse_entry(path, today):
78
+ """-> dict(status, type, hits[(date,str)], bad[str])"""
79
+ out = {'status': 'OK', 'type': None, 'hits': [], 'bad': []}
80
+ try:
81
+ text = open(path, encoding='utf-8').read()
82
+ except (OSError, UnicodeDecodeError) as e:
83
+ out['status'] = 'READ_ERROR'
84
+ out['bad'].append(type(e).__name__)
85
+ return out
86
+ lines = text.splitlines()
87
+ if not lines or lines[0].strip() != '---':
88
+ out['status'] = 'NO_FRONTMATTER'
89
+ return out
90
+ try:
91
+ end = next(i for i in range(1, len(lines)) if lines[i].strip() == '---')
92
+ except StopIteration:
93
+ out['status'] = 'UNTERMINATED_FRONTMATTER'
94
+ return out
95
+ fm = lines[1:end]
96
+ meta_i = next((i for i, l in enumerate(fm) if indent(l) == 0 and re.match(r'^metadata:\s*$', l)), None)
97
+ if meta_i is None:
98
+ return out
99
+ meta = []
100
+ for l in fm[meta_i + 1:]:
101
+ if l.strip() and not l.lstrip().startswith('#') and indent(l) == 0:
102
+ break
103
+ meta.append(l)
104
+ child = min((indent(l) for l in meta if l.strip() and not l.lstrip().startswith('#')), default=None)
105
+ hits_i = None
106
+ for i, l in enumerate(meta):
107
+ if not l.strip() or l.lstrip().startswith('#'):
108
+ continue
109
+ if indent(l) == child:
110
+ m = re.match(r'^\s*type:\s*(.*)$', l)
111
+ if m and out['type'] is None:
112
+ out['type'] = m.group(1).strip().strip('"\'') or None
113
+ if re.match(r'^\s*hits:', l):
114
+ if re.match(r'^\s*hits:\s*$', l):
115
+ hits_i = i
116
+ else:
117
+ out['status'] = 'HITS_MALFORMED'
118
+ out['bad'].append(l.strip())
119
+ if hits_i is None:
120
+ return out
121
+ hind = indent(meta[hits_i])
122
+ for l in meta[hits_i + 1:]:
123
+ if not l.strip() or l.lstrip().startswith('#'):
124
+ continue
125
+ if indent(l) == hind and l.lstrip().startswith('- '):
126
+ out['bad'].append(l.strip() + ' (indentless list item — indent it under hits:)')
127
+ continue
128
+ if indent(l) <= hind:
129
+ break
130
+ s = l.strip()
131
+ m = HIT_RE.match(s)
132
+ if not m:
133
+ out['bad'].append(s)
134
+ continue
135
+ try:
136
+ d = dt.date.fromisoformat(m.group(1))
137
+ except ValueError:
138
+ out['bad'].append(s)
139
+ continue
140
+ if d > today:
141
+ out['bad'].append(s + ' (future date)')
142
+ continue
143
+ out['hits'].append((d.isoformat(), m.group(2)))
144
+ if out['bad'] and out['status'] == 'OK':
145
+ out['status'] = 'HITS_MALFORMED'
146
+ return out
147
+
148
+
149
+ def local_target(dest, index_dir):
150
+ if re.match(r'^[a-zA-Z][a-zA-Z0-9+.-]*:', dest): # https:, mailto:, file: …
151
+ return None
152
+ dest = urllib.parse.unquote(dest.split('#', 1)[0].split('?', 1)[0])
153
+ if not dest.endswith('.md'):
154
+ return None
155
+ return os.path.normpath(dest)
156
+
157
+
158
+ def main():
159
+ ap = argparse.ArgumentParser()
160
+ ap.add_argument('memory_dir')
161
+ ap.add_argument('--index', default='MEMORY.md')
162
+ ap.add_argument('--today')
163
+ ap.add_argument('--cold-days', type=int, default=30)
164
+ ap.add_argument('--promote-age', type=int, default=3)
165
+ ap.add_argument('--cap', type=int, default=25000)
166
+ ap.add_argument('--json', action='store_true')
167
+ a = ap.parse_args()
168
+
169
+ idx_path = os.path.join(a.memory_dir, a.index)
170
+ try:
171
+ names = sorted(f for f in os.listdir(a.memory_dir) if f.endswith('.md') and f != a.index)
172
+ idx_text = open(idx_path, encoding='utf-8').read()
173
+ except (OSError, UnicodeDecodeError) as e:
174
+ print(f'HARNESS-ERROR: {e}', file=sys.stderr)
175
+ return 2
176
+ today = dt.date.fromisoformat(a.today) if a.today else dt.date.today()
177
+
178
+ # loader cap: character offset, and the line it falls in (prefix of that line is still loaded)
179
+ cut = None
180
+ if len(idx_text) > a.cap:
181
+ line_no = idx_text.count('\n', 0, a.cap) + 1
182
+ line_start = idx_text.rfind('\n', 0, a.cap) + 1
183
+ cut = {'char': a.cap, 'line': line_no, 'chars_loaded_in_line': a.cap - line_start}
184
+ pos, dups, dangling, offset = {}, [], [], 0
185
+ for i, line in enumerate(idx_text.splitlines(keepends=True), 1):
186
+ for dest, at in link_dests(line):
187
+ t = local_target(dest, a.memory_dir)
188
+ if t is None:
189
+ continue
190
+ if not os.path.isfile(os.path.join(a.memory_dir, t)):
191
+ dangling.append([t, i])
192
+ continue
193
+ if t in pos:
194
+ dups.append([t, pos[t]['line'], i])
195
+ else:
196
+ pos[t] = {'line': i, 'ord': len(pos), 'past_cap': cut is not None and offset + at >= a.cap}
197
+ offset += len(line)
198
+
199
+ entries = []
200
+ for n in names:
201
+ p = parse_entry(os.path.join(a.memory_dir, n), today)
202
+ e = {'file': n, 'status': p['status'], 'type': p['type'], 'bad': p['bad'],
203
+ 'index_line': pos.get(n, {}).get('line'), 'index_ord': pos.get(n, {}).get('ord'),
204
+ 'past_cap': pos.get(n, {}).get('past_cap', False)}
205
+ if p['hits']:
206
+ days = sorted({d for d, _ in p['hits']})
207
+ e.update(age=len(p['hits']), distinct_days=len(days), last_hit=days[-1])
208
+ else:
209
+ e.update(age=None, distinct_days=None, last_hit=None) # UNMEASURED, not age 1
210
+ entries.append(e)
211
+
212
+ def days_since(d):
213
+ return (today - dt.date.fromisoformat(d)).days
214
+
215
+ ok = lambda e: e['status'] == 'OK'
216
+ cold = [e for e in entries if ok(e) and e['type'] != 'user' and e['age'] == 1
217
+ and days_since(e['last_hit']) >= a.cold_days]
218
+ promote = [e for e in entries if ok(e) and e['age'] is not None and e['age'] >= a.promote_age
219
+ and e['distinct_days'] >= 2]
220
+ cold_set = {e['file'] for e in cold}
221
+ listed = sorted((e for e in entries if e['index_line'] is not None), key=lambda e: e['index_ord'])
222
+ users = [e for e in listed if e['type'] == 'user']
223
+ meas = sorted((e for e in listed if e['type'] != 'user' and ok(e) and e['age'] is not None and e['file'] not in cold_set),
224
+ key=lambda e: (-e['age'], e['index_ord'])) # age ties keep index (link) order
225
+ rest = [e for e in listed if e['type'] != 'user' and not (ok(e) and e['age'] is not None)]
226
+ order = [e['file'] for e in users + meas + rest]
227
+
228
+ rep = {'memory_dir': a.memory_dir, 'today': today.isoformat(), 'files': len(entries),
229
+ 'index_chars': len(idx_text), 'cap': a.cap, 'cut': cut,
230
+ 'unlisted': [e['file'] for e in entries if e['index_line'] is None],
231
+ 'duplicates': dups, 'dangling': dangling,
232
+ 'measured': sum(e['age'] is not None for e in entries),
233
+ 'unmeasured': sum(e['age'] is None for e in entries),
234
+ 'errors': [[e['file'], e['status'], e['bad']] for e in entries if e['status'] != 'OK'],
235
+ 'cold': [e['file'] for e in cold],
236
+ 'promote': [[e['file'], e['age'], e['distinct_days']] for e in promote],
237
+ 'order': order, 'entries': entries}
238
+ if a.json:
239
+ print(json.dumps(rep, ensure_ascii=False, indent=1))
240
+ return 0
241
+ cut_s = 'within cap' if cut is None else f"cap cuts at char {cut['char']} = line {cut['line']} (first {cut['chars_loaded_in_line']} chars of it load)"
242
+ print(f"memory GC report — {rep['files']} topic files · index {len(idx_text)} chars, {cut_s} · today {rep['today']}")
243
+ print(f" index: unlisted {len(rep['unlisted'])} · duplicate lines {len(dups)} · dangling local links {len(dangling)}")
244
+ for t, first, again in dups:
245
+ print(f" dup {t} (lines {first} and {again})")
246
+ for t, ln in dangling:
247
+ print(f" dangling {t} (line {ln})")
248
+ print(f" errors (not folded into 'no hits'): {len(rep['errors'])}")
249
+ for f, st, bad in rep['errors']:
250
+ print(f" {st:<24} {f} {'; '.join(bad)[:120]}")
251
+ print(f" age: measured {rep['measured']} · UNMEASURED {rep['unmeasured']} (no `hits` — never age 1, never cold)")
252
+ for e in sorted(entries, key=lambda e: (e['age'] is None, -(e['age'] or 0), e['file'])):
253
+ age = 'UNMEAS' if e['age'] is None else f"age {e['age']:>2}"
254
+ print(f" {age} · {e['type'] or '-'} · {e['status']} · days {e['distinct_days']} · last {e['last_hit']} · "
255
+ f"{'line ' + str(e['index_line']) if e['index_line'] else 'unlisted'}{' (past cap)' if e['past_cap'] else ''} · {e['file']}")
256
+ print(f" cold (non-user, age 1, no recurrence for ≥ {a.cold_days}d → drop from index only, keep file): {len(cold)}")
257
+ for e in cold:
258
+ print(f" cold {e['file']} last {e['last_hit']}")
259
+ print(f" promote candidates (age ≥ {a.promote_age} over ≥ 2 days → propose rule/hook, human approves): {len(promote)}")
260
+ for e in promote:
261
+ print(f" promote {e['file']} age {e['age']} · days {e['distinct_days']} · last {e['last_hit']}")
262
+ print(f" proposed order ({len(order)}):")
263
+ for n, f in enumerate(order, 1):
264
+ print(f" {n:>3}. {f}")
265
+ print(' read-only: nothing was changed.')
266
+ return 0
267
+
268
+
269
+ if __name__ == '__main__':
270
+ sys.exit(main())