@chrono-meta/fh-gate 3.27.0 → 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 (43) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/CLAUDE.md +2 -2
  3. package/README.ja.md +2 -4
  4. package/README.ko.md +2 -4
  5. package/README.md +19 -19
  6. package/README.zh.md +2 -4
  7. package/knowledge/shared/harness-core/fh_module_contract.md +97 -0
  8. package/knowledge/shared/learnings/subagent_invocations_log.yaml +81 -0
  9. package/package.json +10 -1
  10. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  11. package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +84 -4
  12. package/plugins/fh-commons/skills/ko-tech-writer/fh-module.yaml +19 -0
  13. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_negative.md +73 -1
  14. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_positive.md +39 -1
  15. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_unclosed.md +6 -0
  16. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/CHANGELOG.md +10 -0
  18. package/plugins/fh-meta/skills/frontier-digest/SKILL.md +14 -10
  19. package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +17 -1
  20. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  21. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  22. package/scripts/fh_module_check.py +686 -0
  23. package/scripts/fixtures/frontier_digest_recall.tsv +5 -0
  24. package/scripts/ko_tech_writer_calibrate.py +288 -15
  25. package/scripts/probe_live_eval.sh +19 -1
  26. package/scripts/probe_live_eval_lib.py +174 -5
  27. package/scripts/resident_cost.py +1 -1
  28. package/scripts/selfcheck.sh +7 -1
  29. package/scripts/session_checklist.py +66 -0
  30. package/scripts/session_close_check.sh +44 -0
  31. package/scripts/sim_isolated_run.sh +31 -0
  32. package/scripts/test_claude_md_size_lanes.sh +22 -7
  33. package/scripts/test_fh_module_check_lanes.sh +581 -0
  34. package/scripts/test_frontier_digest_recall.sh +26 -0
  35. package/scripts/test_frontier_digest_recall_negctl.sh +15 -0
  36. package/scripts/test_ko_tech_writer_lanes.sh +1 -1
  37. package/scripts/test_probe_live_eval_lanes.sh +116 -0
  38. package/scripts/test_resident_cost_lanes.sh +1 -1
  39. package/scripts/test_session_checklist_lanes.sh +29 -0
  40. package/scripts/test_sim_isolated_run_lanes.sh +51 -0
  41. package/scripts/test_utterance_checklist_hook_lanes.sh +175 -0
  42. package/scripts/utterance_checklist_hook.py +193 -0
  43. package/scripts/utterance_checklist_hook.sh +31 -0
@@ -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
@@ -69,6 +69,8 @@
69
69
  # bash scripts/probe_live_eval.sh --ids G-GREET-01,G-TRIG-02 --model sonnet
70
70
  # bash scripts/probe_live_eval.sh --subset 3
71
71
  # bash scripts/probe_live_eval.sh --subset 3 --report-out /tmp/spot.md # spot-check: keep the nightly record untouched
72
+ # bash scripts/probe_live_eval.sh --target G-TRIG-02 --before tracks/_meta/live_eval_2026-10-16.md
73
+ # # after a repair aimed at one probe: target reported apart from the other probes, before/after
72
74
  # bash scripts/probe_live_eval.sh # full selected set — nightly cron shape
73
75
  #
74
76
  # PORTABILITY: bash 3.2 (macOS) + bash 5.x (Linux CI). No associative arrays, no `${var,,}`,
@@ -140,6 +142,8 @@ SUBSET=""
140
142
  IDS=""
141
143
  OUTDIR=""
142
144
  REPORT_OUT="" # --report-out: where the markdown report lands (default: tracks/_meta/live_eval_<date>.md)
145
+ TARGET="" # --target <probe-id>: report that probe apart from the rest (record only; default output unchanged)
146
+ BEFORE="" # --before <prior live_eval .md>: the "before" side of the --target split
143
147
  NO_EVIDENCE=0 # --no-evidence: skip the preserved-artifact copy (lanes / throwaway spot-checks)
144
148
  while [ $# -gt 0 ]; do
145
149
  case "$1" in
@@ -151,6 +155,8 @@ while [ $# -gt 0 ]; do
151
155
  --out) OUTDIR="${2:-}"; shift 2 ;;
152
156
  --report-out) REPORT_OUT="${2:-}"; shift 2 ;; # lanes/spot-checks MUST pass this — never the live path
153
157
  --no-evidence) NO_EVIDENCE=1; shift ;;
158
+ --target) TARGET="${2:-}"; shift 2 ;;
159
+ --before) BEFORE="${2:-}"; shift 2 ;;
154
160
  *) echo "unknown flag: $1" >&2; exit 2 ;;
155
161
  esac
156
162
  done
@@ -198,6 +204,15 @@ if [ "$SELECTED_COUNT" -eq 0 ]; then
198
204
  exit 2
199
205
  fi
200
206
 
207
+ # --target must name a probe that is actually in this run: a typo would otherwise burn the whole
208
+ # live run and only fail at report time.
209
+ if [ -n "$TARGET" ] && ! grep -qxF -- "$TARGET" "$SPEC_DIR/selected_ids.txt"; then
210
+ echo "❌ --target '$TARGET' is not among the selected probes (see SELECTED above) — refusing before any live call." >&2
211
+ rm -rf "$WORKDIR"
212
+ exit 2
213
+ fi
214
+ [ -z "$BEFORE" ] || [ -n "$TARGET" ] || { echo "❌ --before only makes sense with --target" >&2; rm -rf "$WORKDIR"; exit 2; }
215
+
201
216
  # `claude` presence is the REAL runner's preflight, so it is checked only on that path. Under
202
217
  # FH_SIM_RUNNER_BIN the stub owns its own preflight — measured 2026-09-05 on CI (ubuntu, no
203
218
  # `claude` installed): this line fired BEFORE the stub was ever called, so FF2/FF3/FF4/FF6 went
@@ -336,7 +351,10 @@ echo ""
336
351
  # default overwrote a real night's distribution once (2026-09-05 10:18: test_probe_live_eval_lanes.sh FF4
337
352
  # ran the real script with a stub runner and replaced the 02:30 report). Lanes pass --report-out.
338
353
  REPORT_PATH="${REPORT_OUT:-$REPO_ROOT/tracks/_meta/live_eval_${RUN_DATE}.md}"
339
- python3 "$LIB" score \
354
+ SCORE_EXTRA=()
355
+ [ -n "$TARGET" ] && SCORE_EXTRA+=(--target "$TARGET")
356
+ [ -n "$BEFORE" ] && SCORE_EXTRA+=(--before "$BEFORE")
357
+ python3 "$LIB" score ${SCORE_EXTRA[@]+"${SCORE_EXTRA[@]}"} \
340
358
  --probes-live "$PROBES_LIVE" \
341
359
  --select-json "$SELECT_JSON" \
342
360
  --ids-file "$SPEC_DIR/selected_ids.txt" \
@@ -368,6 +368,53 @@ def score_probe(primary_text, control_text, polarity, expect_re):
368
368
  return (PASS if not primary_hit else FAIL), primary_hit, control_hit
369
369
 
370
370
 
371
+ def _read_meta_tsv(path):
372
+ """key->value from a <arm>_r<n>.meta.tsv, or None when the file is absent."""
373
+ text = _read_text(path)
374
+ if text is None:
375
+ return None
376
+ out = {}
377
+ for line in text.splitlines():
378
+ if '\t' in line:
379
+ k, v = line.split('\t', 1)
380
+ out[k.strip()] = v.strip()
381
+ return out
382
+
383
+
384
+ def budget_line(base, arms_reps):
385
+ """BUDGET LINE (2026-10-17): the cap each verdict row ran under and whether any episode ENDED
386
+ AT it. Read from the runner's per-episode meta.tsv (written from the real invocation) — never
387
+ from constants in this file. `ended_at_cap` is three-valued: yes when ANY episode was cut at
388
+ its cap; otherwise UNKNOWN when any episode's value is UNKNOWN or its meta/field is missing
389
+ (an older run, or a stub that wrote none — not measured is not `no`); otherwise no.
390
+ Returns (ended_at_cap, text, n_yes, n_eps)."""
391
+ ends, caps = [], set()
392
+ for arm, i in arms_reps:
393
+ m = _read_meta_tsv(os.path.join(base, '%s_r%d.meta.tsv' % (arm, i)))
394
+ if m is None:
395
+ # No meta AND no transcript = the rep never ran: nothing to classify. A transcript
396
+ # without meta is an episode that ran unmeasured — UNKNOWN, never skipped (a skip
397
+ # let 2 `no` + 1 missing read as `no`).
398
+ if os.path.exists(os.path.join(base, '%s_r%d.txt' % (arm, i))):
399
+ ends.append('UNKNOWN')
400
+ continue
401
+ ends.append(m.get('ended_at_cap', 'UNKNOWN') or 'UNKNOWN')
402
+ caps.add('timeout=%ss max_turns=%s tokens=%s' % (
403
+ m.get('timeout_s', '?'), m.get('max_turns', '?'), m.get('token_cap', '?')))
404
+ if not caps:
405
+ return 'UNKNOWN', 'no episode meta (cap not recorded)', 0, len(ends)
406
+ n_yes = sum(1 for e in ends if e == 'yes')
407
+ if n_yes:
408
+ end = 'yes'
409
+ elif any(e != 'no' for e in ends):
410
+ end = 'UNKNOWN'
411
+ else:
412
+ end = 'no'
413
+ text = '%s ended_at_cap=%s%s' % ('; '.join(sorted(caps)), end,
414
+ ' (%d/%d episodes)' % (n_yes, len(ends)) if n_yes else '')
415
+ return end, text, n_yes, len(ends)
416
+
417
+
371
418
  def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
372
419
  """Read <run_root>/<id>/{primary,control}_r{1..reps}.txt for every id, score EACH rep, take the
373
420
  majority, and return a report dict. Does not touch the network or spawn `claude` — pure
@@ -396,7 +443,8 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
396
443
  for pid in ids_in_order:
397
444
  spec = by_id.get(pid)
398
445
  if spec is None:
399
- rows.append({'id': pid, 'verdict': 'UNKNOWN-ID', 'primary_hit': None, 'control_hit': None})
446
+ rows.append({'id': pid, 'verdict': 'UNKNOWN-ID', 'primary_hit': None, 'control_hit': None,
447
+ 'ended_at_cap': 'UNKNOWN', 'budget': 'n/a (unknown id)'})
400
448
  continue
401
449
  base = os.path.join(run_root, pid)
402
450
  has_ctrl_b = bool(spec.get('control_input_b'))
@@ -480,6 +528,10 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
480
528
  elif control_text is None or control_text == '':
481
529
  reasons.append('control: %s' % _failure_reason(base, 'control'))
482
530
  row['reason'] = '; '.join(reasons)
531
+ arms = ['primary', 'control'] + (['control_b'] if has_ctrl_b else [])
532
+ b_end, b_text, b_yes, b_n = budget_line(base, [(a, i) for a in arms for i in range(1, reps + 1)])
533
+ row['ended_at_cap'] = b_end
534
+ row['budget'] = b_text
483
535
  rows.append(row)
484
536
 
485
537
  # ── RUN-BLACKOUT / BLACKOUT-SUSPECT (2026-09-14) ──────────────────────────────────────────
@@ -568,6 +620,106 @@ def score_run(live_rows, run_root, ids_in_order, threshold, model, reps=1):
568
620
  }
569
621
 
570
622
 
623
+ def parse_prev_report(path):
624
+ """Rows of a previous live_eval_<date>.md run table -> {id: verdict}. None when unreadable or
625
+ no run table is found (the caller then says `before: not supplied`, never invents one)."""
626
+ text = _read_text(path)
627
+ if not text:
628
+ return None
629
+ out = {}
630
+ for line in text.splitlines():
631
+ cells = [c.strip() for c in line.strip().strip('|').split('|')]
632
+ if (line.startswith('|') and len(cells) >= 3
633
+ and cells[1] in (PASS, FAIL, UNCALIBRATED, FAILED_TO_RUN, 'UNKNOWN-ID')):
634
+ out[cells[0]] = cells[1]
635
+ return out or None
636
+
637
+
638
+ def _group_summary(verdicts, ended=None):
639
+ """verdicts: list of verdict strings -> counts. pass_rate is over PASS+FAIL only, the same
640
+ denominator score_run uses; None when nothing ran."""
641
+ ran = [v for v in verdicts if v in (PASS, FAIL)]
642
+ passed = [v for v in ran if v == PASS]
643
+ d = {'n': len(verdicts), 'ran': len(ran), 'passed': len(passed),
644
+ 'failed_to_run': sum(1 for v in verdicts if v == FAILED_TO_RUN),
645
+ 'uncalibrated': sum(1 for v in verdicts if v == UNCALIBRATED),
646
+ 'pass_rate': (len(passed) / float(len(ran))) if ran else None}
647
+ if ended is not None:
648
+ d['ended_at_cap_yes'] = sum(1 for e in ended if e == 'yes')
649
+ d['ended_at_cap_unknown'] = sum(1 for e in ended if e == 'UNKNOWN')
650
+ return d
651
+
652
+
653
+ def split_by_target(rows, target, before=None):
654
+ """--target <probe-id>: the targeted probe reported SEPARATELY from the rest, now and (when a
655
+ prior report is supplied) before. 'Fixed the target' and 'moved everything' are different
656
+ facts that one pooled pass_rate cannot tell apart. Record only: no verdict is changed and the
657
+ exit code never reads this. Returns None when target is not among the scored rows."""
658
+ tr = [r for r in rows if r['id'] == target]
659
+ if not tr:
660
+ return None
661
+ others = [r for r in rows if r['id'] != target]
662
+ res = {'target': target,
663
+ 'after_target': tr[0]['verdict'], 'after_target_cap': tr[0].get('ended_at_cap', 'UNKNOWN'),
664
+ 'after_others': _group_summary([r['verdict'] for r in others],
665
+ [r.get('ended_at_cap', 'UNKNOWN') for r in others]),
666
+ 'before': None, 'moved': []}
667
+ if before is not None:
668
+ oth_ids = [r['id'] for r in others]
669
+ b_oth = [before[i] for i in oth_ids if i in before]
670
+ res['before'] = {'target': before.get(target, 'ABSENT-IN-BEFORE'),
671
+ 'others': _group_summary(b_oth),
672
+ 'others_missing': [i for i in oth_ids if i not in before]}
673
+ res['moved'] = ['%s %s->%s' % (r['id'], before[r['id']], r['verdict'])
674
+ for r in others if r['id'] in before and before[r['id']] != r['verdict']]
675
+ return res
676
+
677
+
678
+ def _fmt_pr(g):
679
+ return ('%d/%d pass_rate=%s failed_to_run=%d uncalibrated=%d' % (
680
+ g['passed'], g['ran'], ('%.2f' % g['pass_rate']) if g['pass_rate'] is not None else 'n/a',
681
+ g['failed_to_run'], g['uncalibrated']))
682
+
683
+
684
+ def render_target_lines(t):
685
+ L = []
686
+ L.append('target=%s' % t['target'])
687
+ if t['before'] is not None:
688
+ L.append(' target before=%s after=%s (ended_at_cap=%s)' % (
689
+ t['before']['target'], t['after_target'], t['after_target_cap']))
690
+ L.append(' others before: %s' % _fmt_pr(t['before']['others']))
691
+ if t['before']['others_missing']:
692
+ L.append(' (not in before report, excluded from its count: %s)'
693
+ % ','.join(t['before']['others_missing']))
694
+ else:
695
+ L.append(' target before=not supplied (pass --before <prior live_eval .md>) after=%s '
696
+ '(ended_at_cap=%s)' % (t['after_target'], t['after_target_cap']))
697
+ L.append(' others after: %s ended_at_cap yes=%d unknown=%d' % (
698
+ _fmt_pr(t['after_others']), t['after_others']['ended_at_cap_yes'],
699
+ t['after_others']['ended_at_cap_unknown']))
700
+ if t['before'] is not None:
701
+ miss = t['before']['others_missing']
702
+ if t['moved']:
703
+ moved = ', '.join(t['moved'])
704
+ elif miss:
705
+ # «none» over a before-report that lacks those probes would read as «no movement».
706
+ moved = 'not comparable (%d others absent from before)' % len(miss)
707
+ else:
708
+ moved = 'none'
709
+ L.append(' others moved: %s' % moved)
710
+ return L
711
+
712
+
713
+ def render_target_md(t):
714
+ out = ['## Target split — %s' % t['target'], '',
715
+ 'Record only: the targeted probe is reported apart from the other probes so that '
716
+ '"fixed the target" is distinct from "moved everything". No verdict above depends on this.',
717
+ '']
718
+ out.extend('- ' + l.strip() if i else '- ' + l for i, l in enumerate(render_target_lines(t)))
719
+ out.append('')
720
+ return out
721
+
722
+
571
723
  def render_report_md(select_result, score_result, run_date):
572
724
  lines = []
573
725
  lines.append("# live_eval — %s" % run_date)
@@ -585,13 +737,13 @@ def render_report_md(select_result, score_result, run_date):
585
737
  if score_result is not None:
586
738
  lines.append("## Run — model=%s threshold=%.2f" % (score_result['model'], score_result['threshold']))
587
739
  lines.append("")
588
- lines.append("| Probe | Verdict | reps(pass/ran) | primary_hit | control_hit | polarity | Reason |")
589
- lines.append("|---|---|---|---|---|---|---|")
740
+ lines.append("| Probe | Verdict | reps(pass/ran) | primary_hit | control_hit | polarity | Reason | Budget |")
741
+ lines.append("|---|---|---|---|---|---|---|---|")
590
742
  for r in score_result['rows']:
591
- lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
743
+ lines.append("| %s | %s | %s | %s | %s | %s | %s | %s |" % (
592
744
  r['id'], r['verdict'], r.get('reps', '-'),
593
745
  r.get('primary_hit'), r.get('control_hit'), r.get('polarity', ''),
594
- _md_escape(r.get('reason', ''))))
746
+ _md_escape(r.get('reason', '')), _md_escape(r.get('budget', ''))))
595
747
  lines.append("")
596
748
  pr = score_result['pass_rate']
597
749
  pr_s = ("%.2f" % pr) if pr is not None else "n/a"
@@ -618,6 +770,8 @@ def render_report_md(select_result, score_result, run_date):
618
770
  "instrument failure produce this shape, and this file cannot tell them "
619
771
  "apart; the preserved response bodies can.")
620
772
  lines.append("")
773
+ if score_result is not None and score_result.get('target'):
774
+ lines.extend(render_target_md(score_result['target']))
621
775
  lines.append("## Excluded (from probes.md, 32-row snapshot)")
622
776
  lines.append("")
623
777
  lines.append("| Probe | Reason |")
@@ -705,8 +859,21 @@ def _cmd_score(args):
705
859
  reason = r.get('reason', '')
706
860
  if reason:
707
861
  line += " reason=%s" % reason
862
+ line += " | %s" % r.get('budget', '')
708
863
  print(line)
709
864
  print("")
865
+ if getattr(args, 'target', None):
866
+ before = parse_prev_report(args.before) if getattr(args, 'before', None) else None
867
+ if getattr(args, 'before', None) and before is None:
868
+ print("⚠️ --before %s unreadable or has no run table — before side NOT supplied" % args.before)
869
+ t = split_by_target(score_result['rows'], args.target, before)
870
+ if t is None:
871
+ print("❌ --target %s is not among the scored probes" % args.target, file=sys.stderr)
872
+ return 2
873
+ score_result['target'] = t
874
+ for l in render_target_lines(t):
875
+ print(l)
876
+ print("")
710
877
  pr = score_result['pass_rate']
711
878
  pr_s = ("%.2f" % pr) if pr is not None else "n/a"
712
879
  print("total=%d ran=%d failed_to_run=%d uncalibrated=%d passed=%d pass_rate=%s threshold=%.2f"
@@ -758,6 +925,8 @@ def main():
758
925
  sc.add_argument('--report-out')
759
926
  sc.add_argument('--run-date')
760
927
  sc.add_argument('--reps', type=int, default=1)
928
+ sc.add_argument('--target')
929
+ sc.add_argument('--before')
761
930
 
762
931
  args = ap.parse_args()
763
932
  if args.cmd == 'select':