@chrono-meta/fh-gate 3.27.0 → 3.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/CLAUDE.md +2 -2
  3. package/README.ja.md +2 -4
  4. package/README.ko.md +2 -4
  5. package/README.md +19 -19
  6. package/README.zh.md +2 -4
  7. package/knowledge/shared/harness-core/fh_module_contract.md +97 -0
  8. package/knowledge/shared/learnings/subagent_invocations_log.yaml +81 -0
  9. package/package.json +10 -1
  10. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  11. package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +84 -4
  12. package/plugins/fh-commons/skills/ko-tech-writer/fh-module.yaml +19 -0
  13. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_negative.md +73 -1
  14. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_positive.md +39 -1
  15. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/known_unclosed.md +6 -0
  16. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/CHANGELOG.md +10 -0
  18. package/plugins/fh-meta/skills/frontier-digest/SKILL.md +14 -10
  19. package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +17 -1
  20. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  21. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  22. package/scripts/fh_module_check.py +686 -0
  23. package/scripts/fixtures/frontier_digest_recall.tsv +5 -0
  24. package/scripts/ko_tech_writer_calibrate.py +288 -15
  25. package/scripts/probe_live_eval.sh +19 -1
  26. package/scripts/probe_live_eval_lib.py +174 -5
  27. package/scripts/resident_cost.py +1 -1
  28. package/scripts/selfcheck.sh +7 -1
  29. package/scripts/session_checklist.py +66 -0
  30. package/scripts/session_close_check.sh +44 -0
  31. package/scripts/sim_isolated_run.sh +31 -0
  32. package/scripts/test_claude_md_size_lanes.sh +22 -7
  33. package/scripts/test_fh_module_check_lanes.sh +581 -0
  34. package/scripts/test_frontier_digest_recall.sh +26 -0
  35. package/scripts/test_frontier_digest_recall_negctl.sh +15 -0
  36. package/scripts/test_ko_tech_writer_lanes.sh +1 -1
  37. package/scripts/test_probe_live_eval_lanes.sh +116 -0
  38. package/scripts/test_resident_cost_lanes.sh +1 -1
  39. package/scripts/test_session_checklist_lanes.sh +29 -0
  40. package/scripts/test_sim_isolated_run_lanes.sh +51 -0
  41. package/scripts/test_utterance_checklist_hook_lanes.sh +175 -0
  42. package/scripts/utterance_checklist_hook.py +193 -0
  43. package/scripts/utterance_checklist_hook.sh +31 -0
@@ -723,6 +723,122 @@ _lane EV8 evidence "control — the LIVE evidence dir was not written by these l
723
723
  "$LIVE_EV_BEFORE" "$([ -d "$LIVE_EV" ] && find "$LIVE_EV" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ' || echo ABSENT)"
724
724
 
725
725
  fi
726
+ echo ""
727
+ echo "── budget line + --target split (2026-10-17) ─────────────────────"
728
+ # WHY. A FAIL that ended at a harness cap (timeout) reads identically to a real FAIL, and one pooled
729
+ # pass_rate cannot say whether a repair fixed its target or moved everything. These lanes pin that
730
+ # every row carries the cap and ended_at_cap (three-valued: a missing record is UNKNOWN, never no),
731
+ # and that --target splits the summary while the default output is untouched.
732
+ _budget() { # $1=ended value for primary_r1 meta, or MISSING -> "ended_at_cap|budget"
733
+ python3 - "$REPO_ROOT" "$1" <<'PY'
734
+ import sys, os, tempfile
735
+ sys.path.insert(0, os.path.join(sys.argv[1], 'scripts'))
736
+ from probe_live_eval_lib import score_run
737
+ root = tempfile.mkdtemp(); base = os.path.join(root, 'G-X'); os.makedirs(base)
738
+ open(os.path.join(base, 'primary_r1.txt'), 'w').write('nothing')
739
+ open(os.path.join(base, 'control_r1.txt'), 'w').write('weather')
740
+ for arm in ('primary', 'control'):
741
+ if sys.argv[2] == 'MISSING':
742
+ continue
743
+ if sys.argv[2] == 'PARTIAL' and arm == 'primary':
744
+ continue # transcript present, meta absent: ran but unmeasured
745
+ end = sys.argv[2] if arm == 'primary' else 'no'
746
+ open(os.path.join(base, arm + '_r1.meta.tsv'), 'w').write(
747
+ 'rc\t0\ntimeout_s\t900\nmax_turns\tunset\ntoken_cap\tunset\nended_at_cap\t%s\n' % end)
748
+ r = score_run([{'id': 'G-X', 'polarity': 'present', 'expect_re': 'ZZZ'}], root, ['G-X'], 0.8, 'sonnet')['rows'][0]
749
+ print('%s|%s|%s' % (r['verdict'], r['ended_at_cap'], r['budget']))
750
+ PY
751
+ }
752
+ r="$(_budget yes)"
753
+ _lane BU1 budget "KNOWN-POSITIVE — a FAIL whose primary episode ended at the cap says so" \
754
+ "FAIL|yes|timeout=900s max_turns=unset tokens=unset ended_at_cap=yes (1/2 episodes)" "$r"
755
+ r="$(_budget no)"
756
+ _lane BU2 budget "KNOWN-NEGATIVE — a FAIL that ended on its own says ended_at_cap=no" \
757
+ "FAIL|no|timeout=900s max_turns=unset tokens=unset ended_at_cap=no" "$r"
758
+ r="$(_budget MISSING)"
759
+ _lane BU3 budget "no meta recorded -> UNKNOWN (not measured is not no)" \
760
+ "FAIL|UNKNOWN|no episode meta (cap not recorded)" "$r"
761
+ # BU5 (review B1): one episode's meta missing while its transcript exists must not let the other
762
+ # episode's `no` stand for the row — before the fix this printed `...|no|...`.
763
+ r="$(_budget PARTIAL)"
764
+ _lane BU5 budget "partial meta (transcript without meta) -> UNKNOWN, not the other episode's no" \
765
+ "FAIL|UNKNOWN|timeout=900s max_turns=unset tokens=unset ended_at_cap=UNKNOWN" "$r"
766
+
767
+ # BU4/TG*: end to end through the runner with a stub sim that writes the meta the real runner writes.
768
+ if [ "$NOPROBES" -eq 1 ]; then _skipblock "budget/target runner lanes BU4 TG3-TG5 (need probes.md)"; else
769
+ BSTUB="$T/bud_stub"; mkdir -p "$BSTUB"
770
+ cat > "$BSTUB/fake_sim_budget.sh" <<'FAKEBUD'
771
+ #!/usr/bin/env bash
772
+ arm=""; out=""
773
+ while [ $# -gt 0 ]; do case "$1" in --arm) arm="$2"; shift 2 ;; --out) out="$2"; shift 2 ;; *) shift ;; esac; done
774
+ mkdir -p "$out"
775
+ printf 'stub body %s\n' "$arm" > "$out/${arm}_r1.txt"
776
+ if [ "${FH_BUD_STUB_CAP:-no}" = yes ]; then rc=124; end=yes; else rc=0; end=no; fi
777
+ printf 'rc\t%s\ntimeout_s\t900\nmax_turns\tunset\ntoken_cap\tunset\nended_at_cap\t%s\n' "$rc" "$end" > "$out/${arm}_r1.meta.tsv"
778
+ echo "RESULT: CLEAN"; exit 0
779
+ FAKEBUD
780
+ chmod +x "$BSTUB/fake_sim_budget.sh"
781
+ ( cd "$REPO_ROOT" && FH_SIM_RUNNER_BIN="$BSTUB/fake_sim_budget.sh" FH_BUD_STUB_CAP=yes \
782
+ bash "$RUNNER" --ids "G-GREET-01" --no-evidence --report-out "$T/bud_report.md" ) >"$T/bud.log" 2>&1
783
+ _lane BU4 budget "runner -> report row carries 'ended_at_cap=yes' when the stub hit its cap" \
784
+ "yes" "$(grep -E '^\| G-GREET-01 ' "$T/bud_report.md" | grep -q 'ended_at_cap=yes' && echo yes || echo no)"
785
+
786
+ # TG3 default output unchanged: no --target -> no split section anywhere.
787
+ _lane TG3 target "default (no --target): report has no 'Target split' section" \
788
+ "no" "$(grep -q 'Target split' "$T/bud_report.md" && echo yes || echo no)"
789
+
790
+ # TG4 a --target that is not in the run is refused BEFORE any live call (stub counter stays empty).
791
+ TGCOUNT="$T/tg_counter"; : > "$TGCOUNT"
792
+ ( cd "$REPO_ROOT" && FH_SIM_RUNNER_BIN="$STUBROOT/fake_sim_ok.sh" FH_FAKESIM_COUNTER="$TGCOUNT" \
793
+ bash "$RUNNER" --ids "G-GREET-01" --target NOT-A-PROBE --no-evidence --report-out "$T/tg4.md" ) >/dev/null 2>&1
794
+ tg4_rc=$?
795
+ _lane TG4 target "unknown --target -> rc=2 and zero runner calls" "2/0" "$tg4_rc/$(wc -l < "$TGCOUNT" | tr -d ' ')"
796
+
797
+ # TG5 --target + --before through the runner: section present, before side filled in.
798
+ cat > "$T/prev.md" <<'PREV'
799
+ ## Run — model=sonnet threshold=0.80
800
+
801
+ | Probe | Verdict | reps(pass/ran) | primary_hit | control_hit | polarity | Reason |
802
+ |---|---|---|---|---|---|---|
803
+ | G-GREET-01 | FAIL | 0/1 | False | False | present | |
804
+ PREV
805
+ ( cd "$REPO_ROOT" && FH_SIM_RUNNER_BIN="$BSTUB/fake_sim_budget.sh" \
806
+ bash "$RUNNER" --ids "G-GREET-01,G-TRIG-07" --target G-GREET-01 --before "$T/prev.md" \
807
+ --no-evidence --report-out "$T/tg5.md" ) >"$T/tg5.log" 2>&1
808
+ _lane TG5 target "--target + --before: report has the split, target before=FAIL shown" \
809
+ "yes" "$(grep -q '^## Target split — G-GREET-01' "$T/tg5.md" && grep -q 'before=FAIL' "$T/tg5.md" && echo yes || echo no)"
810
+ fi
811
+
812
+ _target() { # $1=before verdicts "A:V,B:V,.." $2=after verdicts ; target=A -> prints summary tokens
813
+ python3 - "$REPO_ROOT" "$1" "$2" <<'PY'
814
+ import sys, os
815
+ sys.path.insert(0, os.path.join(sys.argv[1], 'scripts'))
816
+ from probe_live_eval_lib import split_by_target
817
+ parse = lambda s: dict(x.split(':') for x in s.split(','))
818
+ before, after = parse(sys.argv[2]), parse(sys.argv[3])
819
+ t = split_by_target([{'id': k, 'verdict': v, 'ended_at_cap': 'no'} for k, v in after.items()], 'A', before)
820
+ print('%s>%s | others %s>%s | moved=%s' % (t['before']['target'], t['after_target'],
821
+ t['before']['others']['passed'], t['after_others']['passed'], len(t['moved'])))
822
+ PY
823
+ }
824
+ r="$(_target 'A:FAIL,B:PASS,C:PASS' 'A:PASS,B:PASS,C:PASS')"
825
+ _lane TG1 target "target fixed, others untouched -> moved=0 (fixed the target, moved nothing else)" \
826
+ "FAIL>PASS | others 2>2 | moved=0" "$r"
827
+ r="$(_target 'A:FAIL,B:PASS,C:PASS' 'A:PASS,B:FAIL,C:PASS')"
828
+ _lane TG2 target "KNOWN-NEGATIVE pair — target fixed but a neighbour regressed -> moved=1, others 2>1" \
829
+ "FAIL>PASS | others 2>1 | moved=1" "$r"
830
+ # TG6 (review B4): a before-report that lacks the other probes must not render «others moved: none».
831
+ r="$(python3 - "$REPO_ROOT" <<'PY'
832
+ import sys, os
833
+ sys.path.insert(0, os.path.join(sys.argv[1], 'scripts'))
834
+ from probe_live_eval_lib import split_by_target, render_target_lines
835
+ t = split_by_target([{'id': k, 'verdict': 'PASS', 'ended_at_cap': 'no'} for k in 'ABC'], 'A', {'A': 'FAIL'})
836
+ print([l for l in render_target_lines(t) if 'others moved' in l][0].strip())
837
+ PY
838
+ )"
839
+ _lane TG6 target "narrower --before -> 'not comparable', never 'none'" \
840
+ "others moved: not comparable (2 others absent from before)" "$r"
841
+
726
842
  echo ""
727
843
  echo "── summary ──────────────────────────────────────────────────────"
728
844
  echo "lanes: $N failed: $([ "$FAIL" -eq 0 ] && echo 0 || echo '>=1')"
@@ -12,7 +12,7 @@
12
12
  # R8 합계 = 측정된 칸의 합(MEMORY 는 적재분)
13
13
  # R9 되돌림: nchars 를 바이트로 바꾼 변이체 → R1 이 빨개져야 한다(적용 확인 → 실행 → 판정)
14
14
  # R10 실물: 이 레포 CLAUDE.md 줄이 독립 계산(len)과 같은 값
15
- # CLAUDE.md 크기 «가드»(145,000 한계)는 scripts/test_claude_md_size_lanes.sh 가 맡는다 — 여기서 다시 안 잰다.
15
+ # CLAUDE.md 크기 «가드»(18,000 한계)는 scripts/test_claude_md_size_lanes.sh 가 맡는다 — 여기서 다시 안 잰다.
16
16
  set -uo pipefail
17
17
  HERE="$(cd "$(dirname "$0")" && pwd)"; ROOT="$(cd "$HERE/.." && pwd)"
18
18
  METER="${RESIDENT_COST_METER:-$HERE/resident_cost.py}" # R9 가 변이체를 넣을 때만 바뀐다
@@ -738,6 +738,35 @@ else
738
738
  fail "L39 rc=$RC (see $TMPDIR_ROOT/l39.out)"
739
739
  fi
740
740
 
741
+ # L40 — re-extracting into a filled sheet carries the judgements forward (2026-10-18: the mid-session nudge
742
+ # re-extracts into the SAME file; a plain overwrite erased 259 filled rows). Known pair: a filled row is carried,
743
+ # an empty row stays empty; a filled row whose utterance is gone is kept under the orphan heading; no file → plain write.
744
+ build_jsonl "$TMPDIR_ROOT/l40.jsonl" "[{'type':'user','timestamp':'2026-10-18T01:00:00.000Z','message':{'role':'user','content':'Please move the session bar a little higher than it is now.'}},{'type':'user','timestamp':'2026-10-18T01:05:00.000Z','message':{'role':'user','content':'Please also fix the badge that sits too far to the right.'}}]"
745
+ L40="$TMPDIR_ROOT/l40.md"
746
+ run "$TMPDIR_ROOT/l40a.out" extract --transcript "$TMPDIR_ROOT/l40.jsonl" --out "$L40"
747
+ L40A_RC=$RC
748
+ L40_PLAIN=$(grep -c '↩️' "$L40") # control: no prior file → no carry line
749
+ python3 - "$L40" <<'PYEOF'
750
+ import sys
751
+ p = sys.argv[1]; L = open(p, encoding="utf-8").read().split("\n")
752
+ for i, l in enumerate(L):
753
+ if l.startswith("| 1 |"):
754
+ L[i] = l.replace("| | | | |", "| ✅DONE | abc1234 (#99) | - | - |")
755
+ L.append("| 7 | 10-17 09:00 | an utterance no longer in the transcript | 🟡PARTIAL | - | half done | 이월: finish |")
756
+ open(p, "w", encoding="utf-8").write("\n".join(L))
757
+ PYEOF
758
+ run "$TMPDIR_ROOT/l40b.out" extract --transcript "$TMPDIR_ROOT/l40.jsonl" --out "$L40"
759
+ if [ "$L40A_RC" -eq 0 ] && [ "$RC" -eq 0 ] && [ "$L40_PLAIN" = 0 ] \
760
+ && grep -q '^| 1 | .*session bar.* | ✅DONE | abc1234 (#99) | - | - |$' "$L40" \
761
+ && grep -qE '^\| 2 \| .*badge.* \| \| \| \| \|$' "$L40" \
762
+ && grep -q '^## 이전 결과서에서 이어받지 못한 판정' "$L40" \
763
+ && grep -q 'an utterance no longer in the transcript | 🟡PARTIAL' "$L40" \
764
+ && grep -q '판정 1줄 이어받음 · 못 맞춘 판정 1줄' "$L40"; then
765
+ pass "L40 extract into a filled sheet: judgement carried (row 1), empty row stays empty (row 2), unmatched judgement kept under the orphan heading, no-file run writes plainly"
766
+ else
767
+ fail "L40 rc=$L40A_RC/$RC plain=$L40_PLAIN (see $L40)"
768
+ fi
769
+
741
770
  echo "── $PASS_COUNT passed, $FAIL_COUNT failed ──"
742
771
 
743
772
  if [ "$FAIL_COUNT" -gt 0 ]; then
@@ -79,6 +79,12 @@ case "${FH_STUB_MODE:-say}" in
79
79
  if [ "$_n" -eq 2 ]; then exit 7; fi
80
80
  printf '{"session_id":"SID-fixed","result":"turn %s ok"}\n' "$_n" ;;
81
81
  hang) sleep 30 ;;
82
+ # L29e — turn 1 crashes (rc 7), every later turn hangs. The rep returns its FIRST failing rc (7),
83
+ # so the budget line must read the per-turn table to see the timeout.
84
+ turns_die1_hang) _c=$(cat "${FH_STUB_SID_COUNTER:-/dev/null}" 2>/dev/null); [ -n "$_c" ] || _c=0
85
+ _n=$((_c+1)); echo "$_n" > "${FH_STUB_SID_COUNTER:-/dev/null}" 2>/dev/null || true
86
+ if [ "$_n" -eq 1 ]; then exit 7; fi
87
+ sleep 30 ;;
82
88
  esac
83
89
  exit 0
84
90
  STUB
@@ -523,5 +529,50 @@ grep -q "RESULT: CLEAN" "$WORKROOT/o_b28n.log" \
523
529
  && ok "L28n CONTROL — healthy multi-turn run is CLEAN (k/l/m are not firing on everything)" \
524
530
  || no "L28n CONTROL was not CLEAN — L28k/l/m prove nothing"
525
531
 
532
+ # ── L29 budget line (2026-10-17) — meta.tsv carries the cap the episode ran under and whether it
533
+ # ENDED AT it. Known-positive: a hanging stub under --timeout 1 (rc=124) -> yes. Known-negative:
534
+ # a normal answer -> no. And the two non-answers stay UNKNOWN, never `no`.
535
+ bud_meta() { # $1=tag $2=stub mode $3..= extra runner args ; env passes through. prints meta path
536
+ local tag="$1" mode="$2"; shift 2
537
+ ( cd "$SRC" && PATH="$STUBBIN:$PATH" HOME="$FAKEHOME" FH_STUB_MODE="$mode" \
538
+ bash "$SUT" --arm a --reps 1 --prompt p --out "$WORKROOT/o_$tag" "$@" ) >"$WORKROOT/o_$tag.log" 2>&1
539
+ printf '%s' "$WORKROOT/o_$tag/a_r1.meta.tsv"
540
+ }
541
+ meta_get() { awk -F'\t' -v k="$2" '$1==k{print $2}' "$1" 2>/dev/null; }
542
+ M="$(bud_meta b29a hang --timeout 1)"
543
+ { [ "$(meta_get "$M" ended_at_cap)" = yes ] && [ "$(meta_get "$M" rc)" = 124 ] && [ "$(meta_get "$M" timeout_s)" = 1 ]; } \
544
+ && ok "L29a KNOWN-POSITIVE — hang under --timeout 1: rc=124, timeout_s=1, ended_at_cap=yes" \
545
+ || no "L29a timeout not recorded as ended_at_cap=yes ($(meta_get "$M" rc)/$(meta_get "$M" ended_at_cap))"
546
+ M="$(bud_meta b29b say --timeout 60)"
547
+ { [ "$(meta_get "$M" ended_at_cap)" = no ] && [ "$(meta_get "$M" max_turns)" = unset ] && [ "$(meta_get "$M" timeout_s)" = 60 ]; } \
548
+ && ok "L29b KNOWN-NEGATIVE — normal answer: ended_at_cap=no, max_turns=unset, timeout_s=60" \
549
+ || no "L29b normal answer mis-recorded ($(meta_get "$M" ended_at_cap))"
550
+ M="$(bud_meta b29c die --timeout 60)"
551
+ [ "$(meta_get "$M" ended_at_cap)" = UNKNOWN ] \
552
+ && ok "L29c a crash (rc=7) is UNKNOWN, not no and not yes" \
553
+ || no "L29c crash classified as '$(meta_get "$M" ended_at_cap)'"
554
+ M="$(CLAUDE_CODE_MAX_OUTPUT_TOKENS=100 bud_meta b29d say --timeout 60)"
555
+ { [ "$(meta_get "$M" token_cap)" = 100 ] && [ "$(meta_get "$M" ended_at_cap)" = UNKNOWN ]; } \
556
+ && ok "L29d token cap read from the inherited env (100); rc=0 under a cap is UNKNOWN (stop reason not read)" \
557
+ || no "L29d token_cap/ended_at_cap: $(meta_get "$M" token_cap)/$(meta_get "$M" ended_at_cap)"
558
+ # L29e (review B2) — multi-turn: turn 1 rc=7, turn 2 times out. rep rc stays 7 (first failure), and
559
+ # before the fix ended_at_cap was UNKNOWN — the timeout was hidden.
560
+ : > "$WORKROOT/sid_b29e"
561
+ ( cd "$SRC" && PATH="$STUBBIN:$PATH" HOME="$FAKEHOME" FH_STUB_MODE=turns_die1_hang \
562
+ FH_STUB_SID_COUNTER="$WORKROOT/sid_b29e" \
563
+ bash "$SUT" --arm mt --reps 1 --turns "$WORKROOT/t3.txt" --timeout 1 --out "$WORKROOT/o_b29e" ) >"$WORKROOT/o_b29e.log" 2>&1
564
+ M="$WORKROOT/o_b29e/mt_r1.meta.tsv"
565
+ { [ "$(meta_get "$M" rc)" = 7 ] && [ "$(meta_get "$M" ended_at_cap)" = yes ]; } \
566
+ && ok "L29e multi-turn: turn-2 timeout behind a turn-1 crash still reads ended_at_cap=yes (rc stays 7)" \
567
+ || no "L29e multi-turn timeout hidden: rc=$(meta_get "$M" rc) ended_at_cap=$(meta_get "$M" ended_at_cap)"
568
+ # L29f (review C2) — a reused --out whose rep fails before writing meta must not keep the old meta.
569
+ mkdir -p "$WORKROOT/o_b29f"
570
+ printf 'rc\t0\nended_at_cap\tno\n' > "$WORKROOT/o_b29f/a_r1.meta.tsv"
571
+ ( cd "$SRC" && PATH="$STUBBIN:$PATH" HOME="$FAKEHOME" FH_STUB_MODE=say \
572
+ bash "$SUT" --arm a --reps 1 --prompt p --base-ref no-such-ref --base-sha 0000000 --out "$WORKROOT/o_b29f" ) >"$WORKROOT/o_b29f.log" 2>&1
573
+ { grep -q "BASE CLONE FAILED" "$WORKROOT/o_b29f.log" && [ ! -e "$WORKROOT/o_b29f/a_r1.meta.tsv" ]; } \
574
+ && ok "L29f clone failure on a reused --out leaves no stale ended_at_cap=no behind" \
575
+ || no "L29f stale meta survived (clone-fail seen: $(grep -c 'BASE CLONE FAILED' "$WORKROOT/o_b29f.log"))"
576
+
526
577
  echo "sim_isolated_run lanes: $pass passed, $fail failed"
527
578
  [ "$fail" -eq 0 ] || exit 1
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env bash
2
+ # Lanes for scripts/utterance_checklist_hook.sh (UserPromptSubmit: capture · cadence nudge · language line).
3
+ # Every lane runs the real hook against a temp CLAUDE_PROJECT_DIR — nothing touches the real hub.
4
+ # Known pairs: Korean ↔ English prompt (language line present ↔ absent) · content ↔ ack (row ↔ counted only) ·
5
+ # cadence row N ↔ N+1 (nudge ↔ none) · good ↔ broken input (output ↔ silent, both rc 0).
6
+ set -u
7
+ HERE="$(cd "$(dirname "$0")" && pwd)"
8
+ HOOK="$HERE/utterance_checklist_hook.sh"
9
+ pass=0; fail=0
10
+ ok() { pass=$((pass+1)); echo " PASS $1"; }
11
+ no() { fail=$((fail+1)); echo " FAIL $1 — $2"; }
12
+ [ -f "$HOOK" ] || { echo "HARNESS-ERROR: hook missing"; exit 10; }
13
+ T="$(mktemp -d)"; trap 'rm -rf "$T"' EXIT
14
+ SID="0123abcd-0000-4000-8000-000000000001"
15
+ run() { # $1 prompt [$2 sid] → stdout; rc in $RC
16
+ local p="$1" s="${2:-$SID}"
17
+ OUT=$(python3 -c 'import json,sys;print(json.dumps({"prompt":sys.argv[1],"session_id":sys.argv[2],"transcript_path":"/x/t.jsonl","hook_event_name":"UserPromptSubmit"}))' "$p" "$s" | CLAUDE_PROJECT_DIR="$T" FH_CHECKLIST_CADENCE="${CAD:-15}" bash "$HOOK"); RC=$?
18
+ }
19
+ D="$T/tracks/_meta/utterances"
20
+
21
+ # U1 language line: Korean → present, English → absent
22
+ run "세션바를 조금 더 위로 올려 줘"
23
+ [ $RC = 0 ] && printf '%s' "$OUT" | grep -q '이번 메시지를 한글로' && ok "U1a Korean prompt → language line" || no U1a "rc=$RC out=$OUT"
24
+ run "please move the session bar up a little"
25
+ [ $RC = 0 ] && ! printf '%s' "$OUT" | grep -q '한글로' && ok "U1b English prompt → no language line" || no U1b "rc=$RC out=$OUT"
26
+
27
+ # U2 content is written down; a short ack is counted, not listed
28
+ rows_before=$(wc -l < "$D/$SID.jsonl" 2>/dev/null | tr -d " " || echo 0)
29
+ run "ㅇㅇ"
30
+ rows_after=$(wc -l < "$D/$SID.jsonl" 2>/dev/null | tr -d " " || echo 0)
31
+ acks=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["acks"])' "$D/$SID.state.json" 2>/dev/null)
32
+ [ "$rows_before" = "$rows_after" ] && [ "$acks" = 1 ] && ok "U2a ack → counted (acks=1), no row" || no U2a "rows ${rows_before}→${rows_after} acks=${acks}"
33
+ [ "$rows_before" = 2 ] && python3 -c 'import json,sys;r=[json.loads(l) for l in open(sys.argv[1])];assert r[0]["text"].startswith("세션바") and r[0]["n"]==1' "$D/$SID.jsonl" && ok "U2b content prompts → rows with text and n" || no U2b "rows=$rows_before"
34
+ run "왜 이게 떠?" # short but a question → a row
35
+ [ "$(wc -l < "$D/$SID.jsonl" | tr -d " ")" = 3 ] && ok "U2c a short question is written down" || no U2c "rows=$(wc -l < "$D/$SID.jsonl" | tr -d " ")"
36
+
37
+ # U3 cadence nudge: with cadence 3, rows 3 and 6 nudge; rows 4 and 5 do not
38
+ S2="0123abcd-0000-4000-8000-000000000002"
39
+ CAD=3
40
+ n=0; got=""
41
+ for p in "첫 번째 요청을 받아 적어 둔다" "두 번째 요청을 받아 적어 둔다" "세 번째 요청을 받아 적어 둔다" "네 번째 요청을 받아 적어 둔다" "다섯 번째 요청을 받아 적어 둔다" "여섯 번째 요청을 받아 적어 둔다"; do # content, not an ack
42
+ n=$((n+1)); run "$p" "$S2"
43
+ printf '%s' "$OUT" | grep -q '체크리스트 점검 시점' && got="$got$n,"
44
+ done
45
+ CAD=15
46
+ [ "$got" = "3,6," ] && ok "U3 cadence 3 → nudges at rows 3 and 6 only" || no U3 "nudged at: $got"
47
+ CAD=3; run "세 번째 다음의 요청 하나를 더 적어 둔다" "0123abcd-0000-4000-8000-000000000003"; run "두 번째 요청을 하나 더 받아 적는다" "0123abcd-0000-4000-8000-000000000003"; run "세 번째 요청을 하나 더 받아 적는다" "0123abcd-0000-4000-8000-000000000003"; CAD=15
48
+ printf '%s' "$OUT" | grep -q "session_checklist.py extract --transcript /x/t.jsonl --out tracks/_meta/session_checklist_" && ok "U3b the nudge names the extract command with this transcript" || no U3b "out=$OUT"
49
+
50
+ # U4 broken input → rc 0, silent; injected notices are not the operator
51
+ for bad in "" "not json" '{"prompt":"안녕하세요 반갑습니다","session_id":"../../etc"}' '{"prompt":"","session_id":"0123abcd-0000"}'; do
52
+ OUT=$(printf '%s' "$bad" | CLAUDE_PROJECT_DIR="$T" bash "$HOOK"); RC=$?
53
+ [ $RC = 0 ] && [ -z "$OUT" ] && ok "U4 bad input silent rc0: ${bad:0:24}" || no U4 "rc=$RC out=$OUT input=$bad"
54
+ done
55
+ ls "$T/etc" >/dev/null 2>&1 && no U4b "path escape created a dir" || ok "U4b a session id with ../ writes nothing outside"
56
+ before=$(wc -l < "$D/$SID.jsonl" | tr -d " "); run "<task-notification>배경 작업이 끝났다 길게 적은 알림</task-notification>"
57
+ [ "$(wc -l < "$D/$SID.jsonl" | tr -d " ")" = "$before" ] && ok "U4c an injected notice is not written down" || no U4c "row added"
58
+ # U4d a subagent hand-back relayed into the prompt is not the operator (first live use: 2 of 15 rows were hand-backs)
59
+ before=$(wc -l < "$D/$SID.jsonl" | tr -d " "); run '<agent-message from="a0000000000000000"> [Subagent hand-back] 체크리스트 259행을 전부 채웠다</agent-message>'
60
+ [ "$(wc -l < "$D/$SID.jsonl" | tr -d " ")" = "$before" ] && ok "U4d a subagent hand-back is not written down" || no U4d "row added"
61
+
62
+ # U5 output is valid JSON with the UserPromptSubmit shape whenever there is output
63
+ run "한글로 된 내용 있는 요청입니다"
64
+ printf '%s' "$OUT" | python3 -c 'import json,sys;o=json.load(sys.stdin);h=o["hookSpecificOutput"];assert h["hookEventName"]=="UserPromptSubmit" and h["additionalContext"]' && ok "U5 output shape" || no U5 "out=$OUT"
65
+
66
+ # U6 the real hub is untouched (control: the temp hub got the files)
67
+ [ -f "$D/$SID.jsonl" ] && [ ! -e "$HERE/../tracks/_meta/utterances/$SID.jsonl" ] && ok "U6 writes only under CLAUDE_PROJECT_DIR" || no U6 "real hub touched or temp missing"
68
+
69
+ # U7 the close chain asks for the result sheet (①-g) and reads session_checklist.py's rc the way that tool defines it
70
+ SCC="$HERE/session_close_check.sh"; SCPY="$HERE/session_checklist.py"
71
+ if grep -q '①-g' "$SCC" && grep -q 'python3 "$_SC_PY" check --file "$_f"' "$SCC"; then ok "U7a ①-g calls session_checklist.py check"; else no U7a "wiring missing"; fi
72
+ grep -q 'session_checklist_\*_"${_UI_SID:0:8}".md' "$SCC" && ok "U7c ①-g selects this session's sheet by id (not any sheet of today)" || no U7c "selection by today only"
73
+ grep -q 'restates it on each mostly-Hangul message' "$HERE/../CLAUDE.md" && grep -q 'every 15 written-down requests' "$HERE/../CLAUDE.md" && ok "U7d CLAUDE.md describes what the hook really does" || no U7d "wording drift"
74
+ cat > "$T/ok.md" <<'MD'
75
+ | # | 발화 | 상태 | 증거 | 사유 | 제안 |
76
+ |---|---|---|---|---|---|
77
+ | 1 | 세션바를 올려 줘 | ✅DONE | FoD #70 | | |
78
+ MD
79
+ cat > "$T/empty.md" <<'MD'
80
+ | # | 발화 | 상태 | 증거 | 사유 | 제안 |
81
+ |---|---|---|---|---|---|
82
+ | 1 | 세션바를 올려 줘 | | | | |
83
+ MD
84
+ python3 "$SCPY" check --file "$T/ok.md" >/dev/null 2>&1; r_ok=$?
85
+ python3 "$SCPY" check --file "$T/empty.md" >/dev/null 2>&1; r_empty=$?
86
+ [ "$r_ok" = 0 ] && [ "$r_empty" = 1 ] && ok "U7b check rc: filled row 0 · empty status 1 (the values ①-g branches on)" || no U7b "rc ok=$r_ok empty=$r_empty"
87
+
88
+ # ── codex R1 (2026-10-18) cases ──
89
+ mk() { python3 -c 'import json,sys;print(json.dumps({"prompt":sys.argv[1],"session_id":sys.argv[2],"transcript_path":sys.argv[3] if len(sys.argv)>3 else "/x/t.jsonl"}))' "$@"; }
90
+ # U8 A1 symlink: a symlinked utterances dir (or file) is refused — nothing lands at the link target
91
+ T2="$(mktemp -d)"; mkdir -p "$T2/tracks/_meta" "$T2/outside"; ln -s "$T2/outside" "$T2/tracks/_meta/utterances"
92
+ mk "심볼릭 링크 너머로 쓰면 안 되는 요청이다" "0123abcd-0000-4000-8000-0000000000a1" | CLAUDE_PROJECT_DIR="$T2" bash "$HOOK" >/dev/null; RC=$?
93
+ [ $RC = 0 ] && [ -z "$(ls -A "$T2/outside")" ] && ok "U8a symlinked dir refused, nothing written at the target" || no U8a "rc=$RC files=$(ls "$T2/outside")"
94
+ T3="$(mktemp -d)"; mkdir -p "$T3/tracks/_meta/utterances" && : > "$T3/public.md"; ln -s "$T3/public.md" "$T3/tracks/_meta/utterances/0123abcd-0000-4000-8000-0000000000a2.jsonl"
95
+ mk "파일 심볼릭 링크로 공개 파일에 쓰면 안 된다" "0123abcd-0000-4000-8000-0000000000a2" | CLAUDE_PROJECT_DIR="$T3" bash "$HOOK" >/dev/null
96
+ [ ! -s "$T3/public.md" ] && ok "U8b symlinked jsonl refused (public file untouched)" || no U8b "written: $(cat "$T3/public.md")"
97
+ # control: the same prompt with no symlink IS written (the refusal is the symlink's doing)
98
+ mk "파일 심볼릭 링크로 공개 파일에 쓰면 안 된다" "0123abcd-0000-4000-8000-0000000000a3" | CLAUDE_PROJECT_DIR="$T3" bash "$HOOK" >/dev/null
99
+ [ -s "$T3/tracks/_meta/utterances/0123abcd-0000-4000-8000-0000000000a3.jsonl" ] && ok "U8c control: a regular path is written" || no U8c "not written"
100
+ # U9 A2 a FIFO at the record path does not stall the prompt
101
+ mkfifo "$T3/tracks/_meta/utterances/0123abcd-0000-4000-8000-0000000000a4.jsonl"
102
+ t0=$(python3 -c 'import time;print(time.time())')
103
+ # a hung hook must fail this lane, not hang the suite: run it under a 5 s limit (python — macOS has no timeout(1))
104
+ RC=$(python3 - "$HOOK" "$T3" <<'PY'
105
+ import json, subprocess, sys
106
+ inp = json.dumps({"prompt": "파이프 파일이 있어도 멈추면 안 되는 요청", "session_id": "0123abcd-0000-4000-8000-0000000000a4", "transcript_path": "/x/t.jsonl"})
107
+ import os, signal
108
+ p = subprocess.Popen(["bash", sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
109
+ env={"CLAUDE_PROJECT_DIR": sys.argv[2], "PATH": "/usr/bin:/bin", "HOME": "/tmp"}, start_new_session=True)
110
+ try:
111
+ p.communicate(inp.encode(), timeout=5); print(p.returncode)
112
+ except subprocess.TimeoutExpired:
113
+ os.killpg(p.pid, signal.SIGKILL); p.wait(); print("hung") # the whole group: a grandchild blocked on the FIFO must not outlive the lane
114
+ PY
115
+ )
116
+ el=$(python3 -c "import time;print(round(time.time()-$t0,2))")
117
+ python3 -c "import sys;sys.exit(0 if $el < 2.0 else 1)" && [ $RC = 0 ] && ok "U9 FIFO: rc 0 in ${el}s (no block)" || no U9 "rc=$RC ${el}s"
118
+ # U10 B7 a 3 MB prompt is handled (stdin, not env)
119
+ # the input is generated inside python (a multi-MB argv would itself hit E2BIG in the test — measured)
120
+ OUT=$(python3 -c 'import json;print(json.dumps({"prompt":"가"*1500000,"session_id":"0123abcd-0000-4000-8000-0000000000a5","transcript_path":"/x/t.jsonl"},ensure_ascii=False))' | CLAUDE_PROJECT_DIR="$T" bash "$HOOK"); RC=$?
121
+ printf '%s' "$OUT" | grep -q '한글로' && [ $RC = 0 ] && ok "U10 a 1.5M-char prompt still gets the language line (no E2BIG)" || no U10 "rc=$RC"
122
+ python3 -c 'import json,sys;r=[json.loads(l) for l in open(sys.argv[1])][-1];assert r.get("truncated") is True and r["chars"]==1500000 and len(r["text"])==20000' "$D/0123abcd-0000-4000-8000-0000000000a5.jsonl" && ok "U10b a long utterance is marked truncated with its real length (B6)" || no U10b "not marked"
123
+ # U11 B5 short real requests and <tag> requests are written down; acks are not
124
+ for p in "버그 고쳐줘" "<div>이 컴포넌트를 수정해 주세요</div>"; do
125
+ b=$(cat "$D/$SID.jsonl" 2>/dev/null | wc -l | tr -d ' '); run "$p"; a=$(wc -l < "$D/$SID.jsonl" | tr -d ' ')
126
+ [ "$a" = $((b+1)) ] && ok "U11 written down: $p" || no U11 "not written: $p"
127
+ done
128
+ for p in "ㅇㅇ" "ㄱㄱ" "ㅇㅋ" "확인완료" "ok"; do
129
+ b=$(wc -l < "$D/$SID.jsonl" | tr -d ' '); run "$p"; a=$(wc -l < "$D/$SID.jsonl" | tr -d ' ')
130
+ [ "$a" = "$b" ] && ok "U11b ack not listed: $p" || no U11b "listed: $p"
131
+ done
132
+ # U12 B9 language: Japanese is not Korean; Korean prose with pasted English code is Korean
133
+ run "このバグを直してください。「한글」という単語を含みます"
134
+ ! printf '%s' "$OUT" | grep -q '한글로' && ok "U12a Japanese prompt → no Korean line" || no U12a "fired"
135
+ run $'이 함수 좀 고쳐 줘\n```js\nfunction computeTheThingWithAVeryLongEnglishName(argumentOne, argumentTwo) { return argumentOne + argumentTwo }\n```'
136
+ printf '%s' "$OUT" | grep -q '한글로' && ok "U12b Korean prose + English code → Korean line" || no U12b "missed"
137
+ # U13 B12 the nudge names only statuses the checker accepts; B10 the path is shell-quoted
138
+ S4="0123abcd-0000-4000-8000-0000000000a6"; CAD=3
139
+ for i in 1 2 3; do OUT=$(mk "점검 박자 확인용 요청 번호 $i 입니다" "$S4" "/tmp/with space/t.jsonl" | CLAUDE_PROJECT_DIR="$T" FH_CHECKLIST_CADENCE=3 bash "$HOOK"); done; CAD=15
140
+ printf '%s' "$OUT" | grep -q '🔎UNVERIFIED' && ! printf '%s' "$OUT" | grep -q '❓' && ok "U13a nudge lists 🔎UNVERIFIED (accepted by session_checklist.py), not ❓" || no U13a "out=$OUT"
141
+ printf '%s' "$OUT" | grep -qF -- "--transcript '/tmp/with space/t.jsonl'" && ok "U13b transcript path is shell-quoted" || no U13b "out=$OUT"
142
+ # U14 B8 HOME and CLAUDE_PROJECT_DIR unset → still rc 0
143
+ OUT=$(mk "홈 변수가 없어도 죽으면 안 된다" "0123abcd-0000-4000-8000-0000000000a7" | env -i PATH=/usr/bin:/bin bash "$HOOK"); RC=$?
144
+ [ $RC = 0 ] && ok "U14 no HOME, no CLAUDE_PROJECT_DIR → rc 0" || no U14 "rc=$RC"
145
+ # U15 B3 ten prompts at once: ten rows, numbered 1..10 with no duplicate, state says 10
146
+ S5="0123abcd-0000-4000-8000-0000000000a8"
147
+ for i in $(seq 1 10); do (mk "동시에 들어온 요청 번호 $i 입니다 길게" "$S5" | CLAUDE_PROJECT_DIR="$T" bash "$HOOK" >/dev/null) & done; wait
148
+ python3 -c 'import json,sys;r=[json.loads(l)["n"] for l in open(sys.argv[1])];s=json.load(open(sys.argv[2]));assert sorted(r)==list(range(1,11)) and s["rows"]==10,(sorted(r),s)' "$D/$S5.jsonl" "$D/$S5.state.json" && ok "U15 10 concurrent prompts → rows 1..10, state 10 (locked)" || no U15 "race"
149
+ rm -rf "$T2" "$T3"
150
+
151
+ # ── codex R2 (final round) cases ──
152
+ T4="$(mktemp -d)"; mkdir -p "$T4/tracks/_meta/utterances"; : > "$T4/outside.md"
153
+ ln "$T4/outside.md" "$T4/tracks/_meta/utterances/0123abcd-0000-4000-8000-0000000000b1.jsonl"
154
+ mk "하드 링크로 바깥 파일에 쓰면 안 되는 요청" "0123abcd-0000-4000-8000-0000000000b1" | CLAUDE_PROJECT_DIR="$T4" bash "$HOOK" >/dev/null
155
+ [ ! -s "$T4/outside.md" ] && ok "U16 hard-linked record refused (outside file untouched)" || no U16 "written through hard link"
156
+ t0=$(python3 -c 'import time;print(time.time())')
157
+ python3 -c 'import json;print(json.dumps({"prompt":"ㅋ"*20000+"x","session_id":"0123abcd-0000-4000-8000-0000000000b2"}))' | CLAUDE_PROJECT_DIR="$T4" bash "$HOOK" >/dev/null
158
+ el=$(python3 -c "import time;print(round(time.time()-$t0,2))")
159
+ python3 -c "import sys;sys.exit(0 if $el < 1.0 else 1)" && ok "U17 a 20000-char near-ack is handled in ${el}s (no regex blow-up)" || no U17 "${el}s"
160
+ S6="0123abcd-0000-4000-8000-0000000000b3"; mkdir -p "$T4/tracks/_meta/utterances/$S6.state.json" # state can never be written
161
+ for i in 1 2 3; do mk "상태 저장이 안 돼도 번호가 겹치면 안 된다 $i" "$S6" | CLAUDE_PROJECT_DIR="$T4" bash "$HOOK" >/dev/null; done
162
+ python3 -c 'import json,sys;r=[json.loads(l)["n"] for l in open(sys.argv[1])];assert r==[1,2,3],r' "$T4/tracks/_meta/utterances/$S6.jsonl" && ok "U18 numbering comes from the record when state cannot be saved (1,2,3)" || no U18 "repeated numbers"
163
+ rm -rf "$T4"
164
+
165
+ # U19 the body runs on its own (the .sh is a thin wrapper): FH_HUB set → row + language line, FH_HUB unset → silent, rc 0 both
166
+ PYB="$HERE/utterance_checklist_hook.py"
167
+ S19="0123abcd-0000-4000-8000-000000000019"
168
+ J19=$(python3 -c 'import json,sys;print(json.dumps({"prompt":"본체를 직접 실행해서 받아 적는지 본다","session_id":sys.argv[1]}))' "$S19")
169
+ O19=$(printf '%s' "$J19" | FH_HUB="$T" python3 "$PYB"); R19=$?
170
+ [ $R19 = 0 ] && printf '%s' "$O19" | grep -q '한글로' && [ "$(wc -l < "$D/$S19.jsonl" 2>/dev/null | tr -d ' ')" = 1 ] && ok "U19a body run directly → row + language line" || no U19a "rc=$R19 out=$O19"
171
+ O19b=$(printf '%s' "$J19" | env -u FH_HUB python3 "$PYB"); R19b=$?
172
+ [ $R19b = 0 ] && [ -z "$O19b" ] && [ "$(wc -l < "$D/$S19.jsonl" | tr -d ' ')" = 1 ] && ok "U19b body without FH_HUB → silent, nothing written" || no U19b "rc=$R19b out=$O19b"
173
+
174
+ echo "lanes: pass=$pass fail=$fail"
175
+ [ $fail = 0 ]
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env python3
2
+ """utterance_checklist_hook.py — body of scripts/utterance_checklist_hook.sh (UserPromptSubmit). See the .sh header for WHY.
3
+
4
+ Reads the hook JSON on STDIN (never through the environment: a multi-MB prompt hit E2BIG and silently disabled the hook —
5
+ codex R1 B7). Contract: exit 0 always, output only JSON hookSpecificOutput.additionalContext on stdout, never write outside
6
+ <hub>/tracks/_meta/utterances/, never follow a symlink there, never block on a FIFO or a held lock.
7
+
8
+ codex R1 (2026-10-18, 12 findings) fixed here: symlink escape (A1) · FIFO/lock stall (A2) · unlocked read-modify-write (B3) ·
9
+ counter advanced on a failed append (B4) · «<…» / short real requests dropped (B5) · silent truncation (B6) · env E2BIG (B7) ·
10
+ HOME unbound (B8, in the .sh) · Japanese/Chinese read as Korean, pasted code counted (B9) · unquoted path in the suggested
11
+ command (B10) · a status label the checker rejects (B12).
12
+ """
13
+ import errno, fcntl, json, os, re, shlex, stat, sys, time
14
+
15
+ ACK = re.compile(r"^(?:ㅇ+|ㄱ+|ㅇㅋ+|ㅇㅇㄱㄱ|ㄴㄴ|ok(?:ay)?|ㅇㅋㅇㅋ|넵|네+|응+|좋아|굿|확인(?:완료)?|ㄱㄱ+|go|yes|y|no|n|ㅋ+|ㅎ+)[\s.!~?ㅋㅎ]*$", re.I)
16
+ INJECTED = re.compile(r"^\s*(?:<(?:task-notification|system-reminder|command-name|command-message|command-args|local-command-stdout|local-command-stderr|bash-input|bash-stdout|bash-stderr|agent-message)\b|\[SYSTEM NOTIFICATION|\[Cross-session delivery notice\]|\[automated-run)", re.I)
17
+ MAX_KEEP = 20000 # chars kept per utterance; longer ones are marked truncated, never cut silently
18
+ MAX_SCAN = 20000 # chars scanned for language (bounded work on huge pastes)
19
+
20
+
21
+ def safe_dir(hub):
22
+ """<hub>/tracks/_meta/utterances as a real directory inside the hub, or None. No symlink anywhere on the last two hops."""
23
+ meta = os.path.join(hub, "tracks", "_meta")
24
+ d = os.path.join(meta, "utterances")
25
+ try:
26
+ tracks = os.path.dirname(meta)
27
+ for p in (tracks, meta):
28
+ if os.path.islink(p):
29
+ return None
30
+ if not os.path.lexists(p):
31
+ try: os.mkdir(p, 0o700)
32
+ except FileExistsError: pass # a parallel first prompt made it (Sonnet R2 #4)
33
+ if not stat.S_ISDIR(os.lstat(p).st_mode):
34
+ return None
35
+ if not os.path.lexists(d):
36
+ try: os.mkdir(d, 0o700)
37
+ except FileExistsError: pass
38
+ st = os.lstat(d)
39
+ if not stat.S_ISDIR(st.st_mode): # a symlink or anything else → refuse
40
+ return None
41
+ real_hub = os.path.realpath(hub)
42
+ if not os.path.realpath(d).startswith(real_hub + os.sep):
43
+ return None
44
+ return d
45
+ except OSError:
46
+ return None
47
+
48
+
49
+ DFD = None # directory fd of utterances/ — every file opens relative to it (codex R2: the folder can't be swapped after the check)
50
+
51
+
52
+ def open_regular(name, flags, mode=0o600):
53
+ """open <name> inside utterances/ via its directory fd, without following a symlink and without blocking on a FIFO;
54
+ refuse anything but a regular file with a single link (a hard link would write into a file elsewhere — codex R2)."""
55
+ fd = os.open(name, flags | os.O_NOFOLLOW | os.O_NONBLOCK, mode, dir_fd=DFD)
56
+ try:
57
+ st = os.fstat(fd)
58
+ if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1:
59
+ raise OSError(errno.EINVAL, "not a single-link regular file")
60
+ fl = fcntl.fcntl(fd, fcntl.F_GETFL)
61
+ fcntl.fcntl(fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
62
+ return fd
63
+ except Exception:
64
+ os.close(fd)
65
+ raise
66
+
67
+
68
+ def prose_only(text):
69
+ t = re.sub(r"```.*?```", " ", text[:MAX_SCAN], flags=re.S) # fenced code
70
+ t = re.sub(r"`[^`\n]*`", " ", t) # inline code
71
+ t = re.sub(r"https?://\S+|(?:~|/)[\w.\-/]+", " ", t) # urls and paths
72
+ return t
73
+
74
+
75
+ def main():
76
+ try:
77
+ raw = sys.stdin.buffer.read(32 * 1024 * 1024).decode("utf-8", "replace")
78
+ ev = json.loads(raw)
79
+ except Exception:
80
+ return
81
+ if not isinstance(ev, dict):
82
+ return
83
+ prompt = ev.get("prompt") if isinstance(ev.get("prompt"), str) else ""
84
+ sid = ev.get("session_id") if isinstance(ev.get("session_id"), str) else ""
85
+ if not prompt.strip() or not re.fullmatch(r"[A-Za-z0-9-]{8,80}", sid):
86
+ return
87
+ if INJECTED.match(prompt):
88
+ return # notices relayed by the runtime, not the operator
89
+ text = prompt.strip()
90
+ substantive = not (len(text) <= 40 and ACK.match(text)) # acks are short; never run the pattern on long text (codex R2)
91
+ hub = os.environ.get("FH_HUB") or ""
92
+ if not hub:
93
+ return
94
+ notes = []
95
+
96
+ global DFD
97
+ d = safe_dir(hub)
98
+ if d:
99
+ try:
100
+ DFD = os.open(d, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
101
+ except OSError:
102
+ d = None
103
+ if d:
104
+ lock_p = sid + ".lock"
105
+ try:
106
+ lfd = open_regular(lock_p, os.O_RDWR | os.O_CREAT)
107
+ except OSError:
108
+ lfd = None
109
+ if lfd is not None:
110
+ locked = False
111
+ deadline = time.monotonic() + 0.3 # never hold the operator's prompt on a lock for long (codex R2)
112
+ while time.monotonic() < deadline:
113
+ try:
114
+ fcntl.flock(lfd, fcntl.LOCK_EX | fcntl.LOCK_NB); locked = True; break
115
+ except OSError:
116
+ time.sleep(0.02)
117
+ if locked:
118
+ try:
119
+ state_p = sid + ".state.json"
120
+ try:
121
+ sfd = open_regular(state_p, os.O_RDONLY)
122
+ if os.fstat(sfd).st_size > 65536: # bounded: a state file is a few dozen bytes
123
+ os.close(sfd); raise ValueError
124
+ with os.fdopen(sfd, "r") as f:
125
+ st = json.load(f)
126
+ if not isinstance(st, dict):
127
+ raise ValueError
128
+ except Exception:
129
+ st = {"rows": 0, "acks": 0, "last_nudge": 0}
130
+ if substantive:
131
+ n_prev = int(st.get("rows", 0))
132
+ try: # the record is the source of n — a failed state write must not repeat numbers (codex R2)
133
+ rfd = open_regular(sid + ".jsonl", os.O_RDONLY)
134
+ with os.fdopen(rfd, "rb") as f:
135
+ n_prev = max(n_prev, f.read(16 * 1024 * 1024).count(b"\n"))
136
+ except OSError:
137
+ pass
138
+ row = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "n": n_prev + 1, "text": text[:MAX_KEEP]}
139
+ if len(text) > MAX_KEEP:
140
+ row["truncated"] = True; row["chars"] = len(text)
141
+ try:
142
+ afd = open_regular(sid + ".jsonl", os.O_WRONLY | os.O_APPEND | os.O_CREAT)
143
+ with os.fdopen(afd, "a", encoding="utf-8") as f:
144
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
145
+ st["rows"] = row["n"] # count only what was really written down
146
+ except OSError:
147
+ pass
148
+ else:
149
+ st["acks"] = int(st.get("acks", 0)) + 1
150
+ try:
151
+ cadence = max(3, int(os.environ.get("FH_CHECKLIST_CADENCE", "15")))
152
+ except Exception:
153
+ cadence = 15
154
+ if substantive and int(st.get("rows", 0)) - int(st.get("last_nudge", 0)) >= cadence:
155
+ st["last_nudge"] = st["rows"]
156
+ tp = ev.get("transcript_path") if isinstance(ev.get("transcript_path"), str) and ev.get("transcript_path") else ""
157
+ out = f"tracks/_meta/session_checklist_{time.strftime('%Y-%m-%d')}_{sid[:8]}.md"
158
+ cmd = (f"python3 scripts/session_checklist.py extract --transcript {shlex.quote(tp)} --out {shlex.quote(out)}"
159
+ if tp else "python3 scripts/session_checklist.py extract --transcript (이 세션 전사본 경로) --out " + shlex.quote(out))
160
+ notes.append(
161
+ f"📋 [FH 체크리스트 점검 시점] 이 세션에서 받아 적은 운영자 발화가 {st['rows']}건이다(지난 점검 뒤 {cadence}건 이상). "
162
+ f"이번 답을 마치기 전에 체크리스트를 갱신하라: {cmd} → 상태 칸을 ✅DONE·🟡PARTIAL·⏳IN-PROGRESS·❌NOT-DONE·⏸HELD·🔎UNVERIFIED 중 하나로, "
163
+ f"완료는 증거·미완은 사유+제안과 함께 채우고 → 표를 운영자에게 보여라(열린 줄이 위로). 받아 적은 원문: tracks/_meta/utterances/{sid}.jsonl")
164
+ fd, tmp = None, f"{sid}.state.{os.getpid()}.tmp"
165
+ try:
166
+ fd = open_regular(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_EXCL)
167
+ with os.fdopen(fd, "w") as f:
168
+ json.dump(st, f)
169
+ os.replace(tmp, state_p, src_dir_fd=DFD, dst_dir_fd=DFD)
170
+ except OSError:
171
+ try: os.unlink(tmp, dir_fd=DFD)
172
+ except OSError: pass
173
+ finally:
174
+ try: fcntl.flock(lfd, fcntl.LOCK_UN)
175
+ except OSError: pass
176
+ os.close(lfd)
177
+
178
+ p = prose_only(text)
179
+ hangul = len(re.findall(r"[가-힣]", p))
180
+ other_cjk = len(re.findall(r"[぀-ヿ一-鿿]", p)) # kana + Han
181
+ latin = len(re.findall(r"[A-Za-z]", p))
182
+ if hangul >= 2 and hangul >= other_cjk and hangul * 2 >= latin:
183
+ notes.append("🗣️ 운영자는 이번 메시지를 한글로 썼다 — 이 턴에 운영자에게 보이는 글은 전부 한글로(도구 호출 사이 진행 메모 포함). 영어는 커밋 메시지·코드·서브에이전트 지시문에만.")
184
+ if notes:
185
+ print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": "\n".join(notes)}}, ensure_ascii=False))
186
+
187
+
188
+ if __name__ == "__main__":
189
+ try:
190
+ main()
191
+ except Exception:
192
+ pass
193
+ sys.exit(0)