@chrono-meta/fh-gate 3.12.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,214 @@
1
+ #!/usr/bin/env bash
2
+ # test_outbound_pr_gate_lanes.sh — known pairs for scripts/outbound_pr_gate.sh.
3
+ #
4
+ # Both directions on every axis: the applicability test (owned vs non-owned), the record test
5
+ # (strong rung vs weak rung, present vs absent, grounded vs vacuous), and the delivery test
6
+ # (deny = exit 2, advisory = exit 0 with output, silent = exit 0 with none).
7
+ # L8 is the CLASS-CLOSING arm: it reads the `standpoint:` closed enum out of
8
+ # templates/.git-hooks/pre-commit and fails if the gate classifies neither strong nor weak — so a
9
+ # new enum member cannot be added without deciding what it means on the outbound surface.
10
+ # L9 is the REVERT probe: neuter the strong-rung allow-list and L1 must go red.
11
+ set -uo pipefail
12
+ HERE="$(cd "$(dirname "$0")" && pwd)"
13
+ REPO="$(cd "$HERE/.." && pwd)"
14
+ GATE="$HERE/outbound_pr_gate.sh"
15
+ PRECOMMIT="${FH_PRECOMMIT_FILE:-$REPO/templates/.git-hooks/pre-commit}"
16
+ fail=0; n=0
17
+ TMP=$(mktemp -d) || { echo "FAIL mktemp"; exit 1; }
18
+ trap 'rm -rf "$TMP"' EXIT
19
+
20
+ # ── fixture world ─────────────────────────────────────────────────────────────────────────────
21
+ FHROOT="$TMP/fh"; mkdir -p "$FHROOT/scripts" "$FHROOT/tracks/_meta"
22
+ : > "$FHROOT/scripts/session_close_check.sh" # the applicability anchor
23
+ git init -q "$FHROOT" 2>/dev/null
24
+ git -C "$FHROOT" remote add origin https://github.com/ownerco/forge-harness.git 2>/dev/null
25
+ mkfork() { # $1 = dir, $2 = origin spec, $3 = upstream spec (empty = none)
26
+ mkdir -p "$1"; git init -q "$1" 2>/dev/null
27
+ git -C "$1" remote add origin "https://github.com/$2.git" 2>/dev/null
28
+ [ -n "${3:-}" ] && git -C "$1" remote add upstream "https://github.com/$3.git" 2>/dev/null
29
+ return 0
30
+ }
31
+ mkfork "$TMP/foreignfork" "ownerco/archify" "tt-a1i/archify" # fork of a repo we do NOT own
32
+ mkfork "$TMP/ourclone" "ownerco/forge-harness" "" # our own repo, no fork parent
33
+ mkfork "$TMP/directclone" "someoneelse/tool" "" # DIRECT clone of a foreign repo
34
+
35
+ TODAY="2026-01-01"
36
+ rec() { # $1 = standpoint value, $2 = generated-path, $3 = fixture-carries ("" = omit the line)
37
+ rm -f "$FHROOT/tracks/_meta"/outbound_pr_*.md
38
+ local f="$FHROOT/tracks/_meta/outbound_pr_${TODAY}_fixture.md"
39
+ : > "$f"
40
+ [ -n "${1:-}" ] && printf 'standpoint: %s\n' "$1" >> "$f"
41
+ [ -n "${2:-}" ] && printf 'generated-path: %s\n' "$2" >> "$f"
42
+ [ -n "${3:-}" ] && printf 'fixture-carries: %s\n' "$3" >> "$f"
43
+ return 0
44
+ }
45
+ FULL_SP='tier2(archify) — ran `node scripts/export.mjs` there, output: wrote 3 files, input intact'
46
+ FULL_GP='none-found(grepped package.json scripts and every *.mjs for a writer of that path)'
47
+ FULL_AR='asserted(`node t.mjs` with dest symlinked to the input, output: input bytes unchanged)'
48
+
49
+ run() { # $1 = label, $2 = expected verdict deny|advisory|silent, $3 = command string, $4 = cwd
50
+ n=$((n+1))
51
+ local out rc
52
+ out=$(printf '{"tool_name":"Bash","cwd":"%s","tool_input":{"command":"%s"}}' "${4:-}" "$3" \
53
+ | CLAUDE_PROJECT_DIR="$FHROOT" FH_OUTBOUND_TODAY="$TODAY" \
54
+ FH_OUTBOUND_RECDIR="$FHROOT/tracks/_meta" bash "$GATE" 2>&1); rc=$?
55
+ local got="silent"
56
+ [ "$rc" -eq 2 ] && got="deny"
57
+ [ "$rc" -eq 0 ] && [ -n "$out" ] && got="advisory"
58
+ if [ "$got" = "$2" ]; then
59
+ echo "PASS $1 ($got)"
60
+ else
61
+ echo "FAIL $1: expected $2, got $got (rc=$rc)"
62
+ printf '%s\n' "$out" | sed 's/^/ /' | head -6
63
+ fail=1
64
+ fi
65
+ }
66
+
67
+ # ── L1 known-POSITIVE: non-owned target, weak rung -> deny ────────────────────────────────────
68
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
69
+ run "L1 non-owned + standpoint tier1b" deny "gh pr create -R tt-a1i/archify --title x"
70
+
71
+ # ── L2 known-NEGATIVE: same target, full record -> silent ─────────────────────────────────────
72
+ rec "$FULL_SP" "$FULL_GP" "$FULL_AR"
73
+ run "L2 non-owned + full record" silent "gh pr create -R tt-a1i/archify --title x"
74
+
75
+ # ── L3 our own repo: never blocked, record or not ─────────────────────────────────────────────
76
+ rec "" "" ""
77
+ run "L3 owned target, no record" silent "gh pr create -R ownerco/forge-harness --title x"
78
+
79
+ # ── L4 applicability undetermined -> advisory, NEVER deny ─────────────────────────────────────
80
+ rec "" "" ""
81
+ run "L4 bare gh pr create, no cwd" advisory "gh pr create --title x"
82
+
83
+ # ── L5 not the outbound act ───────────────────────────────────────────────────────────────────
84
+ run "L5 unrelated command" silent "gh pr list --state open"
85
+ run "L5b gh pr merge is not create" silent "gh pr merge 12 --squash"
86
+
87
+ # ── L6 record absent entirely on a non-owned target ───────────────────────────────────────────
88
+ rec "" "" ""
89
+ run "L6 non-owned + no record at all" deny "gh pr create -R tt-a1i/archify --title x"
90
+
91
+ # ── L7 vacuous grounds ────────────────────────────────────────────────────────────────────────
92
+ rec "$FULL_SP" 'none-found()' "$FULL_AR"
93
+ run "L7 generated-path with empty grounds" deny "gh pr create -R tt-a1i/archify --title x"
94
+ rec 'tier2(archify) — looked' "$FULL_GP" "$FULL_AR"
95
+ run "L7b standpoint tier2 naming no execution" deny "gh pr create -R tt-a1i/archify --title x"
96
+
97
+ # ── L10 DEGRADED_NOT_RUN is an honest record AND a not-ready verdict ──────────────────────────
98
+ rec "$FULL_SP" "$FULL_GP" 'DEGRADED_NOT_RUN(no local chromium on this machine, nothing was run)'
99
+ run "L10 fixture-carries DEGRADED_NOT_RUN" deny "gh pr create -R tt-a1i/archify --title x"
100
+
101
+ # ── L10b spelling C (composition / first-match-only) is an accepted answer on the SAME field ──
102
+ # Rationale for folding rather than adding a 4th field is in the gate header. This lane pins that
103
+ # the C answer clears the gate, so the folding is real and not just documentation.
104
+ rec "$FULL_SP" "$FULL_GP" 'asserted(`node t.mjs "npm publish --dry-run && rm -rf /"` — 2 effective decisions, first excepted; saw hold:false, expected hold:true)'
105
+ run "L10b fixture-carries answered with spelling C" silent "gh pr create -R tt-a1i/archify --title x"
106
+
107
+ # ── L11 fork detection, both directions, via cwd (no -R in the command) ───────────────────────
108
+ rec 'tier1b(archify) — read only' "$FULL_GP" "$FULL_AR"
109
+ run "L11a cwd is a fork of a foreign repo" deny "gh pr create --title x" "$TMP/foreignfork"
110
+ run "L11b cwd is our own clone" silent "gh pr create --title x" "$TMP/ourclone"
111
+ run "L11c cwd is a DIRECT clone of a foreign repo" deny "gh pr create --title x" "$TMP/directclone"
112
+
113
+ # ── L12 override is acknowledged, recorded in the command, and does not satisfy ───────────────
114
+ rec "" "" ""
115
+ run "L12 FH_OUTBOUND_PR_OK=1 in the command" advisory "FH_OUTBOUND_PR_OK=1 gh pr create -R tt-a1i/archify --title x"
116
+
117
+ # ── L13 not an FH checkout -> silent, and we create nothing there ─────────────────────────────
118
+ n=$((n+1))
119
+ _out=$(printf '{"tool_name":"Bash","tool_input":{"command":"gh pr create -R tt-a1i/archify"}}' \
120
+ | CLAUDE_PROJECT_DIR="$TMP/notfh" FH_OUTBOUND_ANCHOR="$TMP/notfh/nope" bash "$GATE" 2>&1); _rc=$?
121
+ if [ "$_rc" -eq 0 ] && [ -z "$_out" ]; then echo "PASS L13 non-FH checkout is silent"
122
+ else echo "FAIL L13 non-FH checkout: rc=$_rc out='$_out'"; fail=1; fi
123
+
124
+ # ── L8 CLASS-CLOSING: every standpoint: enum member must be classified by this gate ───────────
125
+ n=$((n+1))
126
+ # Scope the read to validate_standpoint_leg()'s own body first — an unscoped grep for the enum
127
+ # text picked up three unrelated lines elsewhere in the hook and reported them as members
128
+ # (first run of this lane, 2026-09-18: the instrument had to be calibrated before it measured).
129
+ ENUM=$(awk '/^validate_standpoint_leg\(\)/{f=1} f&&/^}/{f=0} f' "$PRECOMMIT" 2>/dev/null \
130
+ | awk '/Closed enum:/{print; getline; print}' \
131
+ | tr '·' '\n' | sed -E 's/^[[:space:]]*echo[[:space:]]+"//; s/.*Closed enum:[[:space:]]*//; s/\(<h>\)//g; s/[^A-Za-z0-9_-]//g' \
132
+ | grep -E '^[A-Za-z]' | sort -u)
133
+ if [ -z "$ENUM" ]; then
134
+ echo "FAIL L8 INSTRUMENT ERROR — could not extract the standpoint enum from $PRECOMMIT"
135
+ fail=1
136
+ else
137
+ DECLARED=$( { grep -m1 '^STRONG_RUNGS=' "$GATE"; grep -m1 '^WEAK_RUNGS=' "$GATE"; } \
138
+ | sed -E 's/^[A-Z_]+="//; s/"$//' | tr ' ' '\n' | grep -E '^[A-Za-z]' | sort -u)
139
+ missing=$(comm -23 <(printf '%s\n' "$ENUM") <(printf '%s\n' "$DECLARED"))
140
+ if [ -n "$missing" ]; then
141
+ echo "FAIL L8 standpoint enum member(s) unclassified by outbound_pr_gate.sh:"
142
+ printf '%s\n' "$missing" | sed 's/^/ /'
143
+ echo " Classify each as STRONG_RUNGS (clears the outbound gate) or WEAK_RUNGS (blocks it)."
144
+ fail=1
145
+ else
146
+ echo "PASS L8 class-closing: all $(printf '%s\n' "$ENUM" | wc -l | tr -d ' ') enum members classified"
147
+ fi
148
+ fi
149
+
150
+ # ── L8b known-POSITIVE for the class-closing arm: add a member, L8's comparison must name it ──
151
+ n=$((n+1))
152
+ FAKEPC="$TMP/pre-commit-with-new-member"
153
+ sed -E 's/(Closed enum: tier1 )/\1· tier4(<h>) /' "$PRECOMMIT" > "$FAKEPC" 2>/dev/null
154
+ ENUM2=$(awk '/^validate_standpoint_leg\(\)/{f=1} f&&/^}/{f=0} f' "$FAKEPC" 2>/dev/null \
155
+ | awk '/Closed enum:/{print; getline; print}' \
156
+ | tr '·' '\n' | sed -E 's/^[[:space:]]*echo[[:space:]]+"//; s/.*Closed enum:[[:space:]]*//; s/\(<h>\)//g; s/[^A-Za-z0-9_-]//g' \
157
+ | grep -E '^[A-Za-z]' | sort -u)
158
+ DECLARED2=$( { grep -m1 '^STRONG_RUNGS=' "$GATE"; grep -m1 '^WEAK_RUNGS=' "$GATE"; } \
159
+ | sed -E 's/^[A-Z_]+="//; s/"$//' | tr ' ' '\n' | grep -E '^[A-Za-z]' | sort -u)
160
+ if printf '%s\n' "$(comm -23 <(printf '%s\n' "$ENUM2") <(printf '%s\n' "$DECLARED2"))" | grep -qx 'tier4'; then
161
+ echo "PASS L8b class-closing arm goes RED when an enum member is added"
162
+ else
163
+ echo "FAIL L8b class-closing arm did NOT notice an added enum member — L8 green means nothing"
164
+ fail=1
165
+ fi
166
+
167
+ # ── L9 REVERT PROBE: neuter the allow-list; L1 must go red ────────────────────────────────────
168
+ n=$((n+1))
169
+ MUT="$TMP/mutant.sh"
170
+ sed -E 's/^([[:space:]]*)tier2\\\(\*\\\)\|tier2b\\\(\*\\\)\|tier3\\\(\*\\\)\)/\1*)/' "$GATE" > "$MUT"
171
+ if ! grep -qE '^[[:space:]]*\*\)$' "$MUT"; then
172
+ echo "FAIL L9 INSTRUMENT ERROR — the mutation did not apply; the probe would pass vacuously"
173
+ fail=1
174
+ else
175
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
176
+ _o=$(printf '{"tool_name":"Bash","tool_input":{"command":"gh pr create -R tt-a1i/archify"}}' \
177
+ | CLAUDE_PROJECT_DIR="$FHROOT" FH_OUTBOUND_TODAY="$TODAY" \
178
+ FH_OUTBOUND_RECDIR="$FHROOT/tracks/_meta" bash "$MUT" 2>&1); _r=$?
179
+ if [ "$_r" -eq 2 ]; then
180
+ echo "FAIL L9 revert probe: the neutered allow-list STILL denied — L1 is not anchored to it"
181
+ fail=1
182
+ else
183
+ echo "PASS L9 revert probe: neutering the allow-list turns L1's deny off (rc=$_r)"
184
+ fi
185
+ fi
186
+
187
+
188
+ # ── L14 트리거 형태 — cross-family(codex 2026-09-18)가 공격한 자리 ───────────────────────────
189
+ # 🟥 그 지적 7건 중 5건은 실측에서 **틀렸다**(`command gh`·`env X=1 gh`·`time gh`·`noglob gh`·
190
+ # 인용 repo 는 종전 식으로도 잡혔다). 아래 셋만 진짜였고, 앞의 둘을 수리로 닫았다.
191
+ # 이 레인들은 그 수리의 회귀 앵커다 — 정규식이 좁아지면 여기가 적색이 된다.
192
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
193
+ run "L14a 절대경로 gh 도 잡힌다" deny "/opt/homebrew/bin/gh pr create -R tt-a1i/archify --title x"
194
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
195
+ run "L14b 상대경로 ./gh 도 잡힌다" deny "./gh pr create -R tt-a1i/archify --title x"
196
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
197
+ run "L14c 인용 안쪽 sh -c 도 잡힌다" deny "sh -c 'gh pr create -R tt-a1i/archify --title x'"
198
+
199
+ # ── L15 구조적 잔여를 «핀» 으로 박는다 (커버리지 주장이 아니라 잔여 선언) ────────────────────
200
+ # 🟥 변수 간접은 정규식으로 닫히지 않는다. 이 레인은 그 사실을 **고정**한다 — 누가 「닫혔다」고
201
+ # 적으면 여기가 적색이 되어 거짓 주장을 막는다. silent 를 기대하는 것이 의도다.
202
+ rec 'tier1b(archify) — read their export path end to end' "$FULL_GP" "$FULL_AR"
203
+ # 🟥 `$GH_CMD` 는 **리터럴로 가야 한다** — 초판이 이중인용에 그대로 써서 레인 셸이 확장했고
204
+ # `set -u` 에서 그 자리에서 죽었다(L14 까지만 돌고 스위트 중단). 단일인용으로 고정한다.
205
+ run "L15 변수 간접은 NAMED GAP 이다 (silent 가 기대값)" silent 'GH_CMD=gh; $GH_CMD pr create -R tt-a1i/archify'
206
+
207
+ # ── L16 known-NEGATIVE: 넓힌 문자류가 관계없는 명령을 잡지 않는가 ─────────────────────────────
208
+ rec "$FULL_SP" "$FULL_GP" "$FULL_AR"
209
+ run "L16 gh pr edit 는 여전히 NAMED GAP" silent "gh pr edit --body x -R tt-a1i/archify"
210
+ rec "$FULL_SP" "$FULL_GP" "$FULL_AR"
211
+ run "L16b gh pr list 는 트리거 아님" silent "gh pr list -R tt-a1i/archify"
212
+
213
+ echo "── $n lanes, $( [ $fail -eq 0 ] && echo 'all green' || echo 'FAILURES above' ) ──"
214
+ exit $fail