@chrono-meta/fh-gate 3.13.0 → 3.14.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.
@@ -499,22 +499,29 @@ def find_header_index(header_cells, needle):
499
499
  return -1 if len(loose) > 1 else None
500
500
 
501
501
 
502
- def do_check(file_path):
502
+ def load_tables(file_path):
503
+ """Locate every markdown table with a 상태 column. SINGLE SOURCE for both `check` and `unblocked`.
504
+
505
+ 🟥 Extracted 2026-09-19 rather than copied. This repo has a named failure for the alternative
506
+ («관대함 갈린 중복 정규화» — two preprocessors that disagree let an input pass one and be dropped
507
+ silently by the other). Every hardening below (v2–v7, cross-family rounds 1–6) is therefore shared:
508
+ code fences, 4-space indented blocks, outer-pipe-less rows, and the ambiguous-header guard.
509
+
510
+ Returns (tables, rc) where rc is None on success and an int rc when the caller must return it:
511
+ 10 file missing / no 상태-header table found
512
+ 4 DEAD CONTROL — a 상태 table exists but has ZERO data rows ("nothing measured" != "clean")
513
+ """
503
514
  if not os.path.isfile(file_path):
504
515
  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
-
516
+ return None, 10
508
517
  with open(file_path, "r", encoding="utf-8", errors="replace") as f:
509
518
  raw = f.read()
510
519
  if raw.startswith("\ufeff"):
511
520
  raw = raw[1:]
512
521
  lines = raw.splitlines()
513
522
 
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
523
  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
524
+ fence_open = None
518
525
  for i, ln in enumerate(lines):
519
526
  m = FENCE_RE.match(ln)
520
527
  if m:
@@ -529,10 +536,6 @@ def do_check(file_path):
529
536
  continue
530
537
  in_fence[i] = fence_open is not None
531
538
 
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
539
  def is_code_indented(ln):
537
540
  return ln.startswith(" ") or ln.startswith("\t")
538
541
 
@@ -540,32 +543,39 @@ def do_check(file_path):
540
543
  for i, ln in enumerate(lines):
541
544
  if in_fence[i] or is_code_indented(ln):
542
545
  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
+ s2 = ln.strip()
547
+ if not SPLIT_PIPE_RE.search(s2) or "상태" not in s2 or i + 1 >= len(lines):
546
548
  continue
547
549
  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
550
+ continue
549
551
  header_idxs.append(i)
550
552
 
551
553
  if not header_idxs:
552
554
  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
+ return None, 10
555
556
 
556
- tables = [] # [(header_cells, rows)]
557
+ tables = []
557
558
  for header_idx in header_idxs:
558
559
  header_cells = split_row(lines[header_idx])
559
560
  rows = []
560
561
  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]):
562
+ while (j < len(lines) and lines[j].strip() != "" and SPLIT_PIPE_RE.search(lines[j])
563
+ and not in_fence[j] and not is_code_indented(lines[j])):
564
564
  rows.append(split_row(lines[j]))
565
565
  j += 1
566
566
  tables.append((header_cells, rows))
567
567
 
568
568
  if sum(len(r) for _, r in tables) == 0:
569
+ return tables, 4
570
+ return tables, None
571
+
572
+
573
+ def do_check(file_path):
574
+ tables, rc = load_tables(file_path)
575
+ if rc == 10:
576
+ print("checklist: rows=0 ok=0 violations=0 rc=10")
577
+ return 10
578
+ if rc == 4:
569
579
  print("checklist: rows=0 ok=0 violations=0 rc=4")
570
580
  return 4
571
581
 
@@ -676,6 +686,11 @@ def build_parser():
676
686
  p_extract.add_argument("--transcript", required=True)
677
687
  p_extract.add_argument("--out", default=None)
678
688
 
689
+ p_unblocked = sub.add_parser(
690
+ "unblocked",
691
+ help="surface rows whose blocker is DONE but which are still open")
692
+ p_unblocked.add_argument("--file", required=True)
693
+
679
694
  p_check = sub.add_parser(
680
695
  "check",
681
696
  help="validate a filled checklist",
@@ -687,6 +702,98 @@ def build_parser():
687
702
  return parser
688
703
 
689
704
 
705
+ DEP_RE = re.compile(r"\b([A-Z]{1,3}\d{1,3})\s*(?:선행|착지\s*후|이후|완료\s*후|after)\b")
706
+
707
+
708
+ def do_unblocked(file_path):
709
+ """Surface rows whose declared BLOCKER is now DONE but which are themselves still not DONE.
710
+
711
+ WHY THIS EXISTS (2026-09-19, measured on this repo's own checklist). Three operator requests
712
+ degraded mid-session. They were NOT missing from the checklist — they were ON it, marked
713
+ blocked on row A13, and A13 later landed DONE. Nothing re-read the checklist at that moment,
714
+ so A6/A8/A9 sat unblocked and idle until the operator asked again. The operator's prescription
715
+ was literal: "체크리스트를 쓰고 그걸 네가 테스트 한차례 끝날때마다 들여다봐야할것같아."
716
+
717
+ 🟥 This is a CHANNEL check, not a judgment (§Mechanization Boundary). It asserts a property of
718
+ the RECORD — this row names a blocker, that blocker reads DONE, this row does not — and never
719
+ asserts that the row *should* now be worked. A truth check would freeze today's judgment; a
720
+ channel check ages well.
721
+
722
+ rc contract:
723
+ 0 nothing is unblocked-and-idle, AND at least one dependency edge was found
724
+ 1 one or more rows are unblocked but still idle (the finding)
725
+ 4 DEAD CONTROL — rows exist but ZERO dependency edges were parsed. "0 findings" from an
726
+ instrument that found nothing to look at is not a clean bill; it is an unread channel.
727
+ 10 input error (file missing / no 상태 table), inherited from load_tables
728
+ """
729
+ tables, rc = load_tables(file_path)
730
+ if rc == 10:
731
+ print("unblocked: rows=0 edges=0 findings=0 rc=10")
732
+ return 10
733
+ if rc == 4:
734
+ print("unblocked: rows=0 edges=0 findings=0 rc=4")
735
+ return 4
736
+
737
+ status_by_id = {}
738
+ rows_flat = []
739
+ for header_cells, rows in tables:
740
+ idx_status = find_header_index(header_cells, "상태")
741
+ if idx_status is None or idx_status == -1:
742
+ continue
743
+ idx_num = None
744
+ for i, c in enumerate(header_cells):
745
+ if c.strip() == "#":
746
+ idx_num = i
747
+ break
748
+ if idx_num is None:
749
+ idx_num = 0
750
+ for cells in rows:
751
+ if idx_num >= len(cells):
752
+ continue
753
+ rid = re.sub(r"[^A-Za-z0-9]", "", cells[idx_num]).upper()
754
+ if not rid:
755
+ continue
756
+ keys = classify_status(cells[idx_status] if idx_status < len(cells) else "")
757
+ status_by_id[rid] = keys
758
+ rows_flat.append((rid, keys, cells))
759
+
760
+ edges = 0
761
+ findings = []
762
+ for rid, keys, cells in rows_flat:
763
+ # 🟥 EDGES ARE COUNTED FOR EVERY ROW, findings only for open ones. Counting edges only on
764
+ # open rows collapsed two different nothings into the same rc=4: "every dependency was
765
+ # resolved and closed" and "nobody ever wrote a dependency". The first is a clean run; the
766
+ # second is an unread channel. («not found» is not «0» — the named family in this repo.)
767
+ idle = not ("DONE" in keys or "n/a" in keys)
768
+ joined = " | ".join(cells)
769
+ for m in DEP_RE.finditer(joined):
770
+ dep = m.group(1).upper()
771
+ if dep == rid or dep not in status_by_id:
772
+ continue # a pointer to a row that does not exist is a different defect (phantom)
773
+ edges += 1
774
+ if idle and "DONE" in status_by_id[dep]:
775
+ findings.append((rid, dep, m.group(0)))
776
+
777
+ # dedupe: one finding per (row, blocker)
778
+ seen = set()
779
+ uniq = []
780
+ for f in findings:
781
+ k = (f[0], f[1])
782
+ if k not in seen:
783
+ seen.add(k)
784
+ uniq.append(f)
785
+
786
+ for rid, dep, phrase in uniq:
787
+ print(" ⚠️ %s is still open, but its blocker %s reads DONE («%s»)" % (rid, dep, phrase))
788
+
789
+ if edges == 0:
790
+ print("unblocked: rows=%d edges=0 findings=0 rc=4 — DEAD CONTROL: no dependency edge parsed"
791
+ % len(rows_flat))
792
+ return 4
793
+ print("unblocked: rows=%d edges=%d findings=%d rc=%d" % (len(rows_flat), edges, len(uniq), 1 if uniq else 0))
794
+ return 1 if uniq else 0
795
+
796
+
690
797
  def main(argv=None):
691
798
  parser = build_parser()
692
799
  args = parser.parse_args(argv)
@@ -695,6 +802,8 @@ def main(argv=None):
695
802
  return do_extract(args.transcript, args.out)
696
803
  if args.cmd == "check":
697
804
  return do_check(args.file)
805
+ if args.cmd == "unblocked":
806
+ return do_unblocked(args.file)
698
807
 
699
808
  parser.print_help()
700
809
  return 10
@@ -314,6 +314,7 @@ _PYEOF
314
314
 
315
315
  BASE_REF=""; BASE_SHA=""
316
316
  ARM=""; REPS=1; PROMPT=""; MODE="observe"; MODEL="sonnet"; TIMEOUT=900; OUTDIR=""; NOHARNESS=0; SETUP=""; EXTRA=""
317
+ TURNS=""; NORESUME=0
317
318
  while [ $# -gt 0 ]; do
318
319
  case "$1" in
319
320
  --arm) ARM="${2:-}"; shift 2 ;;
@@ -329,15 +330,149 @@ while [ $# -gt 0 ]; do
329
330
  --setup) SETUP="${2:-}"; shift 2 ;; # shell run INSIDE each clone before the sim. See below.
330
331
  --extra-tools) EXTRA="${2:-}"; shift 2 ;; # append tools to the mode's set. See TOOL VISIBILITY.
331
332
  --mcp-config) MCPCFG="${2:-}"; shift 2 ;; # the ONLY MCP servers an arm may see (see MCP ISOLATION). Default: none.
333
+ --turns) TURNS="${2:-}"; shift 2 ;; # MULTI-TURN: one turn per line. See §MULTI-TURN.
334
+ --no-resume) NORESUME=1; shift ;; # CONTROL arm for --turns:each turn is a fresh session. See §MULTI-TURN.
332
335
  *) echo "unknown flag: $1" >&2; exit 2 ;;
333
336
  esac
334
337
  done
335
338
  [ -n "$ARM" ] || { echo "FAIL: --arm required" >&2; exit 2; }
336
- [ -n "$PROMPT" ] || { echo "FAIL: --prompt required" >&2; exit 2; }
339
+ [ -n "$PROMPT" ] || [ -n "$TURNS" ] || { echo "FAIL: --prompt or --turns required" >&2; exit 2; }
337
340
  case "$MODE" in observe|act) ;; *) echo "FAIL: --mode must be observe|act" >&2; exit 2 ;; esac
338
341
 
339
342
  command -v claude >/dev/null 2>&1 || { echo "FAIL: claude CLI not on PATH" >&2; exit 2; }
340
343
 
344
+ # ── §MULTI-TURN — 티키타카를 재는 자리 (2026-09-19) ──────────────────────────────
345
+ #
346
+ # WHY THIS EXISTS, and what it measures that the single-shot path CANNOT:
347
+ # A single `-p` call measures **"does it fire"** — the greeting appears, the gate blocks, the
348
+ # rule is reached. That is the whole existing probe vocabulary and it is a real question.
349
+ # It cannot reach a second class of question, because that class only exists across turns:
350
+ # · does a NEGOTIATION converge (user pushes back → trade-offs surface → a compromise lands)
351
+ # · does the compromise then get APPLIED — i.e. is turn 4 bound by what was agreed in turn 3
352
+ # FH had measured the first and never the second. `--turns` is that axis, not a convenience.
353
+ #
354
+ # HOW: turn 1 runs normally and its `session_id` is captured from `--output-format json`;
355
+ # turns 2..N run with `--resume <sid>`. Isolation is UNCHANGED — same disposable clone,
356
+ # same tool set, same `--strict-mcp-config`, same `< /dev/null`, same timeout per turn.
357
+ #
358
+ # 🟥 `--no-resume` IS THE CONTROL, and it is not optional when you report a number.
359
+ # It runs the identical turn list with NO resume, so every turn is a cold session. A behaviour
360
+ # that survives `--no-resume` was never carried by the conversation — it was carried by the
361
+ # prompt text of that one turn. Same shape as `--no-harness` above: the defect is the
362
+ # instrument ([[feedback_control_presence_is_not_discrimination]]).
363
+ #
364
+ # 🟥 A TURN IS ONE LINE. A turns file cannot express a multi-line utterance, on purpose: the
365
+ # alternative (a delimiter) silently swallows a turn whose text contains the delimiter, and a
366
+ # swallowed turn reads as a shorter conversation, not as an error.
367
+ # Blank lines and `#` comments are skipped. `\n` is NOT unescaped — what you write is what the
368
+ # session receives.
369
+ #
370
+ # 🟥 SESSION STATE IS NOT IN THE CLONE. `--resume` reads ~/.claude, not the working tree, so the
371
+ # per-rep clone does NOT isolate conversation state between reps. Each rep starts a NEW session
372
+ # (turn 1 has no --resume), so reps do not see each other — but a crashed rep leaves its session
373
+ # on disk. That is a disk-growth note, not a contamination path; nothing reads it back.
374
+ if [ -n "$TURNS" ]; then
375
+ [ -f "$TURNS" ] || { echo "FAIL: --turns file not found: $TURNS" >&2; exit 2; }
376
+ [ -z "$PROMPT" ] || { echo "FAIL: --turns and --prompt are mutually exclusive" >&2; exit 2; }
377
+ TURNLIST=()
378
+ # 🟥 The turns file is read into an array FIRST, and this loop body runs no command.
379
+ # A `while read … done < file` loop whose body invokes something hands that something the
380
+ # REST OF THE FILE as stdin — that is the 2026-08-31 defect documented at the exec site
381
+ # below, where every arm silently received the scoring key. Reading first removes the hazard
382
+ # by construction rather than by remembering a redirect.
383
+ while IFS= read -r _tl || [ -n "$_tl" ]; do
384
+ case "$_tl" in ''|'#'*) continue ;; esac
385
+ TURNLIST+=("$_tl")
386
+ done < "$TURNS"
387
+ [ "${#TURNLIST[@]}" -gt 0 ] || { echo "FAIL: --turns file has no turns (blank/comment only): $TURNS" >&2; exit 2; }
388
+ PROMPT="${TURNLIST[0]}" # downstream banners/dumps still have something truthful to show
389
+ fi
390
+
391
+ # fh_run_turns <rep> — runs TURNLIST in one resumed session. Writes:
392
+ # <arm>_r<n>.t<k>.{prompt.txt,json,txt,stderr.txt} per turn
393
+ # <arm>_r<n>.txt concatenated results (same shape the
394
+ # single-shot path produces, so existing
395
+ # scorers keep working unchanged)
396
+ # <arm>_r<n>.turns.tsv k, rc, session_id, bytes — the audit row
397
+ # Returns the rc of the LAST turn. 🟥 A mid-conversation failure does NOT abort the remaining
398
+ # turns: a conversation that broke at turn 2 and a conversation that never got there look
399
+ # identical if we stop, and only one of them is the finding.
400
+ fh_run_turns() {
401
+ local _r="$1" _k=0 _sid="" _rc=0 _lastrc=0 _t _tf _res _anyfail=0 _firstbad=0 _failrc=0
402
+ local _base="$OUTDIR/${ARM}_r${_r}"
403
+ : > "${_base}.txt"
404
+ printf 'turn\trc\tsession_id\tresult_bytes\tnote\n' > "${_base}.turns.tsv"
405
+ for _t in "${TURNLIST[@]}"; do
406
+ _k=$((_k+1)); _tf="${_base}.t${_k}"
407
+ printf '%s' "$_t" > "${_tf}.prompt.txt"
408
+ local _resume=()
409
+ if [ -n "$_sid" ] && [ "$NORESUME" -eq 0 ]; then _resume=(--resume "$_sid"); fi
410
+ ( cd "$WORK" && fh_timeout "$TIMEOUT" claude -p "$_t" \
411
+ --model "$MODEL" "${TOOLS[@]}" ${MCPARGS[@]+"${MCPARGS[@]}"} \
412
+ ${_resume[@]+"${_resume[@]}"} --output-format json \
413
+ < /dev/null 2>"${_tf}.stderr.txt" ) > "${_tf}.json"
414
+ _rc=$?; _lastrc=$_rc
415
+ # 🟥 Parse with python, not grep/sed — a result body containing `"session_id"` verbatim (this
416
+ # repo's own prose does) would fool a regex, and the failure would be a WRONG id, not an
417
+ # empty one. Wrong-and-plausible is the expensive kind.
418
+ # 🟥 exit 3 = PARSE FAILURE, and it is NOT the same as an empty answer. The first build of
419
+ # this wrote "" and exited 0, so unparseable output read as "the session said nothing" —
420
+ # a failure folded into a benign result. cross-family (codex) named it S-tier.
421
+ _res=$(python3 - "${_tf}.json" "${_tf}.txt" <<'_PYT'
422
+ import json,sys
423
+ src,dst=sys.argv[1],sys.argv[2]
424
+ try:
425
+ d=json.load(open(src,encoding="utf-8"))
426
+ if not isinstance(d,dict): raise ValueError("not an object")
427
+ except Exception:
428
+ open(dst,"w",encoding="utf-8").write("")
429
+ print("\t0"); raise SystemExit(3)
430
+ r=d.get("result")
431
+ r="" if r is None else (r if isinstance(r,str) else json.dumps(r,ensure_ascii=False))
432
+ open(dst,"w",encoding="utf-8").write(r)
433
+ print("%s\t%d"%(d.get("session_id") or "", len(r.encode("utf-8"))))
434
+ _PYT
435
+ )
436
+ local _prc=$?
437
+ local _newsid="${_res%% *}" _rbytes="${_res##* }"
438
+ [ -n "$_newsid" ] && _sid="$_newsid"
439
+ local _note=""
440
+ [ "$_prc" -eq 3 ] && _note="PARSE_FAILED"
441
+ printf '%s\t%s\t%s\t%s\t%s\n' "$_k" "$_rc" "${_newsid:-NONE}" "${_rbytes:-0}" "${_note:-ok}" >> "${_base}.turns.tsv"
442
+ { printf '\n===== turn %s (rc=%s) =====\n' "$_k" "$_rc"; cat "${_tf}.txt" 2>/dev/null; } >> "${_base}.txt"
443
+ # 🟥 ANY turn that failed makes the REP failed. Returning only the last turn's rc let a
444
+ # conversation that died at turn 2 and recovered at turn 3 report rc=0 — and because the
445
+ # transcript always carries `===== turn` markers, bytes is never 0, so the outer verdict
446
+ # printed "✅ captured" and "RESULT: CLEAN" over a broken run. cross-family S-tier.
447
+ if [ "$_rc" -ne 0 ] || [ "$_prc" -eq 3 ]; then
448
+ _anyfail=1; [ "$_firstbad" -eq 0 ] && _firstbad=$_k
449
+ [ "$_failrc" -eq 0 ] && { [ "$_rc" -ne 0 ] && _failrc=$_rc || _failrc=3; }
450
+ fi
451
+ # 🟥 EVERY turn, not only turn 1. A missing session_id mid-conversation means this turn did
452
+ # NOT run in the same session — the one thing a multi-turn measurement asserts — and the
453
+ # old code silently reused the previous id, so the evidence vanished while the run stayed
454
+ # clean. cross-family A-tier.
455
+ if [ "$NORESUME" -eq 0 ] && [ -z "$_newsid" ]; then
456
+ echo " 🟥 r${_r} turn ${_k} returned NO session_id — this turn did not demonstrably run"
457
+ echo " in the same session. The run is NOT a multi-turn measurement. Do not score it."
458
+ CONTAMINATED=1; _anyfail=1; [ "$_firstbad" -eq 0 ] && _firstbad=$_k
459
+ [ "$_failrc" -eq 0 ] && _failrc=3
460
+ fi
461
+ done
462
+ if [ "$_anyfail" -ne 0 ]; then
463
+ # 🟥 CONTAMINATED, not a nonzero exit. This script ends in a deliberate `exit 0`
464
+ # ("Detector, never a gate") so a caller cannot be trained to skip running it — so the
465
+ # channel for "do not score this" is CONTAMINATED, and a broken conversation belongs in
466
+ # it. Returning nonzero here instead would have been correct-looking and invisible.
467
+ echo " 🟥 r${_r} MULTI-TURN INCOMPLETE — first failing turn: ${_firstbad} (see ${_base}.turns.tsv)"
468
+ echo " A conversation that broke mid-way is not a shorter conversation. Do not score it."
469
+ CONTAMINATED=1
470
+ return "$_failrc"
471
+ fi
472
+ return "$_lastrc"
473
+ }
474
+
475
+
341
476
  # ── timeout(1) resolution — see §timeout(1) RESOLUTION in the header above for WHY. ──────────────
342
477
  # GNU `timeout` → Homebrew's `gtimeout` → a bash-native watchdog. Never silently proceeds with NO
343
478
  # enforcement at all — that would trade "wrong binary name" for "no timeout, ever", which is worse.
@@ -610,10 +745,17 @@ for r in $(seq 1 "$REPS"); do
610
745
  # NONE. An arm that legitimately needs a server (e.g. Playwright for a web target) gets it
611
746
  # explicitly via --mcp-config <file inside the clone>; nothing is inherited.
612
747
  MCPARGS=(--strict-mcp-config); [ -n "${MCPCFG:-}" ] && MCPARGS+=(--mcp-config "$MCPCFG") # bash 3.2 + set -u: expanded with the ${a[@]+"${a[@]}"} idiom below
748
+ if [ -n "$TURNS" ]; then
749
+ # §MULTI-TURN — the single-shot branch below is left byte-identical on purpose: `--turns`
750
+ # adds a path, it does not modify the one every existing probe already runs on.
751
+ fh_run_turns "$r"
752
+ rc=$?
753
+ else
613
754
  ( cd "$WORK" && fh_timeout "$TIMEOUT" claude -p "$PROMPT" \
614
755
  --model "$MODEL" "${TOOLS[@]}" ${MCPARGS[@]+"${MCPARGS[@]}"} \
615
756
  < /dev/null 2>"$OUTDIR/${ARM}_r${r}.stderr.txt" ) > "$OUTDIR/${ARM}_r${r}.txt"
616
757
  rc=$?
758
+ fi
617
759
  bytes=$(wc -c < "$OUTDIR/${ARM}_r${r}.txt" | tr -d ' ')
618
760
 
619
761
  # 🟥 An empty output is NOT a "no" answer. The first version of tonight's runner used
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env bash
2
+ # test_prless_delta_scan_lanes.sh — `scripts/prless_delta_scan.sh` 의 회귀 앵커.
3
+ #
4
+ # 🟥 **known-pair 가 이 레인의 존재 이유다.** 양성(진짜 PR 없는 델타) 하나만 있는 레인은
5
+ # «판별력» 을 증명하지 못한다 — 전부 고발하는 계기도 그 레인을 통과한다. 그래서 각 팔마다
6
+ # **반대 팔**을 같이 돌린다. 핵심 음성 컨트롤은 **squash 잔재**다: 이 레포는 squash 머지를
7
+ # 쓰므로 이미 착륙한 브랜치의 커밋 해시·per-commit patch-id 가 main 에 없고, 순진한 계기는
8
+ # 그것을 «미착륙» 으로 읽는다(2026-09-19 실측: naive 33/40 · git cherry 17/40 · 이 계기 10/40).
9
+ #
10
+ # 레인은 **합성 레포**를 짓는다 — 라이브 레포를 sim 대상으로 쓰지 않는다.
11
+ #
12
+ # 실행: bash scripts/test_prless_delta_scan_lanes.sh
13
+ set -uo pipefail
14
+
15
+ HERE="$(cd "$(dirname "$0")" && pwd)"
16
+ SCAN="$HERE/prless_delta_scan.sh"
17
+ [ -f "$SCAN" ] || { echo "❌ HARNESS-ERROR: $SCAN 없음 — 레인이 대상을 못 찾았다"; exit 2; }
18
+
19
+ PASS=0; FAIL=0
20
+ ok(){ echo "✅ $1"; PASS=$((PASS+1)); }
21
+ no(){ echo "❌ $1"; FAIL=$((FAIL+1)); }
22
+
23
+ WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
24
+
25
+ # ── 합성 레포 ────────────────────────────────────────────────────────────────
26
+ # main: c0 -- c1 -- SQUASH(b_squash 합본) -- c2
27
+ # b_ff: c0 -- c1 (main 의 조상 → NO_DELTA)
28
+ # b_squash: c1 -- s1 -- s2 (합본이 main 에 squash 로 들어감)
29
+ # b_uniq*: c1 -- u (고유 델타, PR 상태만 다름)
30
+ R="$WORK/repo"
31
+ mkdir -p "$R"; cd "$R"
32
+ git init -q -b main .
33
+ git config user.email lane@example.com; git config user.name lane
34
+ git config commit.gpgsign false
35
+ echo base > base.txt; git add base.txt; git commit -qm c0
36
+ echo one > one.txt; git add one.txt; git commit -qm c1
37
+ C1=$(git rev-parse HEAD)
38
+ git branch b_ff "$C1"
39
+
40
+ # squash 팔: 두 커밋짜리 브랜치를 만든 뒤, 그 «합본» 을 main 에 한 커밋으로 심는다
41
+ git switch -q -c b_squash "$C1"
42
+ printf 'alpha\n' > sq.txt; git add sq.txt; git commit -qm s1
43
+ printf 'alpha\nbeta\n' > sq.txt; git add sq.txt; git commit -qm s2
44
+ git switch -q main
45
+ git checkout -q b_squash -- sq.txt; git add sq.txt; git commit -qm "squash: b_squash (#100)"
46
+
47
+ # 고유 델타 팔 — 내용은 같고 PR 상태만 다르게 붙인다
48
+ for n in nopr open closed merged; do
49
+ git switch -q -c "b_$n" "$C1"
50
+ echo "unique-$n" > "uniq_$n.txt"; git add "uniq_$n.txt"; git commit -qm "u_$n"
51
+ done
52
+ git switch -q main
53
+ echo two > two.txt; git add two.txt; git commit -qm c2
54
+ # origin/main 을 로컬 ref 로 흉내 (scan 의 기본 base 를 --base 로 갈음)
55
+ git update-ref refs/remotes/origin/main "$(git rev-parse main)"
56
+ git branch -D main >/dev/null 2>&1 || true # main 로컬 브랜치는 제외 대상이므로 지워도 무방하나…
57
+ git switch -q --detach refs/remotes/origin/main
58
+
59
+ PRJ="$WORK/prs.json"
60
+ cat > "$PRJ" <<'JSON'
61
+ [{"number":100,"state":"MERGED","headRefName":"b_squash"},
62
+ {"number":101,"state":"OPEN","headRefName":"b_open"},
63
+ {"number":102,"state":"CLOSED","headRefName":"b_closed"},
64
+ {"number":103,"state":"MERGED","headRefName":"b_merged"}]
65
+ JSON
66
+
67
+ run(){ PRLESS_REPO="$R" PRLESS_PR_JSON="$PRJ" bash "$SCAN" "$@" 2>&1; }
68
+ verdict_of(){ echo "$1" | awk -v b="$2" '$0 ~ ("(^|[^a-z_])" b "([ ]|$)") {for(i=1;i<=NF;i++) if($i ~ /^(NO_DELTA|SQUASH_IN_BASE|COMMITS_IN_BASE|DELTA_NO_PR|DELTA_PR_OPEN|DELTA_PR_CLOSED|DELTA_AFTER_MERGED_PR|PATCHID_UNAVAILABLE|UNRELATED_HISTORY)$/) print $i}' | head -1; }
69
+
70
+ OUT=$(run); RC=$?
71
+ echo "--- scan output ---"; echo "$OUT"; echo "--- rc=$RC ---"; echo
72
+
73
+ # ── L1 양성: PR 이 없는 고유 델타 ──────────────────────────────────────────────
74
+ [ "$(verdict_of "$OUT" b_nopr)" = "DELTA_NO_PR" ] \
75
+ && ok "L1 POSITIVE b_nopr → DELTA_NO_PR" || no "L1 POSITIVE b_nopr → '$(verdict_of "$OUT" b_nopr)' (기대 DELTA_NO_PR)"
76
+
77
+ # ── L2 음성 컨트롤(핵심): squash 잔재를 고유 델타로 읽지 않는다 ────────────────
78
+ V2=$(verdict_of "$OUT" b_squash)
79
+ [ "$V2" = "SQUASH_IN_BASE" ] \
80
+ && ok "L2 NEGATIVE b_squash → SQUASH_IN_BASE (판별력 성립)" || no "L2 NEGATIVE b_squash → '$V2' (기대 SQUASH_IN_BASE) — 판별력 없음"
81
+
82
+ # ── L2-b 컨트롤의 컨트롤: 순진한 계기는 이 팔에서 실제로 «틀린다» ──────────────
83
+ # 이 줄이 없으면 L2 는 «원래 안 걸리는 것이 안 걸렸다» 와 구분되지 않는다(죽은 컨트롤).
84
+ NAIVE=$(cd "$R" && git cherry refs/remotes/origin/main b_squash 2>/dev/null | /usr/bin/grep -c '^+')
85
+ [ "${NAIVE:-0}" -gt 0 ] \
86
+ && ok "L2-b KNOWN-POSITIVE-FOR-THE-NAIVE git cherry 가 b_squash 를 $NAIVE 커밋 미착륙으로 «틀리게» 본다" \
87
+ || no "L2-b 죽은 컨트롤 — git cherry 도 b_squash 를 안 건드린다(픽스처가 이 결함을 안 담았다)"
88
+
89
+ # ── L3 음성: main 의 조상 ────────────────────────────────────────────────────
90
+ [ "$(verdict_of "$OUT" b_ff)" = "NO_DELTA" ] \
91
+ && ok "L3 NEGATIVE b_ff → NO_DELTA" || no "L3 NEGATIVE b_ff → '$(verdict_of "$OUT" b_ff)'"
92
+
93
+ # ── L4~L6 PR 상태별 분기 ────────────────────────────────────────────────────
94
+ [ "$(verdict_of "$OUT" b_open)" = "DELTA_PR_OPEN" ] && ok "L4 b_open → DELTA_PR_OPEN (①-b 관할, 발견 아님)" || no "L4 b_open → '$(verdict_of "$OUT" b_open)'"
95
+ [ "$(verdict_of "$OUT" b_closed)" = "DELTA_PR_CLOSED" ] && ok "L5 b_closed → DELTA_PR_CLOSED" || no "L5 b_closed → '$(verdict_of "$OUT" b_closed)'"
96
+ [ "$(verdict_of "$OUT" b_merged)" = "DELTA_AFTER_MERGED_PR" ] && ok "L6 b_merged → DELTA_AFTER_MERGED_PR (부분 머지)" || no "L6 b_merged → '$(verdict_of "$OUT" b_merged)'"
97
+
98
+ # ── L7 advisory: 발견이 있어도 rc=1 이지 차단(≥2)이 아니다 ────────────────────
99
+ [ "$RC" -eq 1 ] && ok "L7 ADVISORY 발견 있음 → rc=1 (차단 아님)" || no "L7 ADVISORY rc=$RC (기대 1)"
100
+
101
+ # ── L8 부재 ≠ 0: PR 출처가 없으면 UNMEASURED(rc=2), «깨끗함» 아니다 ───────────
102
+ O8=$(PRLESS_REPO="$R" PATH=/usr/bin:/bin bash "$SCAN" 2>&1); R8=$?
103
+ if [ "$R8" -eq 2 ] && echo "$O8" | /usr/bin/grep -q 'UNMEASURED'; then
104
+ ok "L8 UNMEASURED gh 부재 → rc=2 + UNMEASURED (0 으로 안 접는다)"
105
+ else
106
+ no "L8 UNMEASURED gh 부재 → rc=$R8 / '$O8'"
107
+ fi
108
+
109
+ # ── L9 깨진 PR JSON 도 «PR 0건» 이 아니다 ────────────────────────────────────
110
+ echo 'not json' > "$WORK/bad.json"
111
+ O9=$(PRLESS_REPO="$R" PRLESS_PR_JSON="$WORK/bad.json" bash "$SCAN" 2>&1); R9=$?
112
+ [ "$R9" -eq 2 ] && ok "L9 깨진 PR JSON → rc=2 UNMEASURED" || no "L9 깨진 PR JSON → rc=$R9 (기대 2 — «PR 0건» 으로 읽으면 전부 오탐)"
113
+
114
+ # ── L10 읽기 전용: 스캔이 레포 상태를 바꾸지 않는다 ───────────────────────────
115
+ S_BEFORE=$(cd "$R" && git rev-parse HEAD; git for-each-ref --format='%(refname) %(objectname)' | sort; git status --porcelain)
116
+ run >/dev/null 2>&1
117
+ S_AFTER=$(cd "$R" && git rev-parse HEAD; git for-each-ref --format='%(refname) %(objectname)' | sort; git status --porcelain)
118
+ [ "$S_BEFORE" = "$S_AFTER" ] && ok "L10 READ-ONLY ref·HEAD·워킹트리 무변경" || no "L10 READ-ONLY 스캔이 레포 상태를 바꿨다"
119
+
120
+ # ── L11 되돌림 프로브: squash 판별을 «빼면» 정확히 L2 만 적색이 되나 ───────────
121
+ # 3단 — 적용확인 → 실행 → 복원. 적용을 확인 안 하면 «안 바뀐 파일로 통과» 를 초록으로 읽는다.
122
+ MUT="$WORK/mutant.sh"
123
+ sed 's#^ elif grep -qxF "$pid" "$PIDMAP" 2>/dev/null; then# elif false; then#' "$SCAN" > "$MUT"
124
+ if ! /usr/bin/grep -q 'elif false; then' "$MUT"; then
125
+ no "L11 REVERT-PROBE HARNESS-ERROR — 뮤턴트가 안 만들어졌다(앵커 줄이 바뀌었나). 이 결과는 증거가 아니다"
126
+ else
127
+ OM=$(PRLESS_REPO="$R" PRLESS_PR_JSON="$PRJ" bash "$MUT" 2>&1)
128
+ VM_SQ=$(verdict_of "$OM" b_squash); VM_FF=$(verdict_of "$OM" b_ff); VM_NP=$(verdict_of "$OM" b_nopr)
129
+ if [ "$VM_SQ" != "SQUASH_IN_BASE" ] && [ "$VM_FF" = "NO_DELTA" ] && [ "$VM_NP" = "DELTA_NO_PR" ]; then
130
+ ok "L11 REVERT-PROBE 판별 줄을 빼면 b_squash 만 뒤집힌다 ('$VM_SQ') · b_ff·b_nopr 불변 → 앵커가 장식이 아니다"
131
+ else
132
+ no "L11 REVERT-PROBE b_squash='$VM_SQ' b_ff='$VM_FF' b_nopr='$VM_NP' — 앵커가 그 줄에 안 묶여 있다"
133
+ fi
134
+ fi
135
+
136
+ # ── L12 detached HEAD 를 «브랜치» 로 읽지 않는다 ──────────────────────────────
137
+ # 이 픽스처는 detached HEAD 에서 돈다(위 setup 이 origin/main 으로 detach 한다).
138
+ # `git branch` 는 그 상태에서 `(HEAD detached at …)` 를 한 줄 뱉고, 그것을 ref 로 읽으면
139
+ # merge-base 가 안 잡혀 **가짜 UNRELATED_HISTORY 발견**이 나간다. 계기가 자기 사각을 만든 자리.
140
+ if echo "$OUT" | /usr/bin/grep -q 'HEAD detached'; then
141
+ no "L12 detached HEAD 의사항목이 브랜치로 집계됐다 — 가짜 발견"
142
+ else
143
+ DET=$(cd "$R" && git rev-parse --abbrev-ref HEAD)
144
+ if [ "$DET" = "HEAD" ]; then
145
+ ok "L12 detached HEAD 에서 돌았고(컨트롤 확인: abbrev-ref=HEAD) 의사항목이 집계 안 됨"
146
+ else
147
+ no "L12 죽은 컨트롤 — 픽스처가 detached 상태가 아니다(abbrev-ref=$DET). 이 레인은 아무것도 안 쟀다"
148
+ fi
149
+ fi
150
+
151
+ echo
152
+ echo "── PASS=$PASS FAIL=$FAIL ──"
153
+ [ "$FAIL" -eq 0 ] || exit 1
154
+ exit 0