@chrono-meta/fh-gate 3.45.0 → 3.47.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 (45) hide show
  1. package/.claude/rules/fh_4axis_gate.md +1 -1
  2. package/.claude-plugin/marketplace.json +4 -4
  3. package/CHEATSHEET.md +8 -4
  4. package/README.ja.md +4 -0
  5. package/README.ko.md +22 -0
  6. package/README.md +24 -0
  7. package/README.zh.md +4 -0
  8. package/docs/codex-compat.md +4 -4
  9. package/knowledge/shared/harness-core/agents_md_runtime_details.md +2 -2
  10. package/knowledge/shared/harness-core/builtin_capability_map.md +5 -2
  11. package/knowledge/shared/harness-core/claude_md_full_reference.md +5 -1
  12. package/knowledge/shared/harness-core/fh_4axis_gate_detail.md +15 -0
  13. package/knowledge/shared/harness-core/fh_detail_protocols.md +1 -0
  14. package/knowledge/shared/harness-core/fh_integration_contract.md +2 -2
  15. package/knowledge/shared/learnings/subagent_invocations_log.yaml +14 -0
  16. package/package.json +3 -1
  17. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  18. package/plugins/fh-commons/skills/mcp-circuit-breaker/SKILL.md +12 -6
  19. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  20. package/plugins/fh-meta/CHANGELOG.md +89 -0
  21. package/plugins/fh-meta/skills/context-doctor/SKILL.md +1 -0
  22. package/plugins/fh-meta/skills/deep-clarify/SKILL.md +76 -22
  23. package/plugins/fh-meta/skills/frontier-digest/SKILL_detail.md +13 -7
  24. package/plugins/fh-meta/skills/harvest-loop/SKILL.md +2 -2
  25. package/plugins/fh-meta/skills/memory-hygiene/SKILL.md +6 -0
  26. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  27. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  28. package/scripts/fh-gate.sh +149 -19
  29. package/scripts/live_eval_trace.py +22 -4
  30. package/scripts/pr_merge_verified.sh +14 -4
  31. package/scripts/selfcheck.sh +2 -0
  32. package/scripts/test_action_yml_lanes.sh +50 -0
  33. package/scripts/test_deep_clarify_interview_lanes.sh +108 -0
  34. package/scripts/test_deep_clarify_spec_path_lanes.sh +91 -0
  35. package/scripts/test_fh_gate_absorb_lanes.sh +1 -0
  36. package/scripts/test_fh_gate_defaults_lanes.sh +229 -3
  37. package/scripts/test_fh_gate_fusion_lanes.sh +1 -0
  38. package/scripts/test_fh_gate_regressions.sh +1 -0
  39. package/scripts/test_live_eval_trace_lanes.sh +27 -7
  40. package/scripts/test_pr_merge_verified_lanes.sh +15 -2
  41. package/scripts/test_probe_live_eval_lanes.sh +4 -3
  42. package/scripts/worktree_reclaim.sh +1 -1
  43. package/templates/PRE-PUBLISH-CHECKLIST.md +22 -0
  44. package/templates/predelete_check.sh +2 -0
  45. package/templates/predelete_check.test.sh +10 -0
@@ -24,7 +24,7 @@
24
24
  # Environment:
25
25
  # FH_DRY_RUN=1 generate prompt only, skip backend invocation; exits 12, not 0
26
26
  # FH_BACKEND=claude|codex|auto AI backend to use (default: claude)
27
- # FH_MODEL=<model> model to use (default depends on backend)
27
+ # FH_MODEL=<model> model to use (claude: claude-sonnet-5-5; codex: not pinned — codex picks its own)
28
28
  # FH_TIMEOUT=120 seconds before backend is killed (default: 120)
29
29
  # FH_VERBOSE=1 print full backend stderr to stderr
30
30
  # FH_RECORD_BASE=<p> directory for governance_log YAML (default: FH_ROOT/tracks/_meta)
@@ -33,13 +33,27 @@
33
33
  # `/code-review` (claude backend only; findings carried as they come — Important →
34
34
  # B, Nit and Pre-existing → C — and the verdict derived from the grades); `fh` =
35
35
  # FH's own goldfish pass, /code-review's method absorbed (no author description).
36
- # UNMEASURED: whether a headless /code-review call, or the goldfish pass, returns
37
- # the structured object the gate needs on every runner — which is why neither is
38
- # the default. FH_REVIEWER=code-review on codex is an argument error.
36
+ # Neither is the default. FH_REVIEWER=code-review on codex is an argument error.
37
+ # 🟥 FH_REVIEWER=code-review CURRENTLY ALWAYS EXITS 10: headless /code-review does not
38
+ # return the structured object the gate needs yet. Measured 2026-11-22 (claude 2.1.330):
39
+ # 0/11 runs returned it — no structured object in 0/5 runs through this
40
+ # script (all exit 10) and 0/6 direct runs. Each ran /code-review as a local command
41
+ # (local_command: code_review, num_turns 0) and gave prose: text lines at low effort,
42
+ # a JSON block inside text or only «Command completed» at medium. That it ignores
43
+ # --json-schema is the likely cause, not isolated. Reading that prose would move the
44
+ # verdict off the typed channel, so the opt-in is left failing closed (operator
45
+ # decision 2026-11-22: no prose parsing, no new channel now). UNMEASURED: whether the
46
+ # `fh` goldfish pass returns the object on every runner.
39
47
  # `code-review` is NOT read-only: /code-review needs git's read commands, and those
40
48
  # can write a file (`--output=`); opt into it for trusted changes only. The `fh` and
41
49
  # elephant passes get only Read · Glob · Grep on the claude backend (no shell, no MCP
42
50
  # server, no skill); on codex they run in `codex exec -s read-only`, codex's sandbox.
51
+ # On claude, every review call (code-review included) runs with user settings only —
52
+ # measured: the checkout's hooks, settings, CLAUDE.md, CLAUDE.local.md, .claude/rules
53
+ # and .mcp.json server do not reach it. On codex the checkout's AGENTS.md is not sent,
54
+ # and the user config is not loaded (--ignore-user-config), so a checkout codex trusts
55
+ # cannot start MCP servers from its .codex/config.toml. If that user config names a
56
+ # provider or endpoint, the codex review is refused (exit 10) instead of rerouted.
43
57
  # FH_GATE_ELEPHANT=off|auto|on the elephant pass (default off; auto = on at level full): task description + the touched
44
58
  # files' git history; looks only for a past fix re-opened, a recorded decision
45
59
  # undone, or the stated task contradicted.
@@ -153,12 +167,16 @@ case "${1:-}" in
153
167
  printf '%s\n' " 1 PENDING B-grade findings; proceed with awareness"
154
168
  printf '%s\n' " 2 BLOCKED A-grade findings; do not merge"
155
169
  printf '%s\n' " 3 ESCALATE human decision required"
156
- printf '%s\n' " 10 harness error — backend unavailable, timeout, unparseable verdict"
170
+ printf '%s\n' " 10 harness error — backend unavailable, timeout, unparseable verdict; also a backend"
171
+ printf '%s\n' " CLI too old for the read-only flags, and (codex) a user config.toml that names a"
172
+ printf '%s\n' " provider or base URL, or cannot be read (since 3.47.0)"
157
173
  printf '%s\n' " 11 argument error"
158
174
  printf '%s\n' " 12 dry run — prompt emitted, NO review performed"
159
175
  printf '%s\n' ""
160
176
  printf '%s\n' " 10, 11 and 12 sit outside the verdict range on purpose: a check that did"
161
177
  printf '%s\n' " not run must never be readable as a pass."
178
+ printf '%s\n' " A plain CI step fails on every non-zero exit, 1 included; the GitHub Action"
179
+ printf '%s\n' " lets 1 (PENDING) pass by default (its fail-on input)."
162
180
  printf '%s\n' ""
163
181
  printf '%s\n' "Environment"
164
182
  printf '%s\n' " FH_BACKEND=claude|codex|auto|cross backend (default: claude)"
@@ -168,6 +186,8 @@ case "${1:-}" in
168
186
  printf '%s\n' " FH_VERBOSE=1 print full backend stderr"
169
187
  printf '%s\n' " FH_REVIEWER=fh-legacy|code-review|fh review stage (default: fh-legacy, the original angle pass;"
170
188
  printf '%s\n' " opt-in: code-review = Claude Code's /code-review, claude only,"
189
+ printf '%s\n' " currently ALWAYS exits 10 (headless /code-review returns no"
190
+ printf '%s\n' " structured object yet — measured 0/11 on claude 2.1.330),"
171
191
  printf '%s\n' " NOT read-only (git can write a file) — trusted changes only ·"
172
192
  printf '%s\n' " fh = FH pass modelled on it, sees the diff only)"
173
193
  printf '%s\n' " FH_GATE_ELEPHANT=off|auto|on history-aware pass (default off; auto: on at level full)"
@@ -370,9 +390,16 @@ fi
370
390
  if [[ -z "${FH_MODEL:-}" ]]; then
371
391
  case "$FH_BACKEND" in
372
392
  claude) FH_MODEL="claude-sonnet-5-5" ;;
373
- codex) FH_MODEL="gpt-5.5" ;;
393
+ # codex: no pinned default (2026-11-22, codex 0.164.0). `-m gpt-5.5`, the old default, is refused for a
394
+ # ChatGPT-account login («The 'gpt-5.5' model is not supported when using Codex with a ChatGPT account»); with no
395
+ # -m codex picks a model from its own catalog for that login (gpt-6.1-terra in that run) and answers. Set FH_MODEL
396
+ # to pin one; it is then passed as -m as before. Measured for one ChatGPT-account login only — API-key logins were
397
+ # not measured — and the model can change with the codex version or the account: set FH_MODEL for a stable one.
398
+ # The record names the model codex resolved (or «unknown»).
399
+ codex) FH_MODEL="" ;;
374
400
  esac
375
401
  fi
402
+ FH_MODEL_LABEL="${FH_MODEL:-codex default (not pinned)}"
376
403
 
377
404
  # ── Review stage (2026-11-19) ─────────────────────────────────────────────────────────────────────
378
405
  # The 2026-11-19 comparison (lab evidence/cr, sealed) measured this gate's own one-pass review against the
@@ -636,7 +663,7 @@ cat > "$PROMPT_FILE" <<PROMPT
636
663
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
637
664
  FH GOVERNANCE GATE v${VERSION} — ${GATE_LEVEL_UPPER} PASS
638
665
  Caller: ${FH_CALLER} | Timestamp: ${TIMESTAMP}
639
- Backend: ${FH_BACKEND} | Model: ${FH_MODEL}
666
+ Backend: ${FH_BACKEND} | Model: ${FH_MODEL_LABEL}
640
667
  Security lens: ${SECURITY_LENS}
641
668
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
642
669
 
@@ -936,7 +963,7 @@ fi
936
963
  # that gates on the documented exit contract.
937
964
  if [[ "$FH_DRY_RUN" == "1" ]]; then
938
965
  if [[ "$FH_REVIEWER" == "code-review" ]]; then
939
- printf 'FH_GATE_DRY_RUN: review = claude --print --model %s --output-format json --json-schema <findings schema> "/code-review %s" (cwd %s)\n' "$FH_MODEL" "$CR_EFFORT" "$WORK_ROOT"
966
+ printf 'FH_GATE_DRY_RUN: review = claude --print --model %s --output-format json --json-schema <findings schema> --setting-sources user <tool policy> -- "/code-review %s" (cwd %s)\n' "$FH_MODEL" "$CR_EFFORT" "$WORK_ROOT"
940
967
  elif [[ "$FH_REVIEWER" == "fh" ]]; then
941
968
  cat "$ABS_PROMPT_FILE"
942
969
  else
@@ -962,6 +989,58 @@ if ! command -v "$FH_BACKEND" &>/dev/null; then
962
989
  exit $EXIT_HARNESS_ERROR
963
990
  fi
964
991
 
992
+ # --- codex: refuse a review the dropped user config would have sent elsewhere ---
993
+ # Every codex review call runs with --ignore-user-config (see the read-only policy below). Dropping that file also
994
+ # drops any provider it names, so the review would silently go to codex's default provider instead — for a proxy or
995
+ # a company gateway, the reviewed code would leave by another road. So before any codex call, read the user config
996
+ # and fail closed (exit 10, nothing sent) if it names where requests go or cannot be read. The keys are the ones the
997
+ # codex 0.164.0 config reference lists as choosing a provider or an endpoint: model_provider (any value but the
998
+ # built-in "openai"), model_providers (custom providers and the built-in cloud ones), openai_base_url (overrides the
999
+ # built-in openai provider), chatgpt_base_url. A profile file ($CODEX_HOME/<name>.config.toml) applies only with
1000
+ # --profile, which fh-gate never passes, and oss_provider only with --oss; neither is read here.
1001
+ # Conservative by design (this is a text scan, not a TOML parser — fh-gate takes no python/TOML dependency): a key
1002
+ # anywhere on a line counts (an inline table, a profile table, a quoted key, even a trailing comment), so a string
1003
+ # value that merely contains one of these words also closes. A quoted key can spell a name with an escape
1004
+ # ("openai\u005fbase_url" is openai_base_url — cross-family R1), so any \u, \U or \x escape closes too. Comment-only
1005
+ # lines are skipped. Absence counts only when confirmed: a dangling link, or a folder on the way that cannot be
1006
+ # searched, is «cannot read», not «no file». The key name and line number are printed, never the value.
1007
+ codex_route_guard() {
1008
+ local _h="${CODEX_HOME:-$HOME/.codex}" _cfg _txt _line _s _n=0 _key="" _p
1009
+ local _q='["'"'"']' _v='("openai"|'"'openai'"'|"""openai"""|'"'''openai'''"')'
1010
+ local _openai="^(model_provider|${_q}model_provider${_q})[[:space:]]*=[[:space:]]*${_v}[[:space:]]*\$"
1011
+ _cfg="$_h/config.toml"
1012
+ _codex_cfg_unreadable() {
1013
+ echo "ERROR: cannot read the codex user config ($_cfg) — fh-gate runs codex with --ignore-user-config and must" >&2
1014
+ echo " first check that file does not name a provider the review would otherwise go to. No review was sent. Failing closed." >&2
1015
+ exit $EXIT_HARNESS_ERROR
1016
+ }
1017
+ if [[ ! -e "$_cfg" && ! -L "$_cfg" ]]; then
1018
+ _p="$_cfg"; while [[ ! -e "$_p" && ! -L "$_p" && "$_p" != / && "$_p" != . ]]; do _p=$(dirname -- "$_p"); done
1019
+ [[ -d "$_p" && -x "$_p" ]] || _codex_cfg_unreadable
1020
+ return 0 # confirmed absent: the nearest existing folder on the way is searchable
1021
+ fi
1022
+ if [[ ! -f "$_cfg" || ! -r "$_cfg" ]] || ! _txt=$(cat -- "$_cfg" 2>/dev/null); then _codex_cfg_unreadable; fi
1023
+ while IFS= read -r _line || [[ -n "$_line" ]]; do
1024
+ _n=$((_n + 1))
1025
+ _s="${_line#"${_line%%[![:space:]]*}"}"
1026
+ [[ -z "$_s" || "$_s" == \#* ]] && continue
1027
+ if [[ "$_s" == *'\u'* || "$_s" == *'\U'* || "$_s" == *'\x'* ]]; then _key="an escape (\\u, \\U or \\x) the guard cannot decode"
1028
+ elif [[ "$_s" == *model_providers* ]]; then _key=model_providers
1029
+ elif [[ "$_s" == *openai_base_url* ]]; then _key=openai_base_url
1030
+ elif [[ "$_s" == *chatgpt_base_url* ]]; then _key=chatgpt_base_url
1031
+ elif [[ "$_s" == *model_provider* && ! "$_s" =~ $_openai ]]; then _key=model_provider
1032
+ fi
1033
+ [[ -n "$_key" ]] && break
1034
+ done <<< "$_txt"
1035
+ [[ -z "$_key" ]] && return 0
1036
+ echo "ERROR: the codex user config ($_cfg, line $_n) has ${_key}. fh-gate runs codex with --ignore-user-config so a" >&2
1037
+ echo " trusted checkout's .codex/config.toml cannot start programs, and that would send this review to codex's default" >&2
1038
+ echo " provider instead of the one your config names. No review was sent. Failing closed." >&2
1039
+ echo " Use the claude backend, or run with a CODEX_HOME whose config.toml names no provider." >&2
1040
+ exit $EXIT_HARNESS_ERROR
1041
+ }
1042
+ [[ "$FH_BACKEND" == "codex" ]] && codex_route_guard
1043
+
965
1044
  # --- Structured-output verdict schema (Typed-Verdict Channel) ---
966
1045
  # Principle: on a gate that ingests untrusted content, the verdict rides a typed,
967
1046
  # schema-constrained channel the content cannot occupy — never a grep-able prose line.
@@ -1023,7 +1102,7 @@ cat > "$CR_SCHEMA_FILE" <<'SCHEMA'
1023
1102
  SCHEMA
1024
1103
 
1025
1104
  # --- Invoke ---
1026
- echo "→ fh-gate v${VERSION} [${GATE_LEVEL_UPPER}] backend=${FH_BACKEND} model=${FH_MODEL} caller=${FH_CALLER} security=${SECURITY_LENS}" >&2
1105
+ echo "→ fh-gate v${VERSION} [${GATE_LEVEL_UPPER}] backend=${FH_BACKEND} model=${FH_MODEL_LABEL} caller=${FH_CALLER} security=${SECURITY_LENS}" >&2
1027
1106
  printf " files:\n%s\n" "$FILES_LIST" >&2
1028
1107
 
1029
1108
  # Use gtimeout (macOS coreutils) if available, fall back to timeout, then bare invoke
@@ -1046,9 +1125,43 @@ fi
1046
1125
  # So the built-in tool set itself is limited (--tools), no MCP server is loaded (--strict-mcp-config with no
1047
1126
  # --mcp-config) and skills and commands are off (--disable-slash-commands). A Claude Code too old for these flags
1048
1127
  # fails the call, which fails closed (exit 10).
1128
+ # The checkout under review is untrusted input (2026-11-22): its project/local settings and hooks must not load into
1129
+ # the reviewer. claude gets --setting-sources user (measured on claude 2.1.330 with a planted checkout and a local
1130
+ # fake API: a project SessionStart hook ran without the flag and did not run with it). codex gets
1131
+ # -c project_doc_max_bytes=0 (measured on codex 0.164.0 the same way: without it the request carried the checkout's
1132
+ # AGENTS.md; with it, it did not). --bare is not used: it also drops OAuth and keychain auth.
1133
+ # Measured again 2026-11-22 with the real CLIs and a subscription login (planted checkout under /tmp; under the
1134
+ # session scratchpad claude loads no CLAUDE.md at all, so a canary there proves nothing): with --setting-sources user
1135
+ # the checkout's CLAUDE.md, CLAUDE.local.md and .claude/rules text did not reach the call (0/3; 3/3 without the flag).
1136
+ # codex also gets --ignore-user-config (2026-11-22, codex 0.164.0, isolated CODEX_HOME, local fake API): when the
1137
+ # user's codex config marks the checkout trusted, codex loads the checkout's .codex/config.toml and starts the MCP
1138
+ # servers it declares — commands from the reviewed checkout, run outside the -s read-only sandbox (3/3; untrusted 0/3).
1139
+ # `-c mcp_servers={}`, `-c projects={}` and a per-path trust override did not stop it; --ignore-user-config did (0/3).
1140
+ # Dropping the user config also drops any provider it names, so the review would go to codex's default provider
1141
+ # instead — codex_route_guard (below, before any call) refuses that case. OPENAI_BASE_URL is not a way around it:
1142
+ # codex 0.164.0 exec did not follow it, with or without the flag (0/2).
1143
+ # Project .rules and hooks of a trusted checkout (measured 2026-11-22, local fake API issuing one command): without
1144
+ # --ignore-user-config the checkout's rule refused the command and its SessionStart/PreToolUse hooks ran (4/4); with
1145
+ # the flag neither applied (0/3), the same as an untrusted checkout (0/3). Those canaries only (one rule, two hook
1146
+ # events); that no other project-scoped codex setting applies is not shown by them.
1049
1147
  _RO_TOOLS="Read,Glob,Grep"
1050
1148
  _RO_ALLOW="$_RO_TOOLS"
1051
1149
  _RO_DENY="Bash,PowerShell,Write,Edit,NotebookEdit,WebFetch,WebSearch"
1150
+ _RO_SOURCES="user"
1151
+ _RO_CODEX_NODOC="project_doc_max_bytes=0"
1152
+ _RO_CODEX_NOUSER="--ignore-user-config"
1153
+ # _note_codex_model <pass> — for an unpinned codex call, the model codex chose: the first `model:` line of codex's own
1154
+ # stderr banner, read only above the `user` line (below it codex echoes the prompt, which carries the reviewed content),
1155
+ # kept only if it looks like a model id; anything else is «unknown» — the record never guesses. Read right after each
1156
+ # call, because the next call overwrites ERR_FILE (cross-family R2: the record named only the last pass).
1157
+ _CODEX_RESOLVED=""
1158
+ _note_codex_model() {
1159
+ [[ "$FH_BACKEND" == "codex" && -z "$FH_MODEL" ]] || return 0
1160
+ local _m
1161
+ _m=$(awk '/^user$/{exit} /^model: /{sub(/^model: /, ""); print; exit}' "$ERR_FILE" 2>/dev/null || true)
1162
+ [[ "$_m" =~ ^[A-Za-z0-9._:-]{1,64}$ ]] || _m="unknown"
1163
+ _CODEX_RESOLVED="${_CODEX_RESOLVED:+${_CODEX_RESOLVED}, }$1 $_m"
1164
+ }
1052
1165
  call_structured() {
1053
1166
  local _ok=0
1054
1167
  : > "$CODEX_LAST"
@@ -1056,16 +1169,17 @@ call_structured() {
1056
1169
  # ${4:-} = "goldfish": the process does not inherit FH_TASK_DESCRIPTION either (not only the prompt)
1057
1170
  claude) ( cd "$WORK_ROOT" && { [[ "${4:-}" == goldfish ]] && unset FH_TASK_DESCRIPTION; :; } && ${_TIMEOUT_CMD} claude --print --model "$FH_MODEL" --output-format json \
1058
1171
  --json-schema "$(cat "$2")" --tools "$_RO_TOOLS" --strict-mcp-config --disable-slash-commands \
1059
- --allowedTools "$_RO_ALLOW" --disallowedTools "$_RO_DENY" < "$1" ) \
1172
+ --setting-sources "$_RO_SOURCES" --allowedTools "$_RO_ALLOW" --disallowedTools "$_RO_DENY" < "$1" ) \
1060
1173
  > "$OUTPUT_FILE" 2>"$ERR_FILE" && _ok=1 ;;
1061
- codex) ( cd "$WORK_ROOT" && { [[ "${4:-}" == goldfish ]] && unset FH_TASK_DESCRIPTION; :; } && ${_TIMEOUT_CMD} codex exec -m "$FH_MODEL" --skip-git-repo-check -s read-only \
1062
- --output-schema "$2" -o "$CODEX_LAST" - < "$1" ) > "$OUTPUT_FILE" 2>"$ERR_FILE" && _ok=1 ;;
1174
+ codex) ( cd "$WORK_ROOT" && { [[ "${4:-}" == goldfish ]] && unset FH_TASK_DESCRIPTION; :; } && ${_TIMEOUT_CMD} codex exec ${FH_MODEL:+-m "$FH_MODEL"} --skip-git-repo-check -s read-only \
1175
+ "$_RO_CODEX_NOUSER" -c "$_RO_CODEX_NODOC" --output-schema "$2" -o "$CODEX_LAST" - < "$1" ) > "$OUTPUT_FILE" 2>"$ERR_FILE" && _ok=1 ;;
1063
1176
  esac
1064
1177
  if [[ "$_ok" != 1 ]]; then
1065
1178
  echo "ERROR: ${3} (${FH_BACKEND}) failed or timed out (${FH_TIMEOUT}s) — failing closed" >&2
1066
1179
  cat "$ERR_FILE" >&2
1067
1180
  exit $EXIT_HARNESS_ERROR
1068
1181
  fi
1182
+ if [[ "$3" == *elephant* ]]; then _note_codex_model elephant; else _note_codex_model review; fi
1069
1183
  [[ "$FH_VERBOSE" == "1" ]] && cat "$ERR_FILE" >&2
1070
1184
  STRUCT_JSON=""
1071
1185
  if [[ "$FH_BACKEND" == "claude" ]]; then
@@ -1143,11 +1257,17 @@ elif [[ "$FH_REVIEWER" == "code-review" ]]; then
1143
1257
  # The runner's command-file variables are left out of this call's environment. That only removes the direct
1144
1258
  # reference: the files can still be found (for example under $RUNNER_TEMP) and written through `git … --output=`.
1145
1259
  # It reduces exposure; it does not make this path safe — which is why it is labelled not read-only.
1260
+ # --setting-sources user (2026-11-22, real claude 2.1.330, planted checkout): without it this call ran the checkout's
1261
+ # project and local hooks, started its .mcp.json server and carried its CLAUDE.md, CLAUDE.local.md and .claude/rules
1262
+ # text (3/3); with it, none of them (3/3). The cost: /code-review no longer has the checkout's CLAUDE.md in context;
1263
+ # it can still read the file with Read.
1264
+ # `--` before the prompt: claude reads a word that follows --disallowedTools as that option's value, so without it
1265
+ # this call failed before any review («"/code-review low" was read as a value of --disallowedTools»), exit 10.
1146
1266
  ( cd "$WORK_ROOT" && unset FH_TASK_DESCRIPTION GITHUB_ENV GITHUB_PATH GITHUB_OUTPUT GITHUB_STATE GITHUB_STEP_SUMMARY && ${_TIMEOUT_CMD} claude --print --model "$FH_MODEL" --output-format json \
1147
- --json-schema "$(cat "$CR_SCHEMA_FILE")" \
1267
+ --json-schema "$(cat "$CR_SCHEMA_FILE")" --setting-sources "$_RO_SOURCES" \
1148
1268
  --allowedTools "Read,Glob,Grep,Agent,Task,Skill,Bash(git diff:*),Bash(git log:*),Bash(git show:*),Bash(git status:*),Bash(git rev-parse:*),Bash(git merge-base:*),Bash(git blame:*)" \
1149
1269
  --disallowedTools "Write,Edit,NotebookEdit,WebFetch,WebSearch" \
1150
- "/code-review ${CR_EFFORT}" < /dev/null ) > "$OUTPUT_FILE" 2>"$ERR_FILE" && _CR_OK=1
1270
+ -- "/code-review ${CR_EFFORT}" < /dev/null ) > "$OUTPUT_FILE" 2>"$ERR_FILE" && _CR_OK=1
1151
1271
  if [[ "$_CR_OK" != 1 ]]; then
1152
1272
  echo "ERROR: /code-review (claude backend) failed or timed out (${FH_TIMEOUT}s) — failing closed" >&2
1153
1273
  cat "$ERR_FILE" >&2
@@ -1190,12 +1310,16 @@ elif [[ "$FH_REVIEWER" == "code-review" ]]; then
1190
1310
  REVIEW_VERDICT="PASS"
1191
1311
  [ "$(printf '%s' "$REVIEW_FINDINGS" | jq -r '[.[]|select(.grade=="B")]|length')" -gt 0 ] && REVIEW_VERDICT="PENDING"
1192
1312
  else
1313
+ # The default (fh-legacy) review gets the same read-only policy as call_structured above, at the repository root:
1314
+ # the target content is already in its prompt, so it only needs to read files. Before 2026-11-22 this call passed no
1315
+ # tool, MCP or sandbox restriction, so it ran with whatever the backend CLI's own settings allowed.
1193
1316
  run_backend() {
1194
1317
  case "$FH_BACKEND" in
1195
- claude) ${_TIMEOUT_CMD} claude --print --model "$FH_MODEL" \
1196
- --output-format json --json-schema "$(cat "$SCHEMA_FILE")" ;;
1197
- codex) ${_TIMEOUT_CMD} codex exec -m "$FH_MODEL" --skip-git-repo-check \
1198
- --output-schema "$SCHEMA_FILE" -o "$CODEX_LAST" - ;;
1318
+ claude) ( cd "$WORK_ROOT" && ${_TIMEOUT_CMD} claude --print --model "$FH_MODEL" \
1319
+ --output-format json --json-schema "$(cat "$SCHEMA_FILE")" --tools "$_RO_TOOLS" --strict-mcp-config \
1320
+ --disable-slash-commands --setting-sources "$_RO_SOURCES" --allowedTools "$_RO_ALLOW" --disallowedTools "$_RO_DENY" ) ;;
1321
+ codex) ( cd "$WORK_ROOT" && ${_TIMEOUT_CMD} codex exec ${FH_MODEL:+-m "$FH_MODEL"} --skip-git-repo-check -s read-only \
1322
+ "$_RO_CODEX_NOUSER" -c "$_RO_CODEX_NODOC" --output-schema "$SCHEMA_FILE" -o "$CODEX_LAST" - ) ;;
1199
1323
  esac
1200
1324
  }
1201
1325
 
@@ -1204,6 +1328,7 @@ if ! run_backend < "$PROMPT_FILE" > "$OUTPUT_FILE" 2>"$ERR_FILE"; then
1204
1328
  cat "$ERR_FILE" >&2
1205
1329
  exit $EXIT_HARNESS_ERROR
1206
1330
  fi
1331
+ _note_codex_model review
1207
1332
 
1208
1333
  [[ "$FH_VERBOSE" == "1" ]] && cat "$ERR_FILE" >&2
1209
1334
 
@@ -1401,6 +1526,11 @@ cat "$PARSE_FILE"
1401
1526
  FINDINGS_A_LOG=$(grep -m 1 "^FH_FINDINGS_A:" "$PARSE_FILE" 2>/dev/null | awk '{print $2}' | tr -d '[:space:]' || echo "0") # portability-noqa: already ends in `|| echo "0"` (P1's own prescribed remedy) — the assignment cannot die under set -e
1402
1527
  FINDINGS_B_LOG=$(grep -m 1 "^FH_FINDINGS_B:" "$PARSE_FILE" 2>/dev/null | awk '{print $2}' | tr -d '[:space:]' || echo "0") # portability-noqa: same as FINDINGS_A_LOG above
1403
1528
  FINDINGS_N_LOG=$(grep -m 1 "^FH_FINDINGS_COUNT:" "$PARSE_FILE" 2>/dev/null | awk '{print $2}' | tr -d '[:space:]' || echo "0") # portability-noqa: same as FINDINGS_A_LOG above
1529
+ # An unpinned codex run records which model codex chose for each pass (_note_codex_model, after every codex call).
1530
+ # The label carries no «: » so the governance YAML stays a plain scalar (cross-family R2).
1531
+ if [[ "$FH_BACKEND" == "codex" && -z "$FH_MODEL" ]]; then
1532
+ FH_MODEL_LABEL="codex default (not pinned, resolved ${_CODEX_RESOLVED:-unknown})"
1533
+ fi
1404
1534
  {
1405
1535
  printf -- "- timestamp: %s\n" "$TIMESTAMP"
1406
1536
  printf " caller: %s\n" "$FH_CALLER"
@@ -1409,7 +1539,7 @@ FINDINGS_N_LOG=$(grep -m 1 "^FH_FINDINGS_COUNT:" "$PARSE_FILE" 2>/dev/null | awk
1409
1539
  printf " elephant: %s\n" "${ELEPHANT_LINE%% —*}"
1410
1540
  printf " e0: %s\n" "$(_exec_get '.e0.status')"
1411
1541
  printf " e1: %s\n" "$(_exec_get '.e1.status')"
1412
- printf " model: %s\n" "$FH_MODEL"
1542
+ printf " model: %s\n" "$FH_MODEL_LABEL"
1413
1543
  printf " gate_level: %s\n" "$GATE_LEVEL"
1414
1544
  printf " verdict: %s\n" "$VERDICT"
1415
1545
  printf " findings_total: %s\n" "$FINDINGS_N_LOG"
@@ -11,7 +11,7 @@ Two uses:
11
11
  extract <stream.jsonl> <out.txt> <tools.txt> (runner) write the final result text and the init
12
12
  tool/MCP/plugin inventory. Exit 3 on a stream that has no parseable result event — never an empty
13
13
  «the session said nothing» (same rule as sim_isolated_run.sh's turns path).
14
- profile <stream.jsonl> (runner) one record-only line: top-level tool calls in four bins
14
+ profile <stream.jsonl> (runner) one record-only line: top-level tool calls in four bins + first error depth
15
15
  (explore · edit · test-run · other). Exit 3 and «trace=UNREADABLE» on a stream it cannot read.
16
16
  library: parse_stream(path) · behave_hit(trace, spec) · inventory(trace) · profile_bins(trace)
17
17
 
@@ -37,7 +37,8 @@ def parse_stream(path):
37
37
  lines = open(path, encoding='utf-8').read().splitlines()
38
38
  except (OSError, UnicodeDecodeError):
39
39
  return None
40
- out = {'result': None, 'tools': None, 'mcp': None, 'plugins': None, 'calls': [], 'damaged': 0, 'ok_ids': set()}
40
+ out = {'result': None, 'tools': None, 'mcp': None, 'plugins': None, 'calls': [], 'damaged': 0, 'ok_ids': set(),
41
+ 'res_ids': set(), 'err_ids': set()}
41
42
  inits = [] # plugin set of every init event, in order
42
43
  for ln in lines:
43
44
  ln = ln.strip()
@@ -76,8 +77,12 @@ def parse_stream(path):
76
77
  out['calls'].append((str(c.get('name', '')), c.get('input') or {}, c.get('id')))
77
78
  elif t == 'user':
78
79
  for c in (ev.get('message') or {}).get('content') or []:
79
- if isinstance(c, dict) and c.get('type') == 'tool_result' and not c.get('is_error'):
80
- out['ok_ids'].add(c.get('tool_use_id'))
80
+ if isinstance(c, dict) and c.get('type') == 'tool_result':
81
+ out['res_ids'].add(c.get('tool_use_id'))
82
+ if c.get('is_error'):
83
+ out['err_ids'].add(c.get('tool_use_id'))
84
+ else:
85
+ out['ok_ids'].add(c.get('tool_use_id'))
81
86
  elif t == 'result':
82
87
  if ev.get('subtype') not in (None, 'success') or ev.get('is_error'):
83
88
  out['damaged'] += 1 # an error result is not a finished session
@@ -276,6 +281,18 @@ def profile_bins(trace):
276
281
  return out
277
282
 
278
283
 
284
+ def first_error(trace):
285
+ """1-based position of the first top-level call whose result is an error · 'none' when every top-level call
286
+ has a result and none is an error · 'unknown' when a call has no result before that (not measured ≠ no error).
287
+ Record only (AQ-20261101-2): a final PASS can hide a run that hit errors early and recovered by luck."""
288
+ for i, (_, _, cid) in enumerate(trace['calls'], 1):
289
+ if cid in trace['err_ids']:
290
+ return str(i)
291
+ if cid not in trace['res_ids']:
292
+ return 'unknown'
293
+ return 'none'
294
+
295
+
279
296
  def _profile(src):
280
297
  """One line for the report. A stream that cannot be read says so (exit 3) — never counts of 0.
281
298
  A stream with no result event or damaged lines keeps its counts and says they are a lower bound."""
@@ -285,6 +302,7 @@ def _profile(src):
285
302
  return 3
286
303
  p = profile_bins(tr)
287
304
  line = ' '.join('%s=%d' % (b, p[b]) for b in PROFILE_BINS) + ' total=%d' % sum(p.values())
305
+ line += ' first_error=%s' % first_error(tr)
288
306
  flags = []
289
307
  if tr['result'] is None:
290
308
  flags.append('result=MISSING')
@@ -16,7 +16,7 @@
16
16
  # 🟥 This script does not decide whether to merge. Approval is still yours — it only makes the
17
17
  # verification impossible to forget once you do.
18
18
  #
19
- # USAGE bash scripts/pr_merge_verified.sh <pr-number> --rerun '<command>' [--repo <path>] [--lease '<label>']
19
+ # USAGE bash scripts/pr_merge_verified.sh <pr-number> --rerun '<command>' [--repo <path>] [--lease '<label>'] [--expect-head <full sha>]
20
20
  # RECEIPT once GitHub has accepted the merge request (every outcome from there: verified · verify failed · queued/not completed ·
21
21
  # merged from another head · not fetchable — never for a refusal or a merge GitHub did not take) one JSON line goes to
22
22
  # ${PMV_RECEIPTS:-<git common dir>/fh-merge-receipts.jsonl} — local, never pushed: pr · head · merge · outcome ·
@@ -25,8 +25,10 @@
25
25
  # Why: arXiv:2610.28683 — 27% of merges that passed a «non-author review» gate rested on an agent approving under a
26
26
  # human account; who decided must be on the record, not inferred later (frontier digest 2026-10-23).
27
27
  # EXIT 0 merged + verified · 1 merged but verify FAILED (the merge stands — act on it)
28
- # 2 usage (nothing merged) · 3 trivial --rerun refused (nothing merged)
29
- # 4 harness error (see message: before or after the merge)
28
+ # 2 usage (nothing merged) — includes an --expect-head that is not a full 40/64-char lowercase hex id
29
+ # 3 trivial --rerun refused (nothing merged)
30
+ # 4 harness error (see message: before or after the merge) — includes a PR head read from gh that is not a full
31
+ # 40/64-char lowercase hex id (cut on the way, e.g. by an output-compression proxy; nothing merged)
30
32
  # 6 merge accepted but not completed (queue/lag) — NOT verified, nothing claimed
31
33
  # 7 lease merge refused: a --lease other than «operator…» and selfdev_merge_tier.sh did not say AUTO, or the tier
32
34
  # could not be read (nothing merged)
@@ -48,8 +50,15 @@ while [ $# -gt 0 ]; do
48
50
  *) [ -z "$PR" ] || { echo "🟥 one PR number only" >&2; exit 2; }; PR="$1"; shift ;;
49
51
  esac
50
52
  done
51
- case "$PR" in ''|*[!0-9]*) echo "🟥 usage: pr_merge_verified.sh <pr-number> --rerun '<cmd>'" >&2; exit 2 ;; esac
53
+ case "$PR" in ''|*[!0-9]*) echo "🟥 usage: pr_merge_verified.sh <pr-number> --rerun '<cmd>' [--repo <path>] [--lease '<label>'] [--expect-head <full sha>]" >&2; exit 2 ;; esac
52
54
  [ "$RERUN_SET" -eq 1 ] || { echo "🟥 --rerun is required — checked before merging so the verify half cannot be skipped" >&2; exit 2; }
55
+ # _full_oid <value> — true only for a full commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex. A shorter value can
56
+ # still resolve locally (git accepts abbreviations), so «resolves» is not «whole». A field run saw an output-compression
57
+ # proxy cut `git rev-parse HEAD` to 37 chars, and the API that took it failed later with no hint why.
58
+ _full_oid() { case "$1" in *[!0-9a-f]*|'') return 1 ;; esac; [ "${#1}" -eq 40 ] || [ "${#1}" -eq 64 ]; }
59
+ if [ -n "$EXPECT_HEAD" ] && ! _full_oid "$EXPECT_HEAD"; then
60
+ echo "🟥 --expect-head is not a full 40- or 64-hex commit id («${EXPECT_HEAD}», ${#EXPECT_HEAD} chars) — a shortened or cut value (an output proxy can do this) cannot pin a merge; not merging" >&2; exit 2
61
+ fi
53
62
  PSV="$(cd "$(dirname "$0")" && pwd)/post_squash_verify.sh"
54
63
  [ -f "$PSV" ] || { echo "🟥 HARNESS-ERROR (before merge): $PSV missing — not merging" >&2; exit 4; }
55
64
 
@@ -96,6 +105,7 @@ _clog() { # outcome-label merge_oid
96
105
  # 1. head before merge
97
106
  HEAD_OID=$(gh pr view "$PR" --json headRefOid -q .headRefOid < /dev/null) || HEAD_OID=""
98
107
  [ -n "$HEAD_OID" ] || { echo "🟥 HARNESS-ERROR (before merge): could not read PR #$PR head" >&2; exit 4; }
108
+ _full_oid "$HEAD_OID" || { echo "🟥 HARNESS-ERROR (before merge): PR #$PR head «${HEAD_OID}» is not a full 40- or 64-hex commit id (${#HEAD_OID} chars) — the value may have been cut on the way (an output proxy can do this); not merging" >&2; exit 4; }
99
109
  git fetch -q origin "pull/$PR/head" < /dev/null 2>/dev/null || git fetch -q origin "$HEAD_OID" < /dev/null 2>/dev/null || true
100
110
  git cat-file -e "$HEAD_OID^{commit}" 2>/dev/null \
101
111
  || { echo "🟥 HARNESS-ERROR (before merge): PR head $HEAD_OID not fetchable — not merging" >&2; exit 4; }
@@ -1325,6 +1325,8 @@ for _pair in \
1325
1325
  "scripts/proposal_hook.sh|scripts/test_proposal_hook_lanes.sh" \
1326
1326
  "plugins/fh-commons/skills/ko-tech-writer/SKILL.md|scripts/test_ko_tech_writer_lanes.sh" \
1327
1327
  "plugins/fh-meta/skills/meta-prompt-builder/SKILL.md|scripts/test_meta_prompt_restate_lanes.sh" \
1328
+ "plugins/fh-meta/skills/deep-clarify/SKILL.md|scripts/test_deep_clarify_spec_path_lanes.sh" \
1329
+ "plugins/fh-meta/skills/deep-clarify/SKILL.md|scripts/test_deep_clarify_interview_lanes.sh" \
1328
1330
  "scripts/absorption_queue.py|scripts/test_absorption_queue_lanes.sh" \
1329
1331
  "scripts/catch_tally.py|scripts/test_catch_tally_lanes.sh" \
1330
1332
  "scripts/shell_name_boundary_scan.sh|scripts/test_name_boundary_locale_lanes.sh" \
@@ -175,6 +175,56 @@ for v in PASS PENDING; do
175
175
  case ",$_failon," in *",$v,"*) no "fail-on default contains $v (over-blocks a reviewed pass)" ;; *) ok "fail-on default correctly omits $v" ;; esac
176
176
  done
177
177
 
178
+ echo "── L7 inputs reach the run script as env data, not as substituted shell text (2026-11-22) ──"
179
+ # WHY. GitHub substitutes `${{ inputs.X }}` into the run: script as TEXT before bash sees it, so a
180
+ # caller-controlled value (a file list built from a PR, say) containing `"; cmd; "` runs `cmd` in the
181
+ # workflow (GitHub's own hardening guide: pass untrusted values through `env:`). Found in the 3.45.0
182
+ # security review (LOW — the caller writes these inputs, but `files` is often derived from PR data).
183
+ # HOW. L7b imitates that substitution: every `${{ inputs.X }}` in the run block is replaced by the
184
+ # value as text, every env: entry is exported as data, `npx` is a stub, and one input carries a
185
+ # payload that touches a file. The file must not appear. L7c is the control: the same run with one
186
+ # env reference turned back into an inline expression must create it.
187
+ _RUNBLK="$(awk '/^ run: \|/{f=1; next} f && /^ - /{exit} f{print}' "$A" | sed 's/^ //')"
188
+ _ENVBLK="$(awk '/^ env:/{f=1; next} f && /^ [a-z-]+:/{exit} f{print}' "$A" | sed 's/^ *//')"
189
+ [ -n "$_RUNBLK" ] && [ -n "$_ENVBLK" ]; chk $? "L7-0 CONTROL: run and env blocks extracted (run $(printf '%s\n' "$_RUNBLK" | wc -l | tr -d ' ') lines)"
190
+ # Any expression form counts — `inputs.x`, `inputs['x']`, `github.event…`, `steps…`: each is pasted as text.
191
+ _inline="$(printf '%s\n' "$_RUNBLK" | grep -c '\${{' || true)"
192
+ [ "$_inline" -eq 0 ]; chk $? "L7a no \${{ … }} expression of any form inside the run script (found $_inline)"
193
+ _L7T="$(mktemp -d "${TMPDIR:-/tmp}/action_yml_l7_XXXXXX")"
194
+ mkdir -p "$_L7T/bin"; printf '#!/bin/sh\nexit 0\n' > "$_L7T/bin/npx"; chmod +x "$_L7T/bin/npx"
195
+ # simulate <run script file> — GitHub-style text substitution of inputs, env as data, stub npx
196
+ _l7_sim(){
197
+ python3 - "$1" "$_L7T" <<'PY'
198
+ import re, sys, os, subprocess
199
+ run = open(sys.argv[1], encoding="utf-8").read(); tmp = sys.argv[2]
200
+ pwn = os.path.join(tmp, "PWNED")
201
+ vals = {"files": 'a.sh"; touch "' + pwn + '"; echo "', "level": "light", "version": "latest",
202
+ "dry-run": "false", "fail-on": "BLOCKED", "backend": "claude", "model": "", "timeout": ""}
203
+ sub = lambda m: vals.get(m.group(1), "")
204
+ env = dict(os.environ, PATH=os.path.join(tmp, "bin") + ":" + os.environ["PATH"],
205
+ GITHUB_OUTPUT=os.path.join(tmp, "out"), GITHUB_STEP_SUMMARY=os.path.join(tmp, "sum"))
206
+ for line in open(os.path.join(tmp, "envblk"), encoding="utf-8"):
207
+ m = re.match(r"([A-Z_]+):\s*(.*)$", line.strip())
208
+ if m: env[m.group(1)] = re.sub(r"\$\{\{\s*inputs\.([a-z-]+)\s*\}\}", sub, m.group(2))
209
+ script = re.sub(r"\$\{\{\s*inputs\.([a-z-]+)\s*\}\}", sub, run)
210
+ if "${{" in script: # an expression form this simulator does not substitute: not measured, never «clean»
211
+ print("UNMEASURED"); sys.exit(0)
212
+ subprocess.run(["bash", "-c", script], env=env, cwd=tmp, capture_output=True)
213
+ print("PWNED" if os.path.exists(pwn) else "clean")
214
+ PY
215
+ }
216
+ printf '%s\n' "$_ENVBLK" > "$_L7T/envblk"
217
+ printf '%s\n' "$_RUNBLK" > "$_L7T/run.sh"
218
+ [ "$(_l7_sim "$_L7T/run.sh")" = "clean" ]; chk $? "L7b a files input carrying '\"; touch …; \"' stays data — no command runs"
219
+ rm -f "$_L7T/PWNED"
220
+ sed 's/"\$FH_ACTION_FILES"/"${{ inputs.files }}"/' "$_L7T/run.sh" > "$_L7T/run_ctl.sh"
221
+ if cmp -s "$_L7T/run.sh" "$_L7T/run_ctl.sh"; then
222
+ no "L7c CONTROL dead — the run script has no \"\$FH_ACTION_FILES\" to turn back into an inline expression"
223
+ else
224
+ [ "$(_l7_sim "$_L7T/run_ctl.sh")" = "PWNED" ]; chk $? "L7c CONTROL: the same payload through an inline \${{ inputs.files }} runs the command (the lane can fail)"
225
+ fi
226
+ rm -rf "$_L7T"
227
+
178
228
  echo ""
179
229
  echo "── action.yml lanes: $PASS passed · $FAIL failed ──"
180
230
  [ "$FAIL" -eq 0 ]
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env bash
2
+ # test_deep_clarify_interview_lanes.sh — the shape of deep-clarify's interview after the four 2026-11-21 additions.
3
+ #
4
+ # WHY. A public «interview me» talk (2026-11-21, used as an idea source only — its numbers are unverified) and
5
+ # deep-clarify differed in four places: deep-clarify folded the upper goal (Why) into the one-line Goal, wrote
6
+ # textbook phrases («make it scalable») straight into the spec, never tested whether it had understood, and
7
+ # offered «start implementation directly» in the same window as an equal next step.
8
+ #
9
+ # WHAT IS CHECKED (structure of SKILL.md — the round templates are what a session copies):
10
+ # I1 Round 1 asks the Why as its own question, separate from the completion-criteria question
11
+ # I2 a textbook-phrase rule: such a phrase is not recorded as a requirement; ask once what is needed
12
+ # I3 the last round tests understanding with an option the user has not mentioned, checks the pick
13
+ # against the Why, re-asks once on a contradiction, then records an open question
14
+ # I4 Step 4's first (default) row is a new session that reads only the saved spec; «Start
15
+ # implementation directly» is still there and marked not the default
16
+ # I5 the spec format carries `## Why` and `## Understanding check`
17
+ # K1 kept: «maximum 3 rounds, maximum 2 questions per round», `(inferred:`, `Excluded:`, `specs/{slug}.md`
18
+ # K2 no round template holds more than 2 numbered questions (the cap holds after adding the Why)
19
+ # C controls: a copy with each of I1–I4 removed goes red on that case alone
20
+ # NOT CHECKED: whether a real session asks these questions — that is the blind Sonnet sim recorded in the
21
+ # PR, not this lane. A green run here means the template says it, not that a model does it.
22
+ #
23
+ # Usage: bash scripts/test_deep_clarify_interview_lanes.sh [<skill file>] Exit: 0 all pass · 1 any fail
24
+ set -uo pipefail
25
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
26
+ SKILL="${1:-$HERE/../plugins/fh-meta/skills/deep-clarify/SKILL.md}"
27
+ TMPROOT=$(mktemp -d "${TMPDIR:-/tmp}/deep_clarify_iv_XXXXXX")
28
+ trap 'rm -rf "$TMPROOT"' EXIT
29
+ pass=0; fail=0
30
+ ok() { printf 'PASS %s\n' "$1"; pass=$((pass + 1)); }
31
+ bad() { printf 'FAIL %s — %s\n' "$1" "$2"; fail=$((fail + 1)); }
32
+
33
+ # probe <skill file> — prints one line per case: «<id> ok» or «<id> <problem>»
34
+ probe() {
35
+ python3 - "$1" <<'PY'
36
+ import re, sys
37
+ t = open(sys.argv[1], encoding="utf-8").read()
38
+ def sec(start, end):
39
+ a = t.find(start)
40
+ if a < 0: return ""
41
+ b = t.find(end, a + len(start)) if end else -1
42
+ return t[a:b] if b > a else t[a:]
43
+ def say(i, ok, why): print(f"{i} ok" if ok else f"{i} {why}")
44
+ r1 = sec("### Round 1", "### Round 2")
45
+ blk = re.findall(r"```\n(.*?)```", r1, re.S)
46
+ qs = re.findall(r"^\s*(\d+)\.\s+(.*)$", blk[0], re.M) if blk else []
47
+ why_q = [n for n, q in qs if re.search(r"\bWhy\b", q)]
48
+ cc_q = [n for n, q in qs if re.search(r"[Cc]ompletion criteria", q)]
49
+ say("I1", why_q and cc_q and set(why_q).isdisjoint(cc_q),
50
+ f"Round 1 template: Why question {why_q or 'missing'}, completion-criteria question {cc_q or 'missing'} (must be separate)")
51
+ tb = sec("### Textbook phrases", "\n## ") or sec("Textbook phrase", "\n### ")
52
+ say("I2", bool(tb) and re.search(r"not (be )?record", tb) and re.search(r"[Aa]sk once", tb),
53
+ "no textbook-phrase rule that says «not recorded as a requirement» and «ask once»")
54
+ r3 = sec("### Round 3", "\n## ")
55
+ say("I3", bool(r3) and re.search(r"not (yet )?(mentioned|discussed)", r3) and re.search(r"\bWhy\b", r3)
56
+ and re.search(r"[Oo]pen question", r3),
57
+ "Round 3 lacks the unmentioned-option test against the Why with an open-question fallback")
58
+ s4 = sec("## Step 4.", "\n## Done When")
59
+ rows = [l for l in s4.splitlines() if l.startswith("|") and not re.match(r"\|\s*-", l)][1:]
60
+ first = rows[0] if rows else ""
61
+ direct = [l for l in rows if "Start implementation directly" in l]
62
+ say("I4", re.search(r"new session", first, re.I) and re.search(r"only the saved spec", first, re.I)
63
+ and direct and re.search(r"not the default", direct[0], re.I),
64
+ f"Step 4 first row «{first[:60]}» is not the new-session default, or «Start implementation directly» is gone / not marked")
65
+ fmt = sec("### Spec Document Format", "\n## Step 4")
66
+ say("I5", "## Why" in fmt and "## Understanding check" in fmt, "spec format lacks ## Why or ## Understanding check")
67
+ keep = ["maximum 3 rounds, maximum 2 questions per round", "(inferred:", "Excluded:", "specs/{slug}.md"]
68
+ miss = [k for k in keep if k not in t]
69
+ say("K1", not miss, f"missing kept text: {miss}")
70
+ over = []
71
+ for name in ("### Round 1", "### Round 2", "### Round 3"):
72
+ s = sec(name, "\n### ") if name != "### Round 3" else r3
73
+ for b in re.findall(r"```\n(.*?)```", s, re.S):
74
+ n = len(re.findall(r"^\s*\d+\.\s", b, re.M))
75
+ if n > 2: over.append(f"{name.strip('# ')}={n}")
76
+ say("K2", not over, f"round template over 2 questions: {over}")
77
+ PY
78
+ }
79
+
80
+ [ -r "$SKILL" ] || { echo "HARNESS: $SKILL not readable — not measured"; exit 1; }
81
+ out=$(probe "$SKILL") || { echo "HARNESS: probe failed"; exit 1; }
82
+ while read -r id rest; do
83
+ [ "$rest" = ok ] && ok "$id" || bad "$id" "$rest"
84
+ done <<< "$out"
85
+
86
+ # C — controls: remove one addition at a time from a copy; exactly that case must go red
87
+ control() { # control <id> <python that edits text t>
88
+ local f="$TMPROOT/ctl_$1.md" got
89
+ python3 - "$SKILL" "$f" "$2" <<'PY'
90
+ import re, sys
91
+ t = open(sys.argv[1], encoding="utf-8").read()
92
+ exec(sys.argv[3])
93
+ open(sys.argv[2], "w", encoding="utf-8").write(t)
94
+ PY
95
+ got=$(probe "$f" | awk '$2 != "ok" {print $1}' | tr '\n' ' ')
96
+ [ "$got" = "$1 " ] && ok "C-$1 control: removing it turns only $1 red" || bad "C-$1 control" "red cases «${got}», expected «$1 »"
97
+ }
98
+ if [ "$fail" -eq 0 ]; then
99
+ control I1 't = re.sub(r"(### Round 1.*?```\n)(.*?)(```)", lambda m: m.group(1) + re.sub(r"^.*\bWhy\b.*\n(?:\s+\(.*\n)?", "", m.group(2), flags=re.M) + m.group(3), t, count=1, flags=re.S)'
100
+ control I2 't = t.replace("### Textbook phrases", "### Plain phrases").replace("Textbook phrase", "Plain phrase")'
101
+ control I3 't = re.sub(r"(### Round 3)(.*?)(\n## )", lambda m: m.group(1) + "\n\nDraft the spec, then confirm once.\n" + m.group(3), t, count=1, flags=re.S)'
102
+ control I4 't = re.sub(r"(## Step 4\..*?\|---\|---\|\n)\|[^\n]*\n", r"\1", t, count=1, flags=re.S)'
103
+ else
104
+ echo "SKIP controls — the shipped skill is already red (a control on a red subject proves nothing)"
105
+ fi
106
+
107
+ echo "PASS $pass · FAIL $fail"
108
+ [ "$fail" -eq 0 ]