@chrono-meta/fh-gate 3.42.0 → 3.44.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 (71) hide show
  1. package/.claude/regression/probes_live.yaml +16 -8
  2. package/.claude/rules/fh_4axis_gate.md +8 -0
  3. package/.claude-plugin/marketplace.json +4 -4
  4. package/AGENTS.md +9 -0
  5. package/README.ja.md +2 -0
  6. package/README.ko.md +2 -0
  7. package/README.md +2 -0
  8. package/README.zh.md +2 -0
  9. package/docs/HOW_FH_DIFFERS.en.md +37 -0
  10. package/docs/HOW_FH_DIFFERS.md +39 -0
  11. package/docs/USER_GUIDE.md +208 -2
  12. package/docs/model_tier_expectations.md +8 -4
  13. package/knowledge/shared/harness-core/claude_md_full_reference.md +10 -0
  14. package/knowledge/shared/harness-core/dispatch_conditional_prohibition.md +18 -0
  15. package/knowledge/shared/harness-core/fh_module_contract.md +19 -0
  16. package/knowledge/shared/harness-core/governance_engineering_definition.md +16 -0
  17. package/knowledge/shared/harness-core/measurement-integrity-checklist.md +24 -0
  18. package/knowledge/shared/learnings/subagent_invocations_log.yaml +42 -0
  19. package/knowledge/shared/plugin-catalog/recommended_plugins.md +53 -9
  20. package/package.json +13 -1
  21. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  22. package/plugins/fh-commons/skills/ko-tech-writer/SKILL.md +49 -14
  23. package/plugins/fh-commons/skills/ko-tech-writer/SKILL_detail.md +60 -0
  24. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/sense_negative.md +30 -0
  25. package/plugins/fh-commons/skills/ko-tech-writer/fixtures/sense_positive.md +56 -0
  26. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  27. package/plugins/fh-meta/CHANGELOG.md +55 -2
  28. package/plugins/fh-meta/skills/auto-decorrelation/SKILL.md +45 -1
  29. package/plugins/fh-meta/skills/edit-manifest/SKILL.md +14 -1
  30. package/plugins/fh-meta/skills/harvest-loop/SKILL.md +1 -1
  31. package/plugins/fh-meta/skills/meta-prompt-builder/SKILL.md +19 -0
  32. package/plugins/fh-meta/skills/sim-conductor/SKILL_detail.md +3 -3
  33. package/plugins/fh-meta/skills/steel-quench/SKILL_detail.md +8 -4
  34. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  35. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  36. package/scripts/agy_launch_guard.sh +49 -0
  37. package/scripts/agy_remote_run.sh +187 -0
  38. package/scripts/capability_registry_check.sh +15 -2
  39. package/scripts/codex_launch_guard.sh +87 -0
  40. package/scripts/finding_fleet.sh +35 -2
  41. package/scripts/finding_verifier.sh +6 -2
  42. package/scripts/ko_tech_writer_calibrate.py +88 -1
  43. package/scripts/live_eval_trace.py +141 -0
  44. package/scripts/package_coverage_check.sh +7 -0
  45. package/scripts/pr_merge_verified.sh +7 -0
  46. package/scripts/prepush_guard_check.sh +33 -20
  47. package/scripts/probe_live_eval.sh +6 -3
  48. package/scripts/probe_live_eval_lib.py +92 -2
  49. package/scripts/remote_marker_gate.sh +56 -0
  50. package/scripts/selfcheck.sh +58 -2
  51. package/scripts/session_checklist.py +109 -5
  52. package/scripts/session_close_check.sh +16 -0
  53. package/scripts/sidecar_calibrate.sh +10 -2
  54. package/scripts/sidecar_wait.sh +21 -1
  55. package/scripts/sim_isolated_run.sh +17 -2
  56. package/scripts/test_agy_launch_guard_lanes.sh +227 -0
  57. package/scripts/test_agy_remote_run_lanes.sh +228 -0
  58. package/scripts/test_codex_launch_guard_lanes.sh +138 -0
  59. package/scripts/test_finding_pipeline_lanes.sh +6 -2
  60. package/scripts/test_fixture_guard_coverage_lanes.sh +71 -10
  61. package/scripts/test_live_eval_trace_lanes.sh +191 -0
  62. package/scripts/test_meta_prompt_restate_lanes.sh +36 -0
  63. package/scripts/test_mutation_probe_lanes.sh +26 -6
  64. package/scripts/test_pr_merge_verified_lanes.sh +23 -0
  65. package/scripts/test_preprep_speech_coach_lanes.sh +18 -2
  66. package/scripts/test_prepush_guard_failure_visibility_lanes.sh +152 -0
  67. package/scripts/test_remote_marker_gate_lanes.sh +96 -0
  68. package/scripts/test_session_checklist_lanes.sh +205 -0
  69. package/scripts/test_session_close_lanes.sh +7 -0
  70. package/scripts/test_sidecar_calibrate_lanes.sh +4 -0
  71. package/scripts/test_sidecar_wait_stdin.sh +18 -0
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env bash
2
+ # agy_remote_run.sh — an agy stand-in that runs agy ONLY as a separate OS user on another machine.
3
+ #
4
+ # WHY. agy runs its own shell and file tools and sends what they print to the cloud model, so it must
5
+ # not run where company repositories are readable (scripts/agy_launch_guard.sh). This runner never
6
+ # starts agy locally: it copies the prompt and the frozen inputs into a fresh work folder in the remote
7
+ # user's home, runs agy there, streams its output back, copies requested files back, and removes only
8
+ # that work folder. If the route is not available it REFUSES — it never falls back to a local agy.
9
+ #
10
+ # REMOTE. A Windows machine reached by OpenSSH, logged in as a non-admin user whose profile cannot read
11
+ # the other profiles (measure that with --canary; do not assume it). agy installed for that user
12
+ # (default %LOCALAPPDATA%\agy\bin\agy.exe). Configuration comes only from the environment — this public
13
+ # file names no host, account or path:
14
+ # FH_AGY_REMOTE ssh target, e.g. user@host (required)
15
+ # FH_AGY_REMOTE_DENY ;-separated remote paths the user must NOT read (required for --canary); only an
16
+ # access-denied error counts, unless the entry starts with ? (then not-found is accepted too)
17
+ # FH_AGY_REMOTE_AGY remote agy path (default: %LOCALAPPDATA%\agy\bin\agy.exe)
18
+ # FH_AGY_REMOTE_RECEIPT_DIR local receipt folder (default: $HOME/.cache/fh-agy-remote — outside any repo)
19
+ #
20
+ # CANARY. `agy_remote_run.sh --canary` runs NO agy. As the remote user it tries to list or open every
21
+ # FH_AGY_REMOTE_DENY path (each must be refused) and reads a file it writes in a fresh work folder (must
22
+ # succeed), then writes a local receipt: receipt_<first 16 of sha256(target, deny list, agy path)>.txt
23
+ # with key=value lines (verdict, target_sha, epoch, denied=N/N, positive) and one line per path.
24
+ # A run is refused unless that receipt says PASS, is under 7 days old and matches the current settings.
25
+ # 🟥 The receipt records this script's own measurement on the day it ran; it is not proof of isolation.
26
+ # 🟥 A deny on a drive or folder root does NOT override an explicit allow entry on a sub-item: on the
27
+ # operator's machine (2026-11-16) the remote user could still list or open 8 such sub-items (game
28
+ # folders, the recycle bins, an antivirus decoy folder, three device-information files), which the
29
+ # operator accepted. The canary only measures the paths you list — list a sub-item only after you
30
+ # have denied it explicitly, and name the accepted ones where you record the receipt.
31
+ #
32
+ # USAGE (agy-compatible; extra flags are this runner's own and are not passed to agy):
33
+ # agy_remote_run.sh [--input <file>]... [--fetch <name>]... [--fetch-dir <dir>] -p "<prompt>" [agy flags...]
34
+ # agy_remote_run.sh --canary
35
+ # Inputs are copied under their own names ([A-Za-z0-9._-] only, no duplicates). The remote agy gets
36
+ # `--settings` limiting it to its workspace (allowNonWorkspaceAccess=false); the OS user is the barrier.
37
+ # Through FH's scripts: FH_AGY_BIN=<repo>/scripts/agy_remote_run.sh FH_AGY_ISOLATION=remote-os-user.
38
+ #
39
+ # EXIT: 0 ok · 1 remote agy exited non-zero (AGY_RC=<n> on stderr) · 2 usage · 3 refused (no target,
40
+ # no/stale/FAIL/mismatched receipt) · 4 route unavailable (ssh/scp failed) · 5 cleanup not verified
41
+ # --canary: 0 PASS · 1 FAIL · 2 usage · 4 route unavailable
42
+ set -uo pipefail
43
+ SSH=ssh; SCP=scp # by name from PATH; there is no override (the lanes put fakes first on PATH)
44
+ die() { echo "agy_remote_run: $2" >&2; exit "$1"; }
45
+ TARGET="${FH_AGY_REMOTE-}"
46
+ [ -n "$TARGET" ] || die 3 "AGY-REMOTE-REFUSED: FH_AGY_REMOTE is not set — refusing (agy is never started locally)"
47
+ case "$TARGET" in *[!A-Za-z0-9@._-]*) die 2 "FH_AGY_REMOTE must look like user@host" ;; esac
48
+ RAGY="${FH_AGY_REMOTE_AGY:-%LOCALAPPDATA%\\agy\\bin\\agy.exe}"
49
+ case "$RAGY" in *[!A-Za-z0-9%\\:._\ -]*) die 2 "FH_AGY_REMOTE_AGY may contain only letters, digits, % \\ : . _ - and spaces" ;; esac
50
+ DENY="${FH_AGY_REMOTE_DENY-}"
51
+ RDIR="${FH_AGY_REMOTE_RECEIPT_DIR:-$HOME/.cache/fh-agy-remote}"
52
+ case "$DENY$RAGY" in *$'\n'*|*$'\r'*) die 2 "FH_AGY_REMOTE_DENY / FH_AGY_REMOTE_AGY must not contain line breaks" ;; esac
53
+ # length-prefixed fields: no two different settings can produce the same hashed text
54
+ TSHA="$(printf 'v1|%d:%s|%d:%s|%d:%s' "${#TARGET}" "$TARGET" "${#DENY}" "$DENY" "${#RAGY}" "$RAGY" | shasum -a 256 2>/dev/null | cut -c1-64)"
55
+ printf '%s' "$TSHA" | grep -Eq '^[0-9a-f]{64}$' || die 4 "could not compute the settings hash (shasum) — refusing"
56
+ RECEIPT="$RDIR/receipt_${TSHA:0:16}.txt"
57
+ SSHO=(-o BatchMode=yes -o ConnectTimeout=15)
58
+ WD="fh_agy_$(date +%Y%m%d%H%M%S)_$(od -An -N3 -tx1 /dev/urandom | tr -d ' \n')"
59
+ LOCAL="$(mktemp -d "${TMPDIR:-/tmp}/fh_agy_remote.XXXXXX")" || die 4 "cannot create a local temp folder"
60
+ trap 'rm -rf "$LOCAL"' EXIT
61
+
62
+ remote_mkdir() { "$SSH" "${SSHO[@]}" "$TARGET" "mkdir $WD" </dev/null >/dev/null 2>&1; }
63
+ remote_put() { "$SCP" -q "${SSHO[@]}" "$@" "$TARGET:$WD/" </dev/null >/dev/null 2>&1; }
64
+ remote_ps() { "$SSH" "${SSHO[@]}" "$TARGET" "powershell -NoProfile -ExecutionPolicy Bypass -File $WD\\$1" </dev/null; }
65
+ remote_cleanup() { # only the folder this run created; the remote script re-checks the name and parent
66
+ cat > "$LOCAL/cleanup.ps1" <<'PS'
67
+ $n = Split-Path -Leaf $PSScriptRoot
68
+ $parent = Split-Path -Parent $PSScriptRoot
69
+ if ($n -notmatch '^fh_agy_[0-9]{14}_[0-9a-f]{6}$' -or $parent -ne $env:USERPROFILE) { "CLEANUP-REFUSED $n"; exit 3 }
70
+ Set-Location $env:USERPROFILE; Remove-Item -LiteralPath $PSScriptRoot -Recurse -Force
71
+ if (Test-Path -LiteralPath $PSScriptRoot) { "CLEANUP-FAILED"; exit 5 } else { "CLEANUP-OK" }
72
+ PS
73
+ remote_put "$LOCAL/cleanup.ps1" || return 5
74
+ local co; co="$(remote_ps cleanup.ps1 2>/dev/null)" # capture first: no early-exit reader on a pipe
75
+ case "$(printf '%s' "$co" | tr -d '\r')" in CLEANUP-OK|*$'\n'CLEANUP-OK) return 0 ;; *) return 5 ;; esac
76
+ }
77
+ # An interrupt after the remote folder exists still removes it (only this run's folder, re-checked remotely).
78
+ CREATED=0
79
+ on_signal() { trap - INT TERM; [ "$CREATED" = 1 ] && remote_cleanup; echo "agy_remote_run: interrupted" >&2; exit 130; }
80
+ trap on_signal INT TERM
81
+
82
+ if [ "${1-}" = "--canary" ]; then
83
+ [ $# -eq 1 ] || die 2 "--canary takes no other arguments"
84
+ [ -n "$DENY" ] || die 2 "FH_AGY_REMOTE_DENY is empty — a canary with nothing to deny measures nothing"
85
+ printf '%s\n' "$DENY" | tr ';' '\n' | sed '/^$/d' > "$LOCAL/deny.txt"
86
+ cat > "$LOCAL/canary.ps1" <<'PS'
87
+ foreach ($p in Get-Content -LiteralPath (Join-Path $PSScriptRoot 'deny.txt') -Encoding UTF8) {
88
+ $absentOk = $p.StartsWith('?'); if ($absentOk) { $p = $p.Substring(1) }
89
+ try { $i = Get-Item -LiteralPath $p -Force -ErrorAction Stop
90
+ if ($i.PSIsContainer) { [void](Get-ChildItem -LiteralPath $p -Force -ErrorAction Stop) } else { [IO.File]::OpenRead($p).Close() }
91
+ "DENY-FAIL $p (readable)" }
92
+ catch { $x = $_.Exception; $e = $x.GetType().Name # walk wrapped errors (OpenRead wraps its own)
93
+ while ($null -ne $x.InnerException) { $x = $x.InnerException; $e = $e + '/' + $x.GetType().Name }
94
+ if ($e -match 'UnauthorizedAccess' -or ($absentOk -and $e -match 'NotFound')) { "DENY-OK $p ($e)" }
95
+ else { "DENY-FAIL $p (not measured: $e)" } } }
96
+ $f = Join-Path $PSScriptRoot 'positive.txt'; Set-Content -LiteralPath $f -Value 'FH-POSITIVE'
97
+ try { if ((Get-Content -LiteralPath $f -Raw).Trim() -eq 'FH-POSITIVE') { 'POS-OK' } else { 'POS-FAIL' } } catch { 'POS-FAIL' }
98
+ PS
99
+ remote_mkdir || die 4 "AGY-REMOTE-UNAVAILABLE: cannot reach $TARGET (mkdir failed)"
100
+ CREATED=1
101
+ remote_put "$LOCAL/deny.txt" "$LOCAL/canary.ps1" || { remote_cleanup; die 4 "AGY-REMOTE-UNAVAILABLE: copy to $TARGET failed"; }
102
+ out="$(remote_ps canary.ps1 2>&1)"; prc=$?; out="$(printf '%s' "$out" | tr -d '\r')"
103
+ remote_cleanup; crc=$?
104
+ want=$(grep -c '' "$LOCAL/deny.txt")
105
+ ok=$(printf '%s\n' "$out" | grep -c '^DENY-OK ')
106
+ bad=$(printf '%s\n' "$out" | grep -c '^DENY-FAIL ')
107
+ pos=$(printf '%s\n' "$out" | grep -q '^POS-OK$' && echo READ || echo FAIL)
108
+ verdict=FAIL; [ "$ok" -eq "$want" ] && [ "$bad" -eq 0 ] && [ "$pos" = READ ] && [ "$want" -gt 0 ] && [ "$crc" -eq 0 ] && [ "$prc" -eq 0 ] && verdict=PASS
109
+ mkdir -p "$RDIR" || die 4 "cannot create $RDIR"
110
+ { echo "verdict=$verdict"; echo "target_sha=$TSHA"; echo "epoch=$(date +%s)"; echo "denied=$ok/$want"
111
+ echo "positive=$pos"; echo "cleanup=$([ "$crc" -eq 0 ] && echo OK || echo UNVERIFIED)"
112
+ printf '%s\n' "$out" | grep -E '^(DENY-OK|DENY-FAIL|POS-OK|POS-FAIL)'; } > "$RECEIPT.tmp" && mv "$RECEIPT.tmp" "$RECEIPT" \
113
+ || die 4 "could not write the receipt $RECEIPT — the canary result is not recorded"
114
+ echo "AGY-REMOTE-CANARY $verdict denied=$ok/$want positive=$pos receipt=$RECEIPT"
115
+ [ "$verdict" = PASS ] && exit 0 || exit 1
116
+ fi
117
+
118
+ # ── run mode: receipt first, then the route ───────────────────────────────────────────────────────
119
+ [ -f "$RECEIPT" ] || die 3 "AGY-REMOTE-REFUSED: no canary receipt for these settings — run: agy_remote_run.sh --canary"
120
+ r_get() { sed -n "s/^$1=//p" "$RECEIPT" | sed -n 1p; } # first value only; sed reads to the end
121
+ [ "$(r_get verdict)" = PASS ] || die 3 "AGY-REMOTE-REFUSED: the last canary did not pass ($RECEIPT)"
122
+ [ "$(r_get target_sha)" = "$TSHA" ] || die 3 "AGY-REMOTE-REFUSED: receipt is for different settings"
123
+ age=$(( $(date +%s) - $(r_get epoch | grep -E '^[0-9]+$' || echo 0) ))
124
+ [ "$age" -le 604800 ] || die 3 "AGY-REMOTE-REFUSED: canary receipt is older than 7 days — run --canary again"
125
+ [ "$age" -ge 0 ] || die 3 "AGY-REMOTE-REFUSED: canary receipt is dated in the future — run --canary again"
126
+
127
+ PROMPT=""; HAVEP=0; INPUTS=(); FETCH=(); FDIR=""; PASS=()
128
+ while [ $# -gt 0 ]; do
129
+ case "$1" in
130
+ --input) [ $# -ge 2 ] || die 2 "--input needs a file"; INPUTS+=("$2"); shift 2 ;;
131
+ --fetch) [ $# -ge 2 ] || die 2 "--fetch needs a name"
132
+ [ "$2" = "$(basename "$2")" ] || die 2 "--fetch takes a bare file name inside the work folder, not a path: $2"
133
+ FETCH+=("$2"); shift 2 ;;
134
+ --fetch-dir) [ $# -ge 2 ] || die 2 "--fetch-dir needs a folder"; FDIR="$2"; shift 2 ;;
135
+ -p|--print|--prompt) [ $# -ge 2 ] || die 2 "$1 needs a prompt"; PROMPT="$2"; HAVEP=1; shift 2 ;;
136
+ --settings) die 2 "--settings is set by this runner (workspace-only); remove it" ;;
137
+ *) case "$1" in *$'\n'*) die 2 "an agy argument contains a newline" ;; esac; PASS+=("$1"); shift ;;
138
+ esac
139
+ done
140
+ [ "$HAVEP" -eq 1 ] || die 2 "a prompt is required (-p)"
141
+ [ "${#FETCH[@]}" -eq 0 ] || [ -n "$FDIR" ] || die 2 "--fetch needs --fetch-dir"
142
+ seen=" "
143
+ for f in ${INPUTS[@]+"${INPUTS[@]}"} ${FETCH[@]+"${FETCH[@]}"}; do
144
+ b="$(basename "$f")"
145
+ lb="$(printf '%s' "$b" | tr 'A-Z' 'a-z')" # Windows names are case-insensitive
146
+ case "$b" in ''|*[!A-Za-z0-9._-]*) die 2 "file name not allowed: $b" ;; esac
147
+ case "$lb" in prompt.txt|args.txt|settings.json|run.ps1|cleanup.ps1|agy_path.txt|canary.ps1|deny.txt) die 2 "file name reserved by the runner: $b" ;; esac
148
+ done
149
+ for f in ${INPUTS[@]+"${INPUTS[@]}"}; do
150
+ [ -f "$f" ] || die 2 "input not found: $f"
151
+ b="$(basename "$f" | tr 'A-Z' 'a-z')"; case "$seen" in *" $b "*) die 2 "two inputs share the name $b (Windows ignores case)" ;; esac; seen="$seen$b "
152
+ done
153
+ printf '%s' "$PROMPT" > "$LOCAL/prompt.txt"
154
+ : > "$LOCAL/args.txt"; for a in ${PASS[@]+"${PASS[@]}"}; do printf '%s\n' "$a" >> "$LOCAL/args.txt"; done
155
+ printf '{"toolPermission":"always-proceed","allowNonWorkspaceAccess":false}\n' > "$LOCAL/settings.json"
156
+ printf '%s' "$RAGY" > "$LOCAL/agy_path.txt"
157
+ cat > "$LOCAL/run.ps1" <<'PS'
158
+ Set-Location $PSScriptRoot
159
+ $p = Get-Content -LiteralPath 'prompt.txt' -Raw -Encoding UTF8
160
+ $a = @(Get-Content -LiteralPath 'args.txt' -Encoding UTF8 | Where-Object { $_ -ne '' })
161
+ $agy = [Environment]::ExpandEnvironmentVariables((Get-Content -LiteralPath 'agy_path.txt' -Raw -Encoding UTF8).Trim())
162
+ & $agy -p $p @a --settings (Join-Path $PSScriptRoot 'settings.json')
163
+ # printed after agy has exited: the runner trusts only the LAST line, which agy's output cannot follow
164
+ $rc = $LASTEXITCODE
165
+ "FH_AGY_RC=$rc"
166
+ exit $rc # the ssh exit status carries the same code, which nothing agy leaves behind can rewrite
167
+ PS
168
+ remote_mkdir || die 4 "AGY-REMOTE-UNAVAILABLE: cannot reach $TARGET (mkdir failed) — not falling back to a local agy"
169
+ CREATED=1
170
+ remote_put "$LOCAL/prompt.txt" "$LOCAL/args.txt" "$LOCAL/settings.json" "$LOCAL/agy_path.txt" "$LOCAL/run.ps1" ${INPUTS[@]+"${INPUTS[@]}"} \
171
+ || { remote_cleanup; die 4 "AGY-REMOTE-UNAVAILABLE: copy to $TARGET failed"; }
172
+ remote_ps run.ps1 > "$LOCAL/out.txt" 2> "$LOCAL/err.txt"; src=$?
173
+ tr -d '\r' < "$LOCAL/out.txt" | sed '$ { /^FH_AGY_RC=/d; }'; tr -d '\r' < "$LOCAL/err.txt" >&2
174
+ last="$(tr -d '\r' < "$LOCAL/out.txt" | sed '/^$/d' | tail -1)"
175
+ arc="$(printf '%s' "$last" | sed -n 's/^FH_AGY_RC=\(-\{0,1\}[0-9][0-9]*\)$/\1/p')"
176
+ frc=0
177
+ for n in ${FETCH[@]+"${FETCH[@]}"}; do
178
+ mkdir -p "$FDIR" && "$SCP" -q "${SSHO[@]}" "$TARGET:$WD/$n" "$FDIR/" </dev/null >/dev/null 2>&1 || { echo "agy_remote_run: could not fetch $n" >&2; frc=4; }
179
+ done
180
+ remote_cleanup || { echo "agy_remote_run: remote work folder $WD not confirmed removed" >&2; exit 5; }
181
+ [ -n "$arc" ] || { echo "agy_remote_run: no exit code came back from the remote side (ssh exited $src) — route failed" >&2; exit 4; }
182
+ # success needs BOTH: the printed code and the ssh exit status agree (a line printed later by a leftover
183
+ # child cannot change the exit status; an ssh failure cannot print the line)
184
+ [ "$src" = "$(( arc & 255 ))" ] || { echo "agy_remote_run: ssh exited $src but the remote printed FH_AGY_RC=$arc — route or output not trusted" >&2; exit 4; }
185
+ [ "$frc" -eq 0 ] || exit 4
186
+ [ "$arc" = 0 ] && exit 0
187
+ echo "AGY_RC=$arc" >&2; exit 1
@@ -64,6 +64,11 @@ FILE_FAILED=0 # 현재 capfile 한정 — 파일마다 초기화한다. 이게
64
64
  # 뒤 파일의 M4 를 SKIPPED 로 만들어, 뒤 파일의 실제 결함이 안 보인다(보고 결함).
65
65
  _fail() { printf ' ❌ %s — %s\n' "$1" "$2"; FAILED=1; FILE_FAILED=1; }
66
66
  _ok() { printf ' ✅ %s — %s\n' "$1" "$2"; }
67
+ # _has <haystack> <fixed-needle> — substring test with NO pipe. Under `set -o pipefail` (line 49)
68
+ # `printf "$big" | grep -q x` returns 141 whenever grep exits on the first match before printf has
69
+ # written everything (SIGPIPE on the writer) — a timing race that made --self-test go red ~5% of
70
+ # runs under parallel load (2026-11-14: 7/144 at 24-way). A here-string has no writer to kill.
71
+ _has() { grep -qF -- "$2" <<<"$1"; }
67
72
  _die() { printf '❌ HARNESS_ERROR: %s\n' "$*" >&2; exit "$RC_HARNESS"; }
68
73
 
69
74
  _parse() {
@@ -495,6 +500,14 @@ _self_test() {
495
500
  else fail=$((fail+1)); printf ' ❌ %-34s rc=%s (기대 %s)\n%s\n' "$1" "$r" "$2" "$o"; fi
496
501
  }
497
502
  printf 'capability_registry_check --self-test\n'
503
+ # P0: the matcher itself. Needle first, then >1 MiB after it — a piped `grep -q` exits on line 1
504
+ # and the writer dies of SIGPIPE, which pipefail turns into «not found». Known-positive (needle
505
+ # present → hit) and known-negative (absent → miss), so a matcher that always says yes is red too.
506
+ local _big; _big="NEEDLE-P0"$'\n'"$(head -c 1200000 /dev/zero | tr '\0' x)"
507
+ if _has "$_big" "NEEDLE-P0"; then pass=$((pass+1)); printf ' ✅ %-34s\n' "P0: 큰 출력 앞머리 매치(파이프 경합 없음)"
508
+ else fail=$((fail+1)); printf ' ❌ %-34s — 있는 문자열을 못 찾았다(파이프+pipefail SIGPIPE 형태)\n' "P0: 큰 출력 앞머리 매치"; fi
509
+ if _has "$_big" "ABSENT-P0"; then fail=$((fail+1)); printf ' ❌ %-34s — 없는 문자열을 찾았다고 했다\n' "P0: 컨트롤(없는 문자열)"
510
+ else pass=$((pass+1)); printf ' ✅ %-34s\n' "P0: 컨트롤(없는 문자열은 미스)"; fi
498
511
  cat > "$T/good.cap" <<EOF
499
512
  id: selftest:true-false
500
513
  entry: bash $T/probe.sh
@@ -585,7 +598,7 @@ LIAR
585
598
  # ★rc 만 보면 **어느 축이 막았는지** 모른다 — M6 를 재려면 M6 가 실패했다고 말해야 한다.
586
599
  CRC_DEBUG_OUT=$(bash "$0" "$T/liar.cap" 2>&1)
587
600
  [ -n "${CRC_DEBUG:-}" ] && printf '%s\n' "$CRC_DEBUG_OUT" >&2
588
- if printf '%s' "$CRC_DEBUG_OUT" | grep -q '❌ M6'; then
601
+ if _has "$CRC_DEBUG_OUT" '❌ M6'; then
589
602
  pass=$((pass+1)); printf ' ✅ %-34s (M6 가 차단자임을 확인)\n' "M6: 차단 귀속"
590
603
  else
591
604
  fail=$((fail+1)); printf ' ❌ %-34s — rc 는 1 인데 M6 가 막은 게 아니다(다른 축이 먼저 걸렸다)\n' "M6: 차단 귀속"
@@ -595,7 +608,7 @@ LIAR
595
608
  # «채널이 켜져 있나 · 계산이 맞나 · 조건부로 꺼지지 않나» 셋이다.
596
609
  _tg() { # $1=이름 $2=기대 rc $3=capfile $4=반드시 포함할 문자열
597
610
  local o r hit; o="$(bash "$0" "$3" 2>&1)"; r=$?
598
- if printf '%s' "$o" | grep -qF "$4"; then hit=1; else hit=0; fi
611
+ if _has "$o" "$4"; then hit=1; else hit=0; fi
599
612
  if [ "$r" = "$2" ] && [ "$hit" = "1" ]; then
600
613
  pass=$((pass+1)); printf ' ✅ %-34s rc=%s\n' "$1" "$r"
601
614
  else
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bash
2
+ # codex_launch_guard.sh — FH starts codex through here. Lighter than agy_launch_guard.sh: codex is allowed
3
+ # on this machine, but never on company-repo material.
4
+ #
5
+ # WHY. codex `--sandbox read-only` limits writes, not reads: measured 2026-11-16 with canary files, it read
6
+ # paths in its cwd, in another temp folder and in the home directory. Whatever it reads goes to the cloud
7
+ # model. So a codex arm may only be handed public material, and this guard refuses the obvious leak: a
8
+ # prompt, an argument or a working folder that names a configured company-repo root.
9
+ #
10
+ # LIST. Company-repo roots, one absolute path per line, from FH_COMPANY_ROOTS (newline- or ':'-separated)
11
+ # or else the file FH_COMPANY_ROOTS_FILE (default: <repo>/.claude/rules/.company-roots, gitignored; '#'
12
+ # comments and blank lines ignored). No root path appears in any public file.
13
+ #
14
+ # MATCH. A root matches when it appears as a path in the prompt (stdin) or an argument — the root string
15
+ # followed by '/', end of text, or a character that cannot continue a path name — in any of three spellings:
16
+ # as given, its real path, with a leading /private removed (macOS /tmp = /private/tmp), and with $HOME
17
+ # written as '~'. Case-sensitive. The working folder matches when its real path is the root or below it.
18
+ # NOT matched: a relative path, file content pasted without its path, or an encoded path — the guard is a
19
+ # string check, not isolation. Not reached: a caller that starts codex by absolute path around this guard
20
+ # (finding_fleet routes CODEX_BIN and bare `codex` through a PATH shim; an absolute path skips it).
21
+ #
22
+ # UNCONFIGURED. No list, or an empty one: codex runs and the guard prints «CODEX-GUARD: no company roots
23
+ # configured — not checked» on stderr. That is said out loud, never shown as clean.
24
+ #
25
+ # Usage: bash scripts/codex_launch_guard.sh <codex-binary> [codex arguments...] (prompt on stdin)
26
+ # Exit: 3 = refused (codex not started; stderr starts «HARNESS-ERROR: CODEX-REFUSED») · 2 = usage
27
+ # · otherwise codex's own exit code (a codex exit of 3 is told apart by the missing CODEX-REFUSED line)
28
+ set -uo pipefail
29
+ [ $# -ge 1 ] || { echo "usage: codex_launch_guard.sh <codex-binary> [codex arguments...]" >&2; exit 2; }
30
+ _here="$(cd "$(dirname "$0")" && pwd -P)"
31
+ _rootsfile="${FH_COMPANY_ROOTS_FILE:-$_here/../.claude/rules/.company-roots}"
32
+ _tmp="$(mktemp "${TMPDIR:-/tmp}/fh_codex_prompt.XXXXXX")" || { echo "HARNESS-ERROR: codex_launch_guard cannot create a temp file — codex not started" >&2; exit 3; }
33
+ trap 'rm -f "$_tmp"' EXIT
34
+ if [ -t 0 ]; then : > "$_tmp"; else cat > "$_tmp"; fi
35
+ _verdict="$(FH_GUARD_PROMPT="$_tmp" FH_GUARD_ROOTS_FILE="$_rootsfile" python3 - "${@:2}" <<'PY'
36
+ import os, re, sys
37
+ def roots():
38
+ env = os.environ.get("FH_COMPANY_ROOTS")
39
+ if env is not None and env.strip():
40
+ raw = re.split(r"[\n:]", env)
41
+ else:
42
+ try: raw = open(os.environ["FH_GUARD_ROOTS_FILE"], encoding="utf-8").read().splitlines()
43
+ except FileNotFoundError: raw = [] # no list at all: unconfigured, said out loud
44
+ except OSError as e: # a list that exists but cannot be read: refuse
45
+ print("ERROR the company-roots file exists but cannot be read (%s)" % type(e).__name__); sys.exit(0)
46
+ out = []
47
+ for r in raw:
48
+ r = r.strip()
49
+ if r and not r.startswith("#"): out.append(r.rstrip("/"))
50
+ return out
51
+ R = roots()
52
+ if not R:
53
+ print("UNCONFIGURED"); sys.exit(0)
54
+ home = os.path.expanduser("~").rstrip("/")
55
+ def spellings(r):
56
+ s = {r}
57
+ try: s.add(os.path.realpath(r).rstrip("/"))
58
+ except OSError: pass
59
+ for x in list(s):
60
+ if x.startswith("/private/"): s.add(x[len("/private"):])
61
+ if home and (x == home or x.startswith(home + "/")): s.add("~" + x[len(home):])
62
+ return [x for x in s if x]
63
+ pats = []
64
+ for r in R:
65
+ for sp in spellings(r):
66
+ pats.append(re.compile(re.escape(sp) + r"(?=/|$|[^A-Za-z0-9._\-~])"))
67
+ def hit(text): return any(p.search(text) for p in pats)
68
+ where = []
69
+ try: prompt = open(os.environ["FH_GUARD_PROMPT"], encoding="utf-8", errors="replace").read()
70
+ except OSError: print("ERROR cannot read the prompt"); sys.exit(0)
71
+ if hit(prompt): where.append("prompt")
72
+ if any(hit(a) for a in sys.argv[1:]): where.append("argument")
73
+ cwd = os.path.realpath(os.getcwd())
74
+ for r in R:
75
+ rr = os.path.realpath(r)
76
+ if cwd == rr or cwd.startswith(rr.rstrip("/") + "/"): where.append("working folder"); break
77
+ print("REFUSE " + ",".join(where) if where else "OK")
78
+ PY
79
+ )" || _verdict="ERROR the matcher failed"
80
+ case "$_verdict" in
81
+ OK) ;;
82
+ UNCONFIGURED) echo "CODEX-GUARD: no company roots configured — not checked (set FH_COMPANY_ROOTS or $_rootsfile)" >&2 ;;
83
+ REFUSE*) echo "HARNESS-ERROR: CODEX-REFUSED — a company-repo root appears in the ${_verdict#REFUSE }; codex was not started. Send codex public material only." >&2; exit 3 ;;
84
+ *) echo "HARNESS-ERROR: CODEX-REFUSED — codex_launch_guard could not check (${_verdict}); codex was not started." >&2; exit 3 ;;
85
+ esac
86
+ exec 3<"$_tmp"; rm -f "$_tmp"; trap - EXIT
87
+ exec "$@" <&3 3<&-
@@ -31,7 +31,40 @@ HERE="$(cd "$(dirname "$0")" && pwd)"
31
31
  # this file ships in the npm package and a literal home directory is both a leak and wrong on the
32
32
  # consumer's machine. Override with FH_CODEX_BIN / FH_AGY_BIN.
33
33
  CODEX="${FH_CODEX_BIN:-$(command -v codex 2>/dev/null || echo "$HOME/.npm-global/bin/codex")}"
34
+ # A function named agy (exported into this shell) would outrank PATH and fool `command -v`: drop it first.
35
+ unset -f agy codex 2>/dev/null || true
34
36
  AGY="${FH_AGY_BIN:-$(command -v agy 2>/dev/null || echo "$HOME/.local/bin/agy")}"
37
+ # Every agy launch goes through the isolation guard (refuses unless FH_AGY_ISOLATION=container|os-user).
38
+ # How: a shim named `agy` in a private temp dir is put FIRST on PATH, and the fleet token AGY_BIN
39
+ # becomes that shim's path. So a default row, a custom row that writes AGY_BIN (quoted or not, under
40
+ # `timeout`/`env`), and a custom row that calls `agy` by name all reach the guard; and no path chosen by
41
+ # the caller is pasted into the eval'd string (a directory name with `&` or PROMPT_FILE in it cannot
42
+ # break it). Named residual: a row that calls agy by ABSOLUTE path, or resets PATH, skips the shim.
43
+ AGY_GUARD="$HERE/agy_launch_guard.sh"
44
+ # A bare name (FH_AGY_BIN=agy) would resolve back to the shim once PATH is changed: pin it to a path now.
45
+ case "$AGY" in */*) ;; *) AGY="$(command -v -- "$AGY" 2>/dev/null || echo "/nonexistent/$AGY")" ;; esac
46
+ case "$AGY" in */fh_agy_shim.*/agy) AGY="${FH_AGY_REAL:-$AGY}" ;; esac # nested run: keep the real binary
47
+ # codex gets the same shim treatment, through the lighter codex_launch_guard.sh (refuses company-root paths)
48
+ case "$CODEX" in */*) ;; *) CODEX="$(command -v -- "$CODEX" 2>/dev/null || echo "/nonexistent/$CODEX")" ;; esac
49
+ case "$CODEX" in */fh_agy_shim.*/codex) CODEX="${FH_CODEX_REAL:-$CODEX}" ;; esac
50
+ CODEX_GUARD="$HERE/codex_launch_guard.sh"
51
+ AGY_SHIM_DIR="$(mktemp -d /tmp/fh_agy_shim.XXXXXX 2>/dev/null)" && [ -d "$AGY_SHIM_DIR" ] || {
52
+ echo "finding_fleet: cannot create the agy shim directory — refusing to run (agy would be unguarded)" >&2; exit 1; }
53
+ trap 'rm -rf "$AGY_SHIM_DIR"' EXIT
54
+ printf '#!/usr/bin/env bash\nexec bash "$FH_AGY_GUARD_PATH" "$FH_AGY_REAL" "$@"\n' > "$AGY_SHIM_DIR/agy"
55
+ chmod +x "$AGY_SHIM_DIR/agy"
56
+ printf '#!/usr/bin/env bash\nexec bash "$FH_CODEX_GUARD_PATH" "$FH_CODEX_REAL" "$@"\n' > "$AGY_SHIM_DIR/codex"
57
+ chmod +x "$AGY_SHIM_DIR/codex"
58
+ export FH_CODEX_GUARD_PATH="$CODEX_GUARD" FH_CODEX_REAL="$CODEX"
59
+ export FH_AGY_GUARD_PATH="$AGY_GUARD" FH_AGY_REAL="$AGY"
60
+ # The shim must actually run here (a noexec /tmp would make a bare `agy` fall through to the real one):
61
+ # run it once with the marker cleared — it must come back from the guard as a refusal, nothing else.
62
+ _shim_probe="$(FH_AGY_ISOLATION= "$AGY_SHIM_DIR/agy" --version 2>&1 </dev/null)"; _shim_rc=$?
63
+ case "$_shim_probe" in AGY-REFUSED*) _shim_said=1 ;; *) _shim_said=0 ;; esac # no early-exit reader on a pipe
64
+ if [ "$_shim_rc" -ne 3 ] || [ "$_shim_said" -ne 1 ]; then
65
+ echo "finding_fleet: the agy shim did not run (rc=$_shim_rc) — refusing to run (agy would be unguarded)" >&2; exit 1
66
+ fi
67
+ export PATH="$AGY_SHIM_DIR:$PATH"
35
68
 
36
69
  default_fleet() {
37
70
  cat <<'EOF'
@@ -92,7 +125,7 @@ DROPPED: lines. Your assigned area is unchanged: '
92
125
  run_member_r2() { # $1=family $2=role $3=command $4=target $5=outdir
93
126
  local fam="$1" role="$2" cmd="$3" tgt="$4" out="$5"
94
127
  local q_codex q_agy q_pf
95
- q_codex="$(printf '%q' "$CODEX")"; q_agy="$(printf '%q' "$AGY")"
128
+ q_codex="$(printf '%q' "$AGY_SHIM_DIR/codex")"; q_agy="$(printf '%q' "$AGY_SHIM_DIR/agy")"
96
129
  cmd="${cmd//CODEX_BIN/$q_codex}"; cmd="${cmd//AGY_BIN/$q_agy}"
97
130
  local raw="$out/raw2_${fam}_${role}.txt" pf="$out/prompt2_${fam}_${role}.txt"
98
131
  for _p in "$raw" "$pf" "$out/err2_${fam}_${role}.txt" "$out/part2_${fam}_${role}.jsonl" "$out/peer_${fam}_${role}.txt"; do
@@ -292,7 +325,7 @@ run_member() { # $1=family $2=role $3=command $4=target $5=outdir
292
325
  # 여기는 bash `eval` 이므로 `printf %q` 가 옳은 도구다(shell=True 로 /bin/sh 에 넘기는
293
326
  # finding_pipeline.sh 와는 사정이 다르다 — 거기서는 %q 가 dash 에서 깨져서 argv 로 갔다).
294
327
  local q_codex q_agy q_pf
295
- q_codex="$(printf '%q' "$CODEX")"; q_agy="$(printf '%q' "$AGY")"
328
+ q_codex="$(printf '%q' "$AGY_SHIM_DIR/codex")"; q_agy="$(printf '%q' "$AGY_SHIM_DIR/agy")"
296
329
  cmd="${cmd//CODEX_BIN/$q_codex}"; cmd="${cmd//AGY_BIN/$q_agy}"
297
330
  local raw="$out/raw_${fam}_${role}.txt" pf="$out/prompt_${fam}_${role}.txt"
298
331
  # 🟥 심링크를 통해 쓰면 남의 파일을 덮는다. 그리고 타깃이 심링크면 그 «내용»이 외부로 나간다.
@@ -20,6 +20,10 @@ set -uo pipefail
20
20
 
21
21
  CODEX="${FH_CODEX_BIN:-$(command -v codex 2>/dev/null || echo "$HOME/.npm-global/bin/codex")}"
22
22
  AGY="${FH_AGY_BIN:-$(command -v agy 2>/dev/null || echo "$HOME/.local/bin/agy")}"
23
+ # Every agy launch goes through the isolation guard (refuses unless FH_AGY_ISOLATION=container|os-user).
24
+ AGY_GUARD="$(cd "$(dirname "$0")" && pwd)/agy_launch_guard.sh"
25
+ # codex goes through the lighter guard: refused when the prompt, an argument or the cwd names a company root
26
+ CODEX_GUARD="$(cd "$(dirname "$0")" && pwd)/codex_launch_guard.sh"
23
27
 
24
28
  FAMILY=""; TARGET=""; MODE="verify"; KEEP=""
25
29
  # 호출자(파이프라인)가 env 로 보존 경로를 줄 수 있다 — 검증 패스의 CLI stderr(토큰 회계)가 여기서 산다.
@@ -122,9 +126,9 @@ if ! grep -q "===== FILE: $(basename "$TARGET") =====" "$WORK/prompt.txt"; then
122
126
  fi
123
127
 
124
128
  case "$FAMILY" in
125
- codex) "$CODEX" exec --sandbox read-only --skip-git-repo-check -m gpt-6-astra \
129
+ codex) bash "$CODEX_GUARD" "$CODEX" exec --sandbox read-only --skip-git-repo-check -m gpt-6-astra \
126
130
  -c model_reasoning_effort="high" < "$WORK/prompt.txt" > "$WORK/raw.txt" 2>"$WORK/err.txt" ;;
127
- gemini) "$AGY" --mode plan --sandbox --model gemini-3.8-flash-high --output-format text --print-timeout 20m \
131
+ gemini) bash "$AGY_GUARD" "$AGY" --mode plan --sandbox --model gemini-3.8-flash-high --output-format text --print-timeout 20m \
128
132
  -p "$(cat "$WORK/prompt.txt")" < /dev/null > "$WORK/raw.txt" 2>"$WORK/err.txt" ;;
129
133
  *) echo "finding_verifier: unknown family '$FAMILY' (codex|gemini)" >&2; exit 2 ;;
130
134
  esac
@@ -253,6 +253,36 @@ def heading_dense(path, common=None, st=None):
253
253
  return out
254
254
 
255
255
 
256
+ # ── S35 낱말 뜻 흔들림 — (a) 기계 단계: 가벼운 동사·명사의 «모든 등장»을 활용형까지 문맥과 함께 늘어놓는다.
257
+ # 🟥 이 함수는 뜻을 가르지 않는다. 뜻 묶기(b)는 판단이다 — 사람 또는 모델이 낱말마다 등장을 뜻별로 묶고 소수 뜻을 표시한다.
258
+ # 레인(C22)이 재는 것은 «늘어놓기의 재현율»뿐이다: 활용형 픽스처의 모든 줄을 잡는가 · 겹치는 다른 낱말(쓰레기 · 세계 · 재료 …)을 안 잡는가.
259
+ # 출발점(2026-11-16): 정규식 하나가 「쓰던 · 쓰면 · 쓰고 · 쓰되」를 놓쳤다 — 활용형 열거가 이 레인의 핵심이다.
260
+ # 낱말을 늘리려면 픽스처 두 파일에 활용형 줄과 겹치는 낱말 줄을 먼저 넣고, 레인이 초록일 때만 여기에 더한다.
261
+ # 앞 경계 (?<![가-힣]) 때문에 합성어(글쓰기 · 덮어쓰기 · 공작기계)는 안 잡는다 — 알려진 잔여.
262
+ SENSE_WORDS = [
263
+ # 쓰다 = 어간 일치 + 이름 붙인 제외(쓰레기 · 쓰나미 · 쓰러지다 · 쓰라리다 · 쓰다듬다 · 씁쓸). 활용형을 열거하지 않는다 —
264
+ # 열거형은 라운드마다 새 활용형을 놓쳤다(쓰던 → 쓰인 → 쓰였다). 대신 과다 나열(쓸모 · 쓴맛 …)을 받아들이고 (b)가 가른다.
265
+ ("쓰다", r"(?<![가-힣])(?:쓰(?!레|나미|러|라리|라린|다듬)|써(?![클머핀드])|썼|씁(?!쓸)|쓴|쓸(?!쓸)|씀)"),
266
+ # 세다 · 재다 = 「세 · 재」로 시작하는 다른 낱말이 너무 많아(세계 · 세션 · 재료 · 재현 …) 어미 첫 음절 목록 + 이름 붙인 제외로 둔다.
267
+ # 이 둘은 열거형이다 — 목록 밖 활용형은 조용히 빠진다(--senses 출력이 그렇게 적는다).
268
+ ("세다", r"(?<![가-힣])(?:세(?:다(?!리)|는|어|었|고|면(?!대)|며|서|던|지|도(?!정)|려|되|겠|니|야|거|봤|보|셨|죠|네|든|기로|길)|센(?:다|(?![가-힣]))|셀(?:까|지|(?![가-힣]))|셉|셌)"),
269
+ ("재다", r"(?<![가-힣])(?:재(?:다|는|어|었|고(?!품)|면(?!접)|며|서|던|지(?!정|원|급)|도(?!전|입)|려|되|겠|니|야|거(?!래)|봤|보(?!험)|셨|죠|든|기로|길)|잰(?:다|(?![가-힣]))|잴|잽(?!싸)|쟀)"),
270
+ ("기계", r"(?<![가-힣])기계"),
271
+ ]
272
+
273
+
274
+ def sense_hits(path, st=None):
275
+ """[(낱말, 줄번호, 문맥)] — 펜스 · 그림 블록은 뺀다. 문맥 = 맞은 자리 앞뒤 20자."""
276
+ out = []
277
+ for i, line in scan_lines(path, True, st or Blocks()):
278
+ line = re.sub(r"<!--.*?-->", "", line) # 주석 안 낱말은 독자 본문이 아니다(픽스처의 기대 표지도 주석이다)
279
+ for lemma, pat in SENSE_WORDS:
280
+ for m in re.finditer(pat, line):
281
+ a, b = max(0, m.start() - 20), min(len(line), m.end() + 20)
282
+ out.append((lemma, i, line[a:b].strip()))
283
+ return out
284
+
285
+
256
286
  # 함수형 레인 레지스트리: 플래그 -> f(path, common) -> [(키, 줄번호, 종류)]
257
287
  FUNC_LANES = {"s7": lambda path, common=None: s7_candidates(path, common),
258
288
  "hdens": lambda path, common=None: heading_dense(path)}
@@ -524,13 +554,42 @@ def scan_main(args):
524
554
  return 0
525
555
 
526
556
 
557
+ def senses_main(args):
558
+ """--senses FILE — S35 (a) 단계: 낱말별 모든 등장을 줄번호 · 문맥과 함께. 뜻 묶기(b)는 이 출력을 읽는 사람/모델의 몫이다."""
559
+ if len(args) != 1 or args[0].startswith("--"):
560
+ sys.stderr.write("usage: ko_tech_writer_calibrate.py --senses FILE\n")
561
+ return 10
562
+ st = Blocks()
563
+ try:
564
+ hits = sense_hits(args[0], st)
565
+ except (OSError, UnicodeDecodeError) as e:
566
+ sys.stderr.write("harness error: cannot scan %s: %s\n" % (args[0], e))
567
+ return 10
568
+ print("scanned: %s %d lines (fence/fig skipped: %d)" % (args[0], st.total, st.skipped))
569
+ print("words: %s -- listing only; group each word's lines by sense and flag the minority sense (judgment)" % ", ".join(w for w, _ in SENSE_WORDS))
570
+ print("coverage: 쓰다 · 기계 = stem match (over-lists; step b sorts it out) · 세다 · 재다 = enumerated endings -- a form outside the list is silently absent, so 0 here is not 'none'")
571
+ for lemma, _ in SENSE_WORDS:
572
+ rows = [(i, c) for w, i, c in hits if w == lemma]
573
+ print("== %s (%d)" % (lemma, len(rows)))
574
+ for i, c in rows:
575
+ print("%d\t%s" % (i, c))
576
+ bad = unclosed(st)
577
+ if bad:
578
+ for b in bad:
579
+ sys.stderr.write("WARNING unclosed block at EOF: %s -- listing after it is NOT valid\n" % b)
580
+ return 3
581
+ return 0
582
+
583
+
527
584
  def main():
528
585
  if len(sys.argv) > 1:
529
586
  if sys.argv[1] == "--scan":
530
587
  return scan_main(sys.argv[2:])
531
588
  if sys.argv[1] == "--check-rewrite":
532
589
  return check_main(sys.argv[2:])
533
- sys.stderr.write("usage: ko_tech_writer_calibrate.py [--scan FILE [--s7-common LIST] | --check-rewrite ...]\n")
590
+ if sys.argv[1] == "--senses":
591
+ return senses_main(sys.argv[2:])
592
+ sys.stderr.write("usage: ko_tech_writer_calibrate.py [--scan FILE [--s7-common LIST] | --check-rewrite ... | --senses FILE]\n")
534
593
  return 10
535
594
  for p in (POS, NEG):
536
595
  if not os.path.isfile(p):
@@ -650,6 +709,33 @@ def main():
650
709
  print("FAIL RW2 %s" % name)
651
710
  nfail += 1
652
711
 
712
+ # C22 S35 낱말 뜻 늘어놓기 — 활용형 픽스처의 «모든» 줄을 기대 낱말로 잡는가(재현율) · 겹치는 다른 낱말을 0건 잡는가.
713
+ # 🟥 판별하는 것은 늘어놓기(a)뿐이다. 뜻 묶기(b)는 판단이라 이 레인이 재지 않는다 — 초록이어도 «뜻 흔들림 검출»을 주장하지 마라.
714
+ sp, sn = os.path.join(FIX, "sense_positive.md"), os.path.join(FIX, "sense_negative.md")
715
+ if not (os.path.isfile(sp) and os.path.isfile(sn)):
716
+ print("FAIL C22 word-sense listing -- fixture missing (%s / %s)" % (sp, sn))
717
+ nfail += 1
718
+ else:
719
+ exp = {}
720
+ for i, l in enumerate(read_lines(sp), 1):
721
+ m = re.search(r"<!-- (\S+) -->\s*$", l)
722
+ if m:
723
+ exp[i] = m.group(1)
724
+ got = {}
725
+ for lemma, i, _ in sense_hits(sp):
726
+ got.setdefault(i, set()).add(lemma)
727
+ miss = sorted(i for i, e in exp.items() if e not in got.get(i, set()))
728
+ extra = sorted(i for i in got if got[i] != {exp.get(i)})
729
+ neg = sense_hits(sn)
730
+ if exp and not miss and not extra and not neg:
731
+ print("OK C22 낱말 뜻 늘어놓기(S35 a단계) -- recall %d/%d lines of a constructed inflection fixture (%s) / negative 0 (listing discriminates there; "
732
+ "sense grouping is judgment, NOT measured here)" % (len(exp), len(exp), ", ".join(w for w, _ in SENSE_WORDS)))
733
+ npass += 1
734
+ else:
735
+ print("FAIL C22 낱말 뜻 늘어놓기 -- expected %d, missed lines %s, wrong-lemma lines %s, negative hits %d"
736
+ % (len(exp), miss, extra, len(neg)))
737
+ nfail += 1
738
+
653
739
  # META 컨트롤 1 — 없는 토큰이 양쪽 다 0인가 (계기가 «늘 잡는다» 를 내지 않는다)
654
740
  if count(POS, NEVER) == 0 and count(NEG, NEVER) == 0:
655
741
  print("OK META control -- an absent token matches nothing in either fixture")
@@ -675,6 +761,7 @@ def main():
675
761
  print(" NOT proven: 'zero residue' in any real document. That is measured per document.")
676
762
  print(" C7-C12 positives are the harvest's own 'before' sentences (re-built short); C13-C14 positives are constructed (no harvest pair), so")
677
763
  print(" false-positive rate on out-of-distribution text is UNMEASURED. C9 over-blocks by design.")
764
+ print(" C22 measures listing recall on a constructed inflection fixture only; grouping occurrences by sense (S35 step b) is judgment and has no lane.")
678
765
  print(" Citing this suite as evidence of 'zero residue' reproduces the very downgrade")
679
766
  print(" recorded in harness_terminal_correlation_and_recommendations.md.")
680
767
  return 0