@chrono-meta/fh-gate 3.11.0 → 3.13.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,704 @@
1
+ #!/usr/bin/env python3
2
+ """session_checklist.py — request-checklist close-report instrument («영혼 다지기» — the close-side warranty).
3
+
4
+ Two subcommands:
5
+
6
+ extract --transcript <jsonl> [--out <md>]
7
+ Reads a Claude Code transcript JSONL and emits a checklist SKELETON in
8
+ Markdown: one row per operator utterance, 상태 column EMPTY. Opens TWO
9
+ channels — raw entries and compaction-summary "All user messages"
10
+ sections — and prints how many of each it found (0 found still counts
11
+ as OPENED, never as "not opened"). See fh_signal_2026-09-18 for the
12
+ doctrine this mechanizes.
13
+
14
+ check --file <md>
15
+ Validates a FILLED checklist. FORM ONLY — this command never judges
16
+ whether a status is TRUE, only whether the record is well-formed
17
+ (closed-enum status; non-DONE/non-n/a rows carry 사유+제안; DONE rows
18
+ carry 증거). Judging truth is left to the human reader, on purpose
19
+ (§Mechanization Boundary: a channel check ages well, a truth check
20
+ freezes today's judgment into tomorrow's ceiling).
21
+
22
+ rc contract (check):
23
+ 0 clean — table found, every row well-formed
24
+ 1 violations — table found, one or more rows malformed
25
+ 4 DEAD CONTROL — a table with a 상태-column header was found but has
26
+ ZERO data rows ("nothing measured" must not read
27
+ as "clean")
28
+ 10 input error — file missing, OR no markdown table whose header
29
+ contains 상태 was found
30
+
31
+ rc contract (extract): 0 on success, 2 if one or more JSONL lines could not be
32
+ parsed (the table is still written — an unparsable line may have been an
33
+ utterance, so the run is never reported clean), 10 if the transcript is missing.
34
+
35
+ What `check` does NOT do: it does not open evidence links, does not verify
36
+ a 증거 pointer actually closes the request, and does not second-guess
37
+ whether ✅ was the right call. Form only.
38
+
39
+ Form details (v2/v3, after cross-family rounds 1–2): every table with a 상태 column
40
+ is checked (a clean earlier table cannot mask a later one); tables inside code
41
+ fences or indented 4+ spaces (CommonMark code) are ignored; a row with fewer
42
+ cells than the header is a violation;
43
+ compact status spellings (`✅DONE`, `DONE ✅`) are accepted on purpose — the
44
+ enum is the SET of statuses, not a spacing rule; invisible spacing (zero-width
45
+ space, NBSP) around a status is stripped; `/`-combos are accepted only when
46
+ every part is in the enum; `n.a.` is NOT an alias of `n/a` (closed enum, loud
47
+ by design). The compaction heading is matched by an alias table (English and
48
+ Korean spellings), and a list item that opens with a quote but never closes
49
+ it is still one utterance.
50
+
51
+ Classification of transcript entries is METADATA FIRST (v11): Claude Code marks
52
+ entries with `origin.kind` (human · task-notification · peer), `isMeta`,
53
+ `isCompactSummary` and `promptSource` — a human-origin entry is never excluded
54
+ by its text (a pasted envelope literal is a request), flagged entries are
55
+ excluded or routed by the flag, and the text-shape validators (opening marker +
56
+ closing/companion mark) apply only to entries that carry no metadata at all;
57
+ there a byte-identical pasted envelope is indistinguishable by design.
58
+ """
59
+ import argparse
60
+ import json
61
+ import os
62
+ import re
63
+ import sys
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # Shared status enum (closed)
67
+ # ---------------------------------------------------------------------------
68
+
69
+ STATUS_ENUM = {
70
+ "DONE": "\u2705", # ✅
71
+ "PARTIAL": "\U0001F7E1", # 🟡
72
+ "IN-PROGRESS": "\u23F3", # ⏳
73
+ "NOT-DONE": "\u274C", # ❌
74
+ "HELD": "\u23F8", # ⏸
75
+ "UNVERIFIED": "\U0001F50E", # 🔎
76
+ }
77
+
78
+ WORD_VARIANTS = {
79
+ "DONE": {"DONE"},
80
+ "PARTIAL": {"PARTIAL"},
81
+ "IN-PROGRESS": {"IN-PROGRESS", "IN PROGRESS", "INPROGRESS"},
82
+ "NOT-DONE": {"NOT-DONE", "NOT DONE", "NOTDONE"},
83
+ "HELD": {"HELD"},
84
+ "UNVERIFIED": {"UNVERIFIED"},
85
+ }
86
+
87
+ EMPTY_PLACEHOLDERS = {"", "-", "\u2014", "tbd", "?"} # '' '-' '—' 'tbd' '?'
88
+
89
+ VARIATION_SELECTOR_RE = re.compile("[\uFE0E\uFE0F]")
90
+
91
+
92
+ def strip_variation_selectors(s):
93
+ return VARIATION_SELECTOR_RE.sub("", s)
94
+
95
+
96
+ def is_empty_cell(cell):
97
+ v = (cell or "").strip()
98
+ return v == "" or v.lower() in EMPTY_PLACEHOLDERS or v in EMPTY_PLACEHOLDERS
99
+
100
+
101
+ def classify_single(part):
102
+ """Classify one '/'-separated piece of a status cell. Returns a key in
103
+ STATUS_ENUM, 'N/A', or None (invalid)."""
104
+ # v4 (codex round 3): zero-width / non-breaking spacing around the emoji is invisible to the reader —
105
+ # strip it before classifying. `n.a.` / `N.A.` are NOT aliases: the enum is closed on purpose (loud).
106
+ p = INVISIBLE_RE.sub("", (part or "")).strip()
107
+ if not p:
108
+ return None
109
+ if p.lower() == "n/a":
110
+ return "N/A"
111
+ p_clean = strip_variation_selectors(p)
112
+ for key, emoji in STATUS_ENUM.items():
113
+ if p_clean == emoji:
114
+ return key
115
+ if p_clean.startswith(emoji):
116
+ rest = p_clean[len(emoji):].strip()
117
+ if rest == "" or rest.upper() in WORD_VARIANTS[key]:
118
+ return key
119
+ if p_clean.endswith(emoji):
120
+ rest = p_clean[: -len(emoji)].strip()
121
+ if rest.upper() in WORD_VARIANTS[key]:
122
+ return key
123
+ p_upper = p_clean.upper()
124
+ for key, variants in WORD_VARIANTS.items():
125
+ if p_upper in variants:
126
+ return key
127
+ return None # ENUM-MEMBERSHIP-FALLTHROUGH
128
+
129
+
130
+ def classify_status(status_cell):
131
+ """Returns a set of matched keys (e.g. {'DONE'}, {'HELD','DONE'},
132
+ {'N/A'}), or None if the cell is empty/invalid."""
133
+ s = (status_cell or "").strip()
134
+ if s == "":
135
+ return None
136
+ if s.lower() == "n/a":
137
+ return {"N/A"}
138
+ if "/" in s:
139
+ keys = set()
140
+ for part in s.split("/"):
141
+ k = classify_single(part)
142
+ if k is None:
143
+ return None
144
+ keys.add(k)
145
+ return keys if keys else None
146
+ k = classify_single(s)
147
+ if k is None:
148
+ return None
149
+ return {k}
150
+
151
+
152
+ # ---------------------------------------------------------------------------
153
+ # extract
154
+ # ---------------------------------------------------------------------------
155
+
156
+ # v10 (codex round 9): every exclusion is an ENVELOPE VALIDATOR — the opening marker at line start AND the
157
+ # closing/companion mark the real Claude Code envelope always carries. A user utterance that merely starts
158
+ # with the same literal (a look-alike) has no closing mark and stays a row. (prefix, required companion)
159
+ # (prefix, companion, where): where="end" — the real envelope ENDS with the companion (nothing after the closing
160
+ # tag; `<command-name>deploy</command-name> is sample text…` has prose after it and is a row) · where="in" — the
161
+ # companion appears anywhere · where="" — the prefix sentence alone is the envelope.
162
+ EXCLUDE_ENVELOPES = (
163
+ ("<system-reminder>", "</system-reminder>", "end"),
164
+ ("[SYSTEM NOTIFICATION", "</task-notification>", "end"),
165
+ ("<task-notification>", "</task-notification>", "end"),
166
+ ("<local-command-stdout>", "</local-command-stdout>", "end"),
167
+ ("<local-command-caveat>", "</local-command-caveat>", "end"),
168
+ ("<command-name>", "<command-message>", "in"),
169
+ ("Caveat: The messages below were generated by the user while running local commands", "", ""), # v6: the synthetic caveat sentence itself
170
+ )
171
+
172
+ COMPACTION_PREFIX = "This session is being continued from a previous conversation"
173
+
174
+ # v4 (codex round 3): the compaction heading is localized in Korean sessions — an alias table, not one spelling.
175
+ USER_MESSAGES_HEADING_RE = re.compile(r"user messages|user utterances|사용자 메시지|사용자 발화|유저 메시지", re.IGNORECASE)
176
+ # v6 (codex round 5): the heading must be a HEADING LINE (numbered / hashed / bold, ending in a colon) — the phrase
177
+ # «user messages» anywhere in an ordinary utterance is not a compaction summary
178
+ USER_MESSAGES_HEADING_LINE_RE = re.compile(r"^\s*(?:\d+[.)]\s*)?(?:#+\s*)?(?:\*\*|__)?\s*(?:all\s+)?(?:user messages|user utterances|모든 사용자 메시지|사용자 메시지|사용자 발화|유저 메시지)[^\"\u201c\n]{0,60}$", re.IGNORECASE)
179
+ TRUNCATION_RE = re.compile(r"(?:\u2026|\.\.\.)\s*$")
180
+ INVISIBLE_RE = re.compile("[​‌‍⁠ ]")
181
+ # v8 (codex round 7): the section ends at the NEXT HEADING — a flush-left numbered line WITHOUT a quote
182
+ # (`7. Pending Tasks:` / `7) …`). A flush-left numbered item that carries a quote (`1. "…"`) is an item.
183
+ TOPLEVEL_NUMBERED_RE = re.compile(r"^\d+[.)]\s+(?!['\"\u201c])[^'\"\u201c\n]*$")
184
+ # v2 (codex round 1): a quoted span may cross a line break (summaries hard-wrap long quotes) and may
185
+ # contain escaped inner quotes (`\"quoted\"`); the v1 regex stopped at the first newline / inner quote,
186
+ # which silently dropped the utterance or split it in two. Items are joined first (bullet + its
187
+ # continuation lines), then quotes are pulled from each item.
188
+ QUOTE_RE = re.compile(r'"((?:[^"\\]|\\.){1,}?)"|\u201c((?:[^\u201d\\]|\\.){1,}?)\u201d', re.S)
189
+ ITEM_START_RE = re.compile(r"^\s*(?:[-*\u2022]\s+|\d+[.)]\s+)")
190
+ FENCE_RE = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
191
+
192
+
193
+ def get_text_and_kind(entry):
194
+ """Returns (text, has_text_block). has_text_block is False for a
195
+ tool_result-only / non-text user entry."""
196
+ msg = entry.get("message") or {}
197
+ content = msg.get("content")
198
+ if isinstance(content, str):
199
+ return content, True
200
+ if isinstance(content, list):
201
+ texts = []
202
+ has_text_block = False
203
+ for b in content:
204
+ if isinstance(b, dict) and b.get("type") == "text":
205
+ has_text_block = True
206
+ t = b.get("text")
207
+ if t:
208
+ texts.append(t)
209
+ if has_text_block:
210
+ return "\n".join(texts), True
211
+ return None, False
212
+ return None, False
213
+
214
+
215
+ def origin_kind(entry):
216
+ o = entry.get("origin")
217
+ return (o.get("kind") or "") if isinstance(o, dict) else ""
218
+
219
+
220
+ def has_metadata(entry):
221
+ """Claude Code marks entries: `origin.kind` (human · task-notification · peer), `isMeta`, `isCompactSummary`,
222
+ `promptSource`. Measured 2026-09-18 on a real transcript: 48/48 typed utterances carry origin.kind=human."""
223
+ return bool(entry.get("origin")) or "isMeta" in entry or "isCompactSummary" in entry or "promptSource" in entry
224
+
225
+
226
+ def is_excluded(text, entry):
227
+ # v11 (codex round 10): METADATA FIRST. A human-origin entry is never excluded by its text shape — a user who
228
+ # pastes an envelope literal, even a byte-identical one, is still a user. Text validators below apply only to
229
+ # entries that carry no metadata at all (older transcripts, hand-made fixtures).
230
+ if origin_kind(entry) == "human" or entry.get("promptSource") in ("typed", "queued"):
231
+ return False
232
+ if entry.get("isMeta") or origin_kind(entry) in ("task-notification", "peer", "system"):
233
+ return True
234
+ if has_metadata(entry) and origin_kind(entry) == "":
235
+ pass # metadata present but no origin — fall through to the text validators
236
+ stripped = text.lstrip()
237
+ for p, companion, where in EXCLUDE_ENVELOPES:
238
+ if not stripped.startswith(p):
239
+ continue
240
+ if where == "" or (where == "in" and companion in text) or (where == "end" and text.rstrip().endswith(companion)):
241
+ return True
242
+ # v9 (codex round 8): exclusions are ENVELOPE-shaped, never substring matches — an operator utterance that
243
+ # merely contains a marker literal (`<task-notification>` · `[Subagent hand-back]` · the peer-message sentence)
244
+ # is a request. The real envelopes: a task notification STARTS with its tag (or with the SYSTEM NOTIFICATION
245
+ # banner, handled above); a peer/subagent message STARTS with the sentence AND carries an `<agent-message` tag.
246
+ if stripped.startswith("Another Claude session sent a message:") and "<agent-message" in text:
247
+ return True
248
+ return False
249
+
250
+
251
+ def collapse(text):
252
+ return re.sub(r"\s+", " ", (text or "")).strip()
253
+
254
+
255
+ def extract_quotes_from_summary(text):
256
+ """Find the 'All user messages' section (bounded by the next top-level
257
+ numbered heading, or end of text) and pull every quoted span out of it,
258
+ in order. Returns a list of raw (uncollapsed) quote strings."""
259
+ lines = text.split("\n")
260
+ heading_idx = None
261
+ for i, ln in enumerate(lines):
262
+ if USER_MESSAGES_HEADING_LINE_RE.match(ln):
263
+ heading_idx = i
264
+ break
265
+ if heading_idx is None:
266
+ return []
267
+ end_idx = len(lines)
268
+ for j in range(heading_idx + 1, len(lines)):
269
+ ln = lines[j]
270
+ if TOPLEVEL_NUMBERED_RE.match(ln) and not ln[:1].isspace():
271
+ end_idx = j
272
+ break
273
+ # join each list item with its continuation lines, then pull the quotes out of each item
274
+ items = []
275
+ for ln in lines[heading_idx + 1: end_idx]:
276
+ if not ln.strip():
277
+ continue
278
+ if ITEM_START_RE.match(ln) or not items:
279
+ items.append(ln.strip())
280
+ else:
281
+ items[-1] = items[-1] + " " + ln.strip()
282
+ quotes = []
283
+ for it in items:
284
+ body = ITEM_START_RE.sub("", it, count=1).strip()
285
+ # v2: an item that IS one quote (opens and closes with a quote char) is taken whole — an inner
286
+ # unescaped quote (`"… the "quoted" word …"`) must not split it into two utterances
287
+ if len(body) >= 3 and body[0] in '"“' and body[-1] in '"”':
288
+ quotes.append(body[1:-1].replace('\\"', '"'))
289
+ continue
290
+ # v3 (codex round 2): an item that OPENS with a quote is one utterance — only its leading quote
291
+ # counts; a quote inside a trailing annotation (`"…" (already "summarized")`) is not a message.
292
+ # An item that does not open with a quote is a prose list of several quotes: take them all.
293
+ matches = list(QUOTE_RE.finditer(it))
294
+ if body[:1] in '"“':
295
+ if not matches:
296
+ # v4 (codex round 3): an item that opens with a quote whose closing quote is missing is still
297
+ # one utterance — capture through the item boundary instead of dropping it silently
298
+ quotes.append(body[1:].rstrip().replace('\\"', '"'))
299
+ continue
300
+ matches = matches[:1]
301
+ for m in matches:
302
+ q = m.group(1) if m.group(1) is not None else m.group(2)
303
+ quotes.append(q.replace('\\"', '"'))
304
+ return quotes
305
+
306
+
307
+ def normalize_utterance(text):
308
+ """Collapse whitespace and drop a trailing ellipsis so a truncated summary quote and its raw
309
+ original compare equal."""
310
+ return collapse(text).rstrip("…. ").strip()
311
+
312
+
313
+ def is_duplicate(summary_text, raw_norms):
314
+ """v2 (codex round 1): the v1 rule compared only the first 40 chars, so two DISTINCT requests
315
+ sharing an opening phrase collapsed into one. Now: equal after normalisation, or one is a prefix
316
+ of the other and the shorter side is at least 40 chars (a truncated quote of the same utterance)."""
317
+ q = normalize_utterance(summary_text)
318
+ if not q:
319
+ return True
320
+ q_trunc = bool(TRUNCATION_RE.search(collapse(summary_text)))
321
+ for r in raw_norms:
322
+ if q == r:
323
+ return True
324
+ # v6 (codex round 5): a prefix relation alone is not a duplicate — a distinct follow-up may share a long
325
+ # opening. Only a quote that visibly ends in a truncation marker («…» / «...») is folded into the longer text.
326
+ if q_trunc and len(q) >= 20 and r.startswith(q):
327
+ return True
328
+ return False
329
+
330
+
331
+ def format_ts(ts):
332
+ if not ts:
333
+ return "\u2014" # —
334
+ # "2026-09-17T05:56:11.019Z" -> "09-17 05:56"
335
+ m = re.match(r"^\d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})", ts)
336
+ if not m:
337
+ return "\u2014"
338
+ mm, dd, hh, mi = m.groups()
339
+ return "%s-%s %s:%s" % (mm, dd, hh, mi)
340
+
341
+
342
+ def md_escape(text):
343
+ return (text or "").replace("|", "\\|")
344
+
345
+
346
+ def do_extract(transcript_path, out_path):
347
+ if not os.path.isfile(transcript_path):
348
+ sys.stderr.write("error: transcript not found: %s\n" % transcript_path)
349
+ return 10
350
+
351
+ raw_rows = [] # [{ts, text}]
352
+ summary_texts = [] # raw compaction-entry text, in order
353
+ line_count = 0
354
+ parse_errors = 0
355
+
356
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
357
+ for line in f:
358
+ line_count += 1
359
+ line = line.strip()
360
+ if not line:
361
+ continue
362
+ try:
363
+ entry = json.loads(line)
364
+ except Exception:
365
+ parse_errors += 1
366
+ continue
367
+ if entry.get("type") != "user":
368
+ continue
369
+ text, has_text = get_text_and_kind(entry)
370
+ if not has_text or text is None or text.strip() == "":
371
+ continue
372
+ text = text.lstrip("\ufeff") # v5: a BOM before the compaction prefix hid the summary channel
373
+ if entry.get("isCompactSummary") is True:
374
+ # v11: the flag Claude Code sets on compaction entries — primary signal; the text shape is the fallback
375
+ summary_texts.append(text)
376
+ continue
377
+ if origin_kind(entry) == "human" or entry.get("promptSource") in ("typed", "queued"):
378
+ raw_rows.append({"ts": entry.get("timestamp"), "text": text})
379
+ continue
380
+ # v5 (codex round 4): the compaction prefix alone is not proof — an ordinary utterance can start with
381
+ # it. A compaction entry also carries a «user messages» section; without one it is a raw utterance.
382
+ if text.lstrip().startswith(COMPACTION_PREFIX) and any(USER_MESSAGES_HEADING_LINE_RE.match(l) for l in text.split("\n")) \
383
+ and extract_quotes_from_summary(text):
384
+ # v7 (codex round 6): boilerplate + heading is still not proof — a user drafting a compaction
385
+ # TEMPLATE has both and no quoted items. Only a section that yields ≥1 quote is a summary.
386
+ summary_texts.append(text)
387
+ continue
388
+ if is_excluded(text, entry):
389
+ continue
390
+ raw_rows.append({"ts": entry.get("timestamp"), "text": text})
391
+
392
+ raw_norms = [normalize_utterance(r["text"]) for r in raw_rows]
393
+
394
+ summary_found_total = 0
395
+ summary_rows = [] # [{text}]
396
+ seen_summary = [] # summary-vs-summary duplicates (the same quote restated by a later summary)
397
+ for stext in summary_texts:
398
+ quotes = extract_quotes_from_summary(stext)
399
+ summary_found_total += len(quotes)
400
+ for q in quotes:
401
+ if is_duplicate(q, raw_norms) or is_duplicate(q, seen_summary):
402
+ continue
403
+ seen_summary.append(normalize_utterance(q))
404
+ summary_rows.append({"text": q})
405
+
406
+ n_raw = len(raw_rows)
407
+ n_summary_found = summary_found_total
408
+ n_summary_added = len(summary_rows)
409
+ rc = 2 if parse_errors else 0 # v5: an unparsable line may have been an utterance — loud, never rc=0
410
+
411
+ lines_out = []
412
+ title = "# 세션 요청 체크리스트 (스켈레톤) — %s" % os.path.basename(transcript_path)
413
+ lines_out.append(title)
414
+ lines_out.append("")
415
+ lines_out.append(
416
+ "\ucc44\ub110 2/2 \uc5f4\uc74c \u2014 raw %d\uac74 \u00b7 \uc555\ucd95 \uc694\uc57d %d\uac74(\uc911\ubcf5 \uc81c\uac70 \ud6c4 %d\uac74 \ucd94\uac00)"
417
+ % (n_raw, n_summary_found, n_summary_added)
418
+ )
419
+ lines_out.append(chr(0x1F4CE) + " " + "원장 = %s (%d lines)" % (transcript_path, line_count))
420
+ if parse_errors:
421
+ lines_out.append("🟥 JSONL 파싱 실패 %d줄 — 그 줄의 발화는 이 표에 없다 (rc=2)" % parse_errors)
422
+ lines_out.append("")
423
+ lines_out.append(
424
+ "| # | \uc2dc\uac01 | \ubc1c\ud654(\uc694\uc9c0) | \uc0c1\ud0dc | \uc99d\uac70 | \uc0ac\uc720 / \ub0a8\uc740 \uac83 | \uc81c\uc548(\uc774\ubc88 \uc138\uc158 vs \uc774\uc6d4) |"
425
+ )
426
+ lines_out.append("|---|---|---|---|---|---|---|")
427
+
428
+ n = 0
429
+ for r in raw_rows:
430
+ n += 1
431
+ blurb = collapse(r["text"])
432
+ if len(blurb) > 160:
433
+ blurb = blurb[:160] + "\u2026"
434
+ lines_out.append(
435
+ "| %d | %s | %s | | | | |" % (n, format_ts(r["ts"]), md_escape(blurb))
436
+ )
437
+
438
+ s = 0
439
+ for r in summary_rows:
440
+ s += 1
441
+ blurb = collapse(r["text"])
442
+ if len(blurb) > 160:
443
+ blurb = blurb[:160] + "\u2026"
444
+ lines_out.append(
445
+ "| S%d | (요약) | %s | | | | |" % (s, md_escape(blurb))
446
+ )
447
+
448
+ content = "\n".join(lines_out) + "\n"
449
+ sys.stdout.write(content)
450
+
451
+ if out_path:
452
+ with open(out_path, "w", encoding="utf-8") as f:
453
+ f.write(content)
454
+
455
+ return rc
456
+
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # check
460
+ # ---------------------------------------------------------------------------
461
+
462
+ SPLIT_PIPE_RE = re.compile(r"(?<!\\)\|")
463
+
464
+
465
+ def split_row(line):
466
+ r"""v5 (codex round 4): `\|` is a literal pipe inside a cell (the utterance column carries them), not a
467
+ column boundary — a naive split shifted every later column and the checker read the wrong 상태 cell."""
468
+ s = line.strip()
469
+ if s.startswith("|"):
470
+ s = s[1:]
471
+ if s.endswith("|") and not s.endswith("\\|"):
472
+ s = s[:-1]
473
+ return [c.strip().replace("\\|", "|") for c in SPLIT_PIPE_RE.split(s)]
474
+
475
+
476
+ def is_separator_line(line):
477
+ """v7 (codex round 6): the delimiter row may omit the outer pipes too (`---|---|---`)."""
478
+ s = line.strip()
479
+ if "|" not in s and "-" not in s:
480
+ return False
481
+ inner = s.strip("|")
482
+ if inner == "":
483
+ return False
484
+ cells = SPLIT_PIPE_RE.split(inner)
485
+ return len(cells) >= 2 and all(re.fullmatch(r"[\s:\-]*", c) for c in cells) and any("-" in c for c in cells)
486
+
487
+
488
+ def find_header_index(header_cells, needle):
489
+ """v5 (codex round 4): an EXACT header cell wins; a contains-match is the fallback only when exactly one
490
+ cell contains the needle (`이전 상태 메모` next to `상태` used to steal the status column)."""
491
+ exact = [i for i, c in enumerate(header_cells) if c.strip() == needle]
492
+ if len(exact) == 1:
493
+ return exact[0]
494
+ if len(exact) > 1:
495
+ return -1 # ambiguous
496
+ loose = [i for i, c in enumerate(header_cells) if needle in c]
497
+ if len(loose) == 1:
498
+ return loose[0]
499
+ return -1 if len(loose) > 1 else None
500
+
501
+
502
+ def do_check(file_path):
503
+ if not os.path.isfile(file_path):
504
+ sys.stderr.write("error: file not found: %s\n" % file_path)
505
+ print("checklist: rows=0 ok=0 violations=0 rc=10")
506
+ return 10
507
+
508
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
509
+ raw = f.read()
510
+ if raw.startswith("\ufeff"):
511
+ raw = raw[1:]
512
+ lines = raw.splitlines()
513
+
514
+ # v2 (codex round 1): lines inside a code fence are not a table — a fenced example table used to be
515
+ # picked as THE checklist and mask the real one below it (rc=0 on a file with a bad row).
516
+ in_fence = [False] * len(lines)
517
+ fence_open = None # (char, length) — v5 (codex round 4): a closer must be the same char and at least as long
518
+ for i, ln in enumerate(lines):
519
+ m = FENCE_RE.match(ln)
520
+ if m:
521
+ tick = m.group(1)
522
+ if fence_open is None:
523
+ fence_open = (tick[0], len(tick))
524
+ in_fence[i] = True
525
+ continue
526
+ if tick[0] == fence_open[0] and len(tick) >= fence_open[1] and ln.strip() == tick:
527
+ fence_open = None
528
+ in_fence[i] = True
529
+ continue
530
+ in_fence[i] = fence_open is not None
531
+
532
+ # v2: EVERY table with a 상태 column is checked, not only the first — a clean earlier table used to
533
+ # mask a malformed later one.
534
+ # v3 (codex round 2): a line indented by 4+ spaces (or a tab) is a CommonMark indented code block,
535
+ # not a table row — an indented example used to be read as THE checklist (rc=0 with no real table).
536
+ def is_code_indented(ln):
537
+ return ln.startswith(" ") or ln.startswith("\t")
538
+
539
+ header_idxs = []
540
+ for i, ln in enumerate(lines):
541
+ if in_fence[i] or is_code_indented(ln):
542
+ continue
543
+ s = ln.strip()
544
+ # v7 (codex round 6): a header row may omit the outer pipes — a line with an unescaped `|` and 상태 qualifies
545
+ if not SPLIT_PIPE_RE.search(s) or "상태" not in s or i + 1 >= len(lines):
546
+ continue
547
+ if is_code_indented(lines[i + 1]) or not is_separator_line(lines[i + 1]):
548
+ continue # v5: an indented delimiter row is code, so this is not a table
549
+ header_idxs.append(i)
550
+
551
+ if not header_idxs:
552
+ sys.stderr.write("error: no markdown table with a 상태-column header found in %s\n" % file_path)
553
+ print("checklist: rows=0 ok=0 violations=0 rc=10")
554
+ return 10
555
+
556
+ tables = [] # [(header_cells, rows)]
557
+ for header_idx in header_idxs:
558
+ header_cells = split_row(lines[header_idx])
559
+ rows = []
560
+ j = header_idx + 2
561
+ # v6 (codex round 5): GFM rows may omit the outer pipes — a row is any non-blank, non-code line with an
562
+ # unescaped `|` until the first blank / pipe-less line
563
+ while j < len(lines) and lines[j].strip() != "" and SPLIT_PIPE_RE.search(lines[j]) and not in_fence[j] and not is_code_indented(lines[j]):
564
+ rows.append(split_row(lines[j]))
565
+ j += 1
566
+ tables.append((header_cells, rows))
567
+
568
+ if sum(len(r) for _, r in tables) == 0:
569
+ print("checklist: rows=0 ok=0 violations=0 rc=4")
570
+ return 4
571
+
572
+ def cell(cells, idx):
573
+ if idx is None or idx >= len(cells):
574
+ return ""
575
+ return cells[idx]
576
+
577
+ violations = []
578
+ ok_count = 0
579
+ n_rows = 0
580
+
581
+ for t_no, (header_cells, rows) in enumerate(tables, start=1):
582
+ idx_status = find_header_index(header_cells, "상태")
583
+ idx_evidence = find_header_index(header_cells, "증거")
584
+ idx_reason = find_header_index(header_cells, "사유")
585
+ idx_proposal = find_header_index(header_cells, "제안")
586
+ # v5 (codex round 4): the canonical columns must all be present and unambiguous — a table with only
587
+ # `#` and 상태 is not a checklist (its rows could never carry evidence / reason / proposal)
588
+ missing = [n for n, ix in (("상태", idx_status), ("증거", idx_evidence), ("사유", idx_reason), ("제안", idx_proposal)) if ix is None]
589
+ ambiguous = [n for n, ix in (("상태", idx_status), ("증거", idx_evidence), ("사유", idx_reason), ("제안", idx_proposal)) if ix == -1]
590
+ if missing or ambiguous:
591
+ sys.stderr.write("error: checklist schema — missing columns %s, ambiguous columns %s (table %d)\n" % (missing, ambiguous, t_no))
592
+ print("checklist: rows=0 ok=0 violations=0 rc=10")
593
+ return 10
594
+ idx_num = None
595
+ for i, c in enumerate(header_cells):
596
+ if c.strip() == "#":
597
+ idx_num = i
598
+ break
599
+ if idx_num is None:
600
+ idx_num = 0
601
+ tprefix = "" if len(tables) == 1 else "table %d " % t_no
602
+
603
+ for pos, cells in enumerate(rows, start=1):
604
+ n_rows += 1
605
+ num_val = cell(cells, idx_num).strip()
606
+ label = tprefix + (num_val if num_val else str(pos))
607
+
608
+ # v2: a row shorter than the header is malformed — a truncated `| 1 | … | n/a |` used to pass
609
+ if len(cells) < len(header_cells):
610
+ violations.append("row %s short (%d cells < header %d)" % (label, len(cells), len(header_cells)))
611
+ continue
612
+
613
+ status_cell = cell(cells, idx_status)
614
+ if status_cell.strip() == "":
615
+ violations.append("row %s missing 상태" % label)
616
+ continue
617
+ keys = classify_status(status_cell)
618
+ if keys is None:
619
+ violations.append("row %s invalid 상태 (got '%s')" % (label, status_cell.strip()))
620
+ continue
621
+
622
+ is_na = keys == {"N/A"}
623
+ contains_done = "DONE" in keys
624
+ purely_done = keys == {"DONE"}
625
+ row_ok = True
626
+
627
+ if contains_done and is_empty_cell(cell(cells, idx_evidence)):
628
+ violations.append("row %s DONE missing 증거" % label)
629
+ row_ok = False
630
+
631
+ if not is_na and not purely_done:
632
+ if is_empty_cell(cell(cells, idx_reason)):
633
+ violations.append("row %s missing 사유" % label)
634
+ row_ok = False
635
+ if is_empty_cell(cell(cells, idx_proposal)):
636
+ violations.append("row %s missing 제안" % label)
637
+ row_ok = False
638
+
639
+ if row_ok:
640
+ ok_count += 1
641
+
642
+ for v in violations:
643
+ print(v)
644
+
645
+ rc = 1 if violations else 0
646
+ extra = "" if len(tables) == 1 else " tables=%d" % len(tables)
647
+ print("checklist: rows=%d ok=%d violations=%d rc=%d%s" % (n_rows, ok_count, len(violations), rc, extra))
648
+ return rc
649
+
650
+
651
+ # ---------------------------------------------------------------------------
652
+ # CLI
653
+ # ---------------------------------------------------------------------------
654
+
655
+ RC_CONTRACT_TEXT = """rc contract (check):
656
+ rc=0 clean - table found, every row well-formed
657
+ rc=1 violations - table found, one or more rows malformed
658
+ rc=4 DEAD CONTROL - a table with a status(\uc0c1\ud0dc) header was found but has
659
+ ZERO data rows (nothing measured must not read as clean)
660
+ rc=10 input error - file missing, or no table with a \uc0c1\ud0dc column found
661
+
662
+ check never judges whether a status is TRUE -- form only.
663
+ """
664
+
665
+
666
+ def build_parser():
667
+ parser = argparse.ArgumentParser(
668
+ prog="session_checklist.py",
669
+ description="Request-checklist close-report instrument (extract / check).",
670
+ epilog=RC_CONTRACT_TEXT,
671
+ formatter_class=argparse.RawDescriptionHelpFormatter,
672
+ )
673
+ sub = parser.add_subparsers(dest="cmd")
674
+
675
+ p_extract = sub.add_parser("extract", help="extract a checklist skeleton from a transcript JSONL")
676
+ p_extract.add_argument("--transcript", required=True)
677
+ p_extract.add_argument("--out", default=None)
678
+
679
+ p_check = sub.add_parser(
680
+ "check",
681
+ help="validate a filled checklist",
682
+ epilog=RC_CONTRACT_TEXT,
683
+ formatter_class=argparse.RawDescriptionHelpFormatter,
684
+ )
685
+ p_check.add_argument("--file", required=True)
686
+
687
+ return parser
688
+
689
+
690
+ def main(argv=None):
691
+ parser = build_parser()
692
+ args = parser.parse_args(argv)
693
+
694
+ if args.cmd == "extract":
695
+ return do_extract(args.transcript, args.out)
696
+ if args.cmd == "check":
697
+ return do_check(args.file)
698
+
699
+ parser.print_help()
700
+ return 10
701
+
702
+
703
+ if __name__ == "__main__":
704
+ sys.exit(main())