@chrono-meta/fh-gate 3.25.0 → 3.26.1

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 (90) hide show
  1. package/.claude/regression/probes_live.yaml +9 -3
  2. package/.claude/rules/fh_4axis_gate.md +2 -0
  3. package/.claude-plugin/marketplace.json +4 -4
  4. package/AGENTS.md +69 -13
  5. package/CLAUDE.md +3 -3
  6. package/README.ja.md +90 -379
  7. package/README.ko.md +130 -379
  8. package/README.md +122 -364
  9. package/README.zh.md +90 -346
  10. package/docs/REFERENCE.md +465 -0
  11. package/docs/USER_GUIDE.md +19 -0
  12. package/docs/codex-compat.md +36 -9
  13. package/knowledge/shared/harness-core/agents_md_runtime_details.md +49 -5
  14. package/knowledge/shared/harness-core/multi_model_sidecar_strategy.md +7 -3
  15. package/knowledge/shared/learnings/subagent_invocations_log.yaml +73 -0
  16. package/knowledge/shared/rules/operations.md +3 -2
  17. package/package.json +10 -1
  18. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  19. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  20. package/plugins/fh-meta/CHANGELOG.md +32 -0
  21. package/plugins/fh-meta/skills/prompt-regression/SKILL.md +2 -2
  22. package/plugins/fh-meta/skills/sim-conductor/SKILL.md +3 -3
  23. package/plugins/fh-meta/skills/sim-conductor/SKILL_detail.md +4 -2
  24. package/plugins/fh-preprep/.claude-plugin/plugin.json +1 -1
  25. package/plugins/fh-preprep/skills/preprep/lane_speech_coach.py +14 -22
  26. package/plugins/fh-preprep/skills/preprep/test_lane_speech_coach.py +47 -1
  27. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  28. package/scripts/fixtures/generated_harness/P1_r1/.claude/agents/todo-developer.md +28 -0
  29. package/scripts/fixtures/generated_harness/P1_r1/.claude/agents/todo-qa.md +25 -0
  30. package/scripts/fixtures/generated_harness/P1_r1/.claude/skills/harness/SKILL.md +6 -0
  31. package/scripts/fixtures/generated_harness/P1_r1/.claude/skills/todo-dev/SKILL.md +37 -0
  32. package/scripts/fixtures/generated_harness/P1_r1/CLAUDE.md +10 -0
  33. package/scripts/fixtures/generated_harness/P1_r1/tests/test_cli.py +1 -0
  34. package/scripts/fixtures/generated_harness/P1_r1/todo/cli.py +13 -0
  35. package/scripts/fixtures/generated_harness/P2_r2/.claude/agents/note-organizer.md +26 -0
  36. package/scripts/fixtures/generated_harness/P2_r2/.claude/agents/summary-reviewer.md +20 -0
  37. package/scripts/fixtures/generated_harness/P2_r2/.claude/agents/summary-writer.md +23 -0
  38. package/scripts/fixtures/generated_harness/P2_r2/.claude/skills/meeting-notes-organize/SKILL.md +23 -0
  39. package/scripts/fixtures/generated_harness/P2_r2/.claude/skills/weekly-meeting-summary/SKILL.md +39 -0
  40. package/scripts/fixtures/generated_harness/P2_r2/.claude/skills/weekly-summary-write/SKILL.md +25 -0
  41. package/scripts/fixtures/generated_harness/P2_r2/CLAUDE.md +10 -0
  42. package/scripts/fixtures/generated_harness/P2_r2/tests/test_cli.py +1 -0
  43. package/scripts/fixtures/generated_harness/P2_r2/todo/cli.py +13 -0
  44. package/scripts/fixtures/generated_harness/P3_r1/.claude/agents/todo-developer.md +30 -0
  45. package/scripts/fixtures/generated_harness/P3_r1/.claude/agents/todo-reviewer.md +21 -0
  46. package/scripts/fixtures/generated_harness/P3_r1/.claude/agents/todo-tester.md +23 -0
  47. package/scripts/fixtures/generated_harness/P3_r1/.claude/settings.json +11 -0
  48. package/scripts/fixtures/generated_harness/P3_r1/.claude/skills/todo-dev/SKILL.md +38 -0
  49. package/scripts/fixtures/generated_harness/P3_r1/CLAUDE.md +12 -0
  50. package/scripts/fixtures/generated_harness/P3_r1/tests/test_cli.py +1 -0
  51. package/scripts/fixtures/generated_harness/P3_r1/todo/cli.py +13 -0
  52. package/scripts/fixtures/generated_harness/P3_r2/.claude/agents/todo-developer.md +27 -0
  53. package/scripts/fixtures/generated_harness/P3_r2/.claude/agents/todo-reviewer.md +15 -0
  54. package/scripts/fixtures/generated_harness/P3_r2/.claude/agents/todo-tester.md +20 -0
  55. package/scripts/fixtures/generated_harness/P3_r2/.claude/settings.json +12 -0
  56. package/scripts/fixtures/generated_harness/P3_r2/.claude/skills/todo-dev-team/SKILL.md +32 -0
  57. package/scripts/fixtures/generated_harness/P3_r2/CLAUDE.md +12 -0
  58. package/scripts/fixtures/generated_harness/P3_r2/tests/test_cli.py +1 -0
  59. package/scripts/fixtures/generated_harness/P3_r2/todo/cli.py +13 -0
  60. package/scripts/fixtures/generated_harness/P4_r2/.claude/agents/todo-developer.md +27 -0
  61. package/scripts/fixtures/generated_harness/P4_r2/.claude/agents/todo-qa.md +23 -0
  62. package/scripts/fixtures/generated_harness/P4_r2/.claude/skills/todo-dev/SKILL.md +19 -0
  63. package/scripts/fixtures/generated_harness/P4_r2/.claude/skills/todo-orchestrator/SKILL.md +33 -0
  64. package/scripts/fixtures/generated_harness/P4_r2/CLAUDE.md +10 -0
  65. package/scripts/fixtures/generated_harness/P4_r2/tests/test_cli.py +1 -0
  66. package/scripts/fixtures/generated_harness/P4_r2/todo/cli.py +13 -0
  67. package/scripts/gate_bootstrap_ephemeral.sh +0 -2
  68. package/scripts/generated_harness_check.py +740 -0
  69. package/scripts/lane_onoff_compare.py +138 -0
  70. package/scripts/lane_stub_env.allow +5 -0
  71. package/scripts/lane_stub_env.sh +63 -0
  72. package/scripts/mutation_probe.py +0 -5
  73. package/scripts/pr_merge_verified.sh +27 -3
  74. package/scripts/probe_live_eval.sh +1 -1
  75. package/scripts/probe_live_eval_lib.py +2 -2
  76. package/scripts/selfcheck.sh +22 -1
  77. package/scripts/test_axis4_lane_substitute_lanes.sh +93 -0
  78. package/scripts/test_card_drift_probe.sh +7 -0
  79. package/scripts/test_channel_inventory_lanes.sh +7 -1
  80. package/scripts/test_generated_harness_check_lanes.sh +325 -0
  81. package/scripts/test_hook_source_gate_lanes.sh +14 -3
  82. package/scripts/test_lane_stub_env_lanes.sh +218 -0
  83. package/scripts/test_marker_floor_lanes.sh +7 -0
  84. package/scripts/test_pr_merge_verified_lanes.sh +50 -3
  85. package/scripts/test_probe_live_eval_lanes.sh +1 -1
  86. package/scripts/test_push_zone_lanes.sh +6 -0
  87. package/scripts/test_session_close_lanes.sh +7 -0
  88. package/scripts/test_utterance_intake_lanes.sh +20 -1
  89. package/templates/.claude/rules/session.md +11 -0
  90. package/templates/.git-hooks/pre-commit +63 -21
@@ -0,0 +1,740 @@
1
+ #!/usr/bin/env python3
2
+ # generated_harness_check.py — 외부 생성기(예: revfactory/harness «하네스 구성해줘»)가 써 넣은
3
+ # 하네스를 FH 가 받아서 검사하는 «뒷단» 기계 검사기.
4
+ #
5
+ # 사용: python3 scripts/generated_harness_check.py <대상 디렉터리> [--json] [--exclude-skill NAME ...]
6
+ # python3 scripts/generated_harness_check.py --selftest
7
+ # 읽는 것: CLAUDE.md · .claude/agents/*.md · .claude/skills/*/SKILL.md ·
8
+ # .claude/settings.json · .claude/settings.local.json
9
+ # 생성기 자신의 스킬(harness · harness-evolve)은 검사 대상에서 뺀다(--exclude-skill 로 추가).
10
+ #
11
+ # 판정 = 종료코드 (출력 파싱 아님):
12
+ # 0 PASS 사람 확인 항목 없음 (경고·정보는 있을 수 있다)
13
+ # 1 HUMAN_REVIEW H1/H2 가 하나 이상 — 비가역 권한이 «열려 있다»
14
+ # 3 HARNESS_ERROR 대상 없음 · 읽기 실패 · JSON 깨짐 · frontmatter 파싱 실패 ·
15
+ # 검사할 하네스 자체가 없음. «못 읽음» 을 PASS 나 0건으로 접지 않는다.
16
+ #
17
+ # 사람 확인: H1 settings 의 permissions.allow 에 비가역 패턴 · H2 지침 본문이 비가역 동작을
18
+ # «확인 없이/알아서» 류와 같은(또는 바로 다음) 문장에서 허용.
19
+ # 경고(rc 무영향): W1 읽기 전용 주장 vs 쓰기·Bash 도구(tools 없음=전부 상속 포함) · W2 tools 줄 없음(전부 상속) · W7 스킬 파일명이 SKILL.md 아님 ·
20
+ # W4 죽은 참조 · W6 스킬 description 비어 있음.
21
+ # 정보: W3 Bash 범위 제한 서술 없음 · W5 Done When 없음(FH 기준, 생성기 결함 아님) ·
22
+ # 아직 없는 입출력 경로(자리표시자·디렉터리·_workspace·런타임 산출 파일명).
23
+ #
24
+ # 🟥 정직한 한계 — 막는 것은 «기록의 형태»이지 의도가 아니다. 전부 정규식이라 우회된다
25
+ # (철자 변형 · 다른 언어 · 두 문장 건너 허용 · 다른 프로그램을 거친 실행 —
26
+ # `xargs git push` · `sh -c '…'` · 스크립트·별칭 — · 따옴표/이스케이프/서브셸 같은 셸 문법 구석).
27
+ # 셸 문법 우회는 이름 붙인 잔여다: cross-family 리뷰 R1~R4 가 라운드마다 한 구석씩 찾았고
28
+ # (R5 «회귀만» 에서 0 으로 수렴), «우회를 다 찾는다» 는 정규식 검사기로는 수렴하지 않는다.
29
+ # 서브커맨드 판정은 토큰 집합이라 `git log --grep push` 같은 무해 명령도 걸린다 — 의도된 과차단.
30
+ # PASS 는 «사람 확인 항목을 못 찾았다» 일 뿐 «안전하다» 가 아니다. 이 검사기는 사람의 확인을
31
+ # 대체하지 않고, 비가역 권한을 열지 말지의 결론은 언제나 사람 몫이다. 부정문 판정(금지문 제외)은
32
+ # «같은 문장 안 부정어» 휴리스틱이라 «하지 않는다고는 하나 결국 한다» 류를 놓칠 수 있다.
33
+ # 표준 라이브러리만 사용 (python 3.9 호환).
34
+ import fnmatch
35
+ import json
36
+ import os
37
+ import posixpath
38
+ import re
39
+ import sys
40
+
41
+ RC_PASS, RC_HUMAN, RC_ERROR = 0, 1, 3
42
+
43
+ GENERATOR_SKILLS = ("harness", "harness-evolve")
44
+
45
+ # ── H1: permissions.allow 의 비가역 패턴 ─────────────────────────────────
46
+ # (라벨, 정규식) — Bash(...) 안쪽 문자열에 적용한다. 철자가 아니라 «동작» 기준으로 넓게 잡는다.
47
+ H1_PATTERNS = [
48
+ ("rm (삭제)", r"\brm\b"),
49
+ ("git push", r"\bgit\s+push\b"),
50
+ ("git reset --hard", r"\bgit\s+reset\b.*--hard"),
51
+ ("git branch -d/-D", r"\bgit\s+branch\b(?:\s+\S+)*\s+(?:-[A-Za-z]*[dD]\b|--delete\b)"),
52
+ ("git clean -f", r"\bgit\s+clean\b.*-[A-Za-z]*f"),
53
+ ("gh pr merge", r"\bgh\s+pr\s+merge\b"),
54
+ ("gh repo delete", r"\bgh\s+repo\s+delete\b"),
55
+ ("npm publish", r"\bnpm\s+publish\b"),
56
+ ("twine upload", r"\btwine\s+upload\b"),
57
+ # git/gh/npm/twine 접두 전체 허용(`git:*`, `git *`)은 위 동작들을 간접으로 연다.
58
+ ("광범위 접두 허용", r"^(?:git|gh|npm|twine)(?:\s+\*|:\*|\*)?$"),
59
+ ]
60
+ _H1_RE = [(lab, re.compile(p)) for lab, p in H1_PATTERNS]
61
+
62
+
63
+ # 비가역 명령 표본 — 허용 항목 안쪽의 `*` 와일드카드를 glob 으로 보고 이 표본 중 하나라도 덮으면 H1.
64
+ IRREV_SAMPLES = ["rm x", "rm -rf x", "git push", "git push --force", "git push origin main",
65
+ "git reset --hard", "git branch -D x", "git branch --delete x", "git clean -fd",
66
+ "gh pr merge 1", "gh repo delete x", "npm publish", "twine upload x"]
67
+ # git 전역 옵션(서브커맨드 앞) — 매칭 전에 걷어낸다: `git -C . push` 가 `git push` 로 읽혀야 한다.
68
+ _GIT_GLOBAL_RE = re.compile(
69
+ r"^git((?:\s+(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=|\s+)\S+|--work-tree(?:=|\s+)\S+|"
70
+ r"--no-pager|--paginate|-P|--bare|--no-replace-objects))+)\s+")
71
+ _SEG_SPLIT_RE = re.compile(r"&&|\|\||;|\||&|[\r\n]") # 줄바꿈·단독 & 도 명령 구분자 (codex R4)
72
+
73
+
74
+ def _segments(inner):
75
+ """allow 항목 안쪽 → 명령 «머리» 조각들. `&&`·`||`·`;`·`|` 로 쪼개고 앞쪽 sudo/env/VAR=val 을 걷어낸다.
76
+ (echo rm 의 rm 은 인자라 머리가 아니다 · cd x && rm y 의 rm 은 머리다.)"""
77
+ out = []
78
+ for seg in _SEG_SPLIT_RE.split(inner):
79
+ toks = seg.strip().split()
80
+ while toks and (toks[0] in ("sudo", "env") or re.match(r"^[A-Za-z_]\w*=", toks[0])):
81
+ toks.pop(0)
82
+ if toks and "/" in toks[0]: # `/usr/bin/git push` · `/bin/rm x` — 경로 머리는 이름으로 본다
83
+ toks[0] = toks[0].rstrip("/").rsplit("/", 1)[-1]
84
+ seg = " ".join(toks)
85
+ while True:
86
+ m = _GIT_GLOBAL_RE.match(seg)
87
+ if not m:
88
+ break
89
+ seg = "git " + seg[m.end():]
90
+ if seg:
91
+ out.append(seg)
92
+ return out
93
+
94
+
95
+ def h1_match(entry):
96
+ """permissions.allow 항목(또는 스킬 allowed-tools 의 Bash 항목) 하나 → 걸린 라벨 또는 None."""
97
+ if not isinstance(entry, str):
98
+ return None
99
+ m = re.match(r"^Bash(?:\((.*)\))?$", entry.strip(), re.S)
100
+ if not m:
101
+ return None
102
+ inner = m.group(1)
103
+ if inner is None or inner.strip() in ("", "*", ":*"):
104
+ return "Bash 전면 허용"
105
+ inner = inner.strip()
106
+ if "*" in inner: # 와일드카드: 명시 정규식과 별개로, 비가역 표본을 덮는지 본다
107
+ for pat in {inner.replace(":*", "*"), inner.replace(":*", " *")}:
108
+ for smp in IRREV_SAMPLES:
109
+ if fnmatch.fnmatchcase(smp, pat):
110
+ return "와일드카드가 `%s` 를 덮는다" % smp
111
+ # 명령 치환·프로세스 치환은 위치와 상관없이 그 자리에서 실행된다(X=`id` cmd · cmd $(id), codex 카트리지 R13)
112
+ if re.search(r"`|\$\(|<\(|>\(", inner):
113
+ return "명령·프로세스 치환"
114
+ # 따옴표·역슬래시는 낱말을 이어 붙여 서브커맨드를 가리고(git p""ush), 리다이렉션은 머리 앞에 와서
115
+ # 실행 대상을 가린다(0</dev/null sh). 문자열 검사로는 셸 파싱을 다 못 하므로 있으면 사람 확인(codex 카트리지 R14)
116
+ if re.search(r"[\"'\\<>]", inner):
117
+ return "따옴표·역슬래시·리다이렉션"
118
+ # 마지막 울타리: 셸 문법 우회는 목록으로 끝나지 않았다(codex 카트리지 R1~R15 — ${X:-push} · ! sh 까지).
119
+ # 평범한 명령 글자 밖이면 사람 확인. 운영자 결정 2026-10-12, 과차단은 받아들인다.
120
+ if re.search(r"[^A-Za-z0-9_./:*=, -]", inner):
121
+ return "허용 문자 밖의 글자 (셸 문법 가능성)"
122
+ for raw in _SEG_SPLIT_RE.split(inner):
123
+ lab = _indirect_wildcard(raw)
124
+ if lab:
125
+ return lab
126
+ for seg in _segments(inner):
127
+ if "*" in seg: # 경로 머리를 이름으로 줄인 뒤에도 본다 — `/bin/*` 는 줄이면 `*` (codex R3)
128
+ for pat in {seg.replace(":*", "*"), seg.replace(":*", " *")}:
129
+ for smp in IRREV_SAMPLES:
130
+ if fnmatch.fnmatchcase(smp, pat):
131
+ return "와일드카드가 `%s` 를 덮는다" % smp
132
+ for lab, rx in _H1_RE:
133
+ if rx.match(seg):
134
+ return lab
135
+ lab = _tokenset_irreversible(seg)
136
+ if lab:
137
+ return lab
138
+ return None
139
+
140
+
141
+ # 인자를 «명령» 으로 실행하는 머리 (codex 카트리지 R8 · ghc R1). 블록리스트로 옵션을 쫓지 않는다:
142
+ # 와일드카드가 있으면 «인터프리터 바로 뒤 고정 스크립트 경로» 형태만 통과, 나머지는 전부 H1.
143
+ # 인터프리터 이름의 «단일 출처» — 정규식과 glob 후보가 여기서만 나온다(목록끼리 어긋난 것이 R6·R8·R10 세 번)
144
+ _INTERP_BASE = ["sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "python", "pypy",
145
+ "node", "nodejs", "deno", "bun", "perl", "ruby", "php", "lua", "luajit", "osascript",
146
+ "npx", "uvx", "pipx", "tclsh", "wish", "expect", "awk", "gawk", "mawk", "nawk",
147
+ "Rscript", "julia", "pwsh", "powershell", "cmd"]
148
+ _INTERP_RE = re.compile(r"^(?:%s)[0-9.]*$" % "|".join(map(re.escape, _INTERP_BASE))) # python3.12 · lua5.4
149
+ # 고정 실행 대상 = 경로처럼 생긴 것(`/` 포함 또는 스크립트 확장자) — `deno eval` · `bun exec` 의 낱말은 아니다
150
+ _SCRIPT_TARGET_RE = re.compile(r"(?:/|\.(?:py|js|mjs|cjs|ts|sh|bash|zsh|rb|pl|php|lua|R|jl|ps1|tcl|awk)$)")
151
+ # 고정 경로 예외가 없는 인터프리터 — awk 계열은 첫 인자가 프로그램 텍스트, 윈도 셸은 `/Command` 처럼
152
+ # `/` 로 시작하는 옵션을 받아 경로와 구분이 안 된다(codex R9)
153
+ _PROGTEXT_HEADS = {"awk", "gawk", "mawk", "nawk", "pwsh", "powershell", "cmd"}
154
+ # `python -m X:*` 예외는 pytest 하나 — 린터도 인자를 코드로 실행한다(pylint --init-hook, codex R4).
155
+ # 넓히려면 «인자 코드 실행 없음» 을 보이는 레인부터.
156
+ _PY_M_OK = {"pytest"}
157
+ _PKG_EXEC_HEADS = {"npx", "uvx", "pipx", "bunx"}
158
+ _PKG_MGR_HEADS = {"npm", "pnpm", "yarn", "bun"} # 서브커맨드 exec·dlx·x 가 옵션 뒤 어디에 있든 실행기
159
+ # 뒤따르는 낱말을 명령으로 실행하는 감싸개 — 와일드카드가 «어디에» 있든 임의 명령이다
160
+ # (고정 대상을 감싼 `timeout 5 python3 x.py:*` 도 H1 — 비가역 쪽 과차단을 택한다)
161
+ _WRAP_HEADS = {"eval", "exec", "xargs", "env", "sudo", "doas", "nohup", "timeout", "command",
162
+ "time", "nice", "watch", "caffeinate", "script", "parallel"}
163
+ _GLOB_CANDIDATES = list(dict.fromkeys(
164
+ sorted(_WRAP_HEADS) + _INTERP_BASE + sorted(_PROGTEXT_HEADS | _PKG_MGR_HEADS | _PKG_EXEC_HEADS)))
165
+
166
+
167
+ def _bare(tok):
168
+ t = re.sub(r"(?::\*|\*)$", "", tok).strip("\"'")
169
+ return t.rstrip("/").rsplit("/", 1)[-1] if "/" in t else t
170
+
171
+
172
+ def _indirect_wildcard(raw_seg):
173
+ """원문 조각(sudo/env 를 걷어내기 «전») → 라벨 또는 None."""
174
+ toks = raw_seg.strip().split()
175
+ while toks and re.match(r"^[A-Za-z_]\w*=", toks[0]):
176
+ toks.pop(0)
177
+ if not toks:
178
+ return None
179
+ # 머리에 따옴표·역슬래시·전개가 있으면 무엇이 실행될지 문자열로 못 정한다(s""h · \sh, codex 카트리지 R12)
180
+ if re.search(r"[\"'\\$`]", toks[0]):
181
+ return "명령 머리에 셸 따옴표·전개 `%s`" % toks[0]
182
+ head = _bare(toks[0])
183
+ raw0 = toks[0].strip("\"'")
184
+ raw0 = raw0[:-2] if raw0.endswith(":*") else raw0
185
+ if re.search(r"[*?\[]", raw0):
186
+ head = raw0.rsplit("/", 1)[-1] # `py*` · `python[3]` · `python3.1?` — 머리 자체가 glob
187
+ if head == "git" and re.search(r"alias\.[^\s=]*=", raw_seg):
188
+ return "git -c alias 정의 (별칭이 임의 명령을 실행)"
189
+ if "*" not in raw_seg:
190
+ return None
191
+ if re.search(r"[*?\[]", head): # 머리 자체가 glob — 인터프리터·감싸개 이름을 덮으면 그것과 같다
192
+ # 허용하는 머리 glob 은 «글자 + 끝 `*`» (`ls*` · `npm*`) 하나뿐. `?` · `[` · 중간 `*` 는 무엇을 덮는지
193
+ # 목록으로 판정할 수 없어 바로 H1 이다(`?ython3`, codex R12 — 후보 비교를 조이던 길을 닫는다).
194
+ if not re.fullmatch(r"[^*?\[]+\*", head):
195
+ return "머리 glob `%s` (끝 `*` 접두 형태가 아니다)" % head
196
+ lit = head[:-1]
197
+ hits = [n for n in _GLOB_CANDIDATES
198
+ if n.startswith(lit) or (lit.startswith(n) and re.fullmatch(r"[0-9.]*", lit[len(n):]))]
199
+ for n in hits: # 덮은 이름 «전부» 를 같은 규칙에 — 하나라도 H1 이면 H1 (재귀는 `:*` 라 끝난다)
200
+ lab = _indirect_wildcard(" ".join([n + ":*"] + toks[1:]))
201
+ if lab:
202
+ return "머리 glob `%s` → %s" % (head, lab)
203
+ return None
204
+ if head in _WRAP_HEADS:
205
+ return "간접 실행 `%s` 와일드카드" % head
206
+ # 패키지 실행기 — 인자로 받은 패키지를 받아 실행한다. 고정 경로 예외가 없다(`npx @babel/node`, codex R5)
207
+ sub = [t.strip("\"'") for t in toks[1:] if not t.startswith("-")]
208
+ sub = [t[:-2] if t.endswith(":*") else t for t in sub]
209
+ fam = re.sub(r"[0-9.]+$", "", head) if _INTERP_RE.match(head) else head # `awk5` · `npx2` → 계열 이름 (codex R13)
210
+ if fam in _PKG_EXEC_HEADS or (fam in _PKG_MGR_HEADS and any(
211
+ fnmatch.fnmatchcase(e, t) for t in sub for e in ("exec", "dlx", "x"))):
212
+ return "패키지 실행기 `%s` 와일드카드" % head
213
+ if not _INTERP_RE.match(head):
214
+ return None
215
+ # 끝의 `:*` 만 «인자 허용» 접미사다. 맨 `*` 는 대상 안의 glob 이라 남겨서 아래에서 H1 로 본다.
216
+ rest = [(t[:-2] if t.endswith(":*") else t).strip("\"'") for t in toks[1:]]
217
+ if fam in _PROGTEXT_HEADS:
218
+ return "인터프리터 `%s` 와일드카드 (고정 경로 예외 없음)" % head
219
+ if head.startswith("python") and rest[:1] == ["-m"]:
220
+ mod = rest[1] if len(rest) > 1 else ""
221
+ if mod in _PY_M_OK:
222
+ return None
223
+ return "인터프리터 `%s -m %s` 와일드카드 (검토된 모듈 아님)" % (head, mod or "*")
224
+ nxt = rest[0] if rest else ""
225
+ # 고정 스크립트는 «레포 안 상대 경로» 만이다. 절대 경로는 /dev/stdin · //dev/stdin · /./dev/fd/0 처럼
226
+ # 같은 파일을 가리키는 철자가 끝이 없어 열거로 못 막는다(codex 카트리지 R9·R10) — 절대 경로·레포 밖(..)
227
+ # 은 H1. 절대 경로 스크립트(/usr/local/bin/x.py)는 과차단을 받아들인다.
228
+ rel = posixpath.normpath(nxt) if nxt else ""
229
+ if not nxt or nxt.startswith("-") or re.search(r"[*?\[]", nxt) or not _SCRIPT_TARGET_RE.search(nxt) \
230
+ or nxt.startswith("/") or nxt.startswith("~") or rel == ".." or rel.startswith("../") \
231
+ or not re.fullmatch(r"[A-Za-z0-9_./-]+", nxt): # 셸 전개($ ` { 따옴표)가 경로를 바꾼다(codex 카트리지 R11)
232
+ return "인터프리터 `%s` 와일드카드 (고정 스크립트·모듈이 바로 뒤에 없다)" % head
233
+ return None
234
+
235
+
236
+ def _tokenset_irreversible(seg):
237
+ """서브커맨드 앞 옵션(`git -C. push`, `gh --repo x pr merge`, `npm --registry u publish`)을 옵션
238
+ 목록으로 쫓지 않고 «토큰 집합» 으로 본다: 머리가 git/gh/npm/pnpm/yarn/twine 이면 머리 뒤 비-`-` 토큰
239
+ 집합 어디에든 비가역 서브커맨드가 있으면 H1.
240
+ 🟥 알려진 과차단: `git log --grep push` · `git commit -m push` 도 걸린다 — 비가역 표면이라 그 방향이 맞다."""
241
+ toks = seg.split()
242
+ if not toks:
243
+ return None
244
+ head = re.sub(r"(?::\*|\*)$", "", toks[0])
245
+ raw = [re.sub(r"(?::\*|\*)$", "", t) for t in toks[1:]]
246
+ words = {t for t in raw if t and not t.startswith("-")}
247
+ if head == "git":
248
+ if "push" in words:
249
+ return "git push (토큰 집합)"
250
+ if "reset" in words and "--hard" in raw:
251
+ return "git reset --hard (토큰 집합)"
252
+ if "branch" in words and any(re.match(r"^(?:-[A-Za-z]*[dD]|--delete)$", t) for t in raw):
253
+ return "git branch 삭제 (토큰 집합)"
254
+ if "clean" in words and any(re.match(r"^-[A-Za-z]*f", t) for t in raw):
255
+ return "git clean -f (토큰 집합)"
256
+ elif head == "gh":
257
+ if ("pr" in words and "merge" in words) or ("repo" in words and "delete" in words) \
258
+ or ("release" in words and "delete" in words):
259
+ return "gh 비가역 서브커맨드 (토큰 집합)"
260
+ elif head in ("npm", "pnpm", "yarn"):
261
+ if "publish" in words or (head == "npm" and "unpublish" in words):
262
+ return "%s publish (토큰 집합)" % head
263
+ elif head == "twine":
264
+ if "upload" in words:
265
+ return "twine upload (토큰 집합)"
266
+ return None
267
+
268
+
269
+ def tools_bash_entries(value):
270
+ """frontmatter allowed-tools 값(문자열: 쉼표/공백 구분, [..] 가능) → Bash 항목 리스트."""
271
+ return [t for t in re.findall(r"[A-Za-z_][\w.-]*(?:\([^)]*\))?", value) if t == "Bash" or t.startswith("Bash(")]
272
+
273
+
274
+ # ── H2: 지침 본문의 «확인 없이» 비가역 허용 ──────────────────────────────
275
+ IRREV_RE = re.compile(
276
+ r"(?<![A-Za-z])rm(?![A-Za-z])|삭제|지우|지워|덮어|git\s+push|(?<![A-Za-z])push(?![A-Za-z])|푸시|"
277
+ r"force[- ]push|publish|발행|배포|(?<![A-Za-z])merge(?![A-Za-z])|머지|병합|reset\s+--hard|"
278
+ r"(?<![A-Za-z])delete(?![A-Za-z])|(?<![A-Za-z])drop(?![A-Za-z])|(?<![A-Za-z])overwrite", re.I)
279
+ # 허용 어휘. «묻지 않고» 처럼 부정어가 허용 표현 안에 들어 있는 것은 부정 판정 전에 먼저 걷어낸다.
280
+ PERMIT_RE = re.compile(
281
+ r"확인\s*없이|(?:묻|확인하)지\s*(?:말고|않고)|never\s+ask\b|don'?t\s+ask\b|do\s+not\s+ask\b|no\s+confirmation|알아서|자동으로|[가-힣]도\s*(?:된다|됩니다|됨)|허용했|"
282
+ r"without\s+(?:asking|confirm\w*|approval|prompt\w*|permission)|autonomously|automatically|freely|"
283
+ r"(?:is|are)\s+allowed\s+to|allowed\s+to", re.I)
284
+ # 바로 다음 문장까지 보는 «인접» 판정에는 강한 허용 어휘만 쓴다 — 「…해도 된다」는 앞 문장의 동작이
285
+ # 아니라 다른 얘기일 수 있어(실물 오탐: «커밋·push) 요청을 받으면 … 사용한다. 단순 질문에는 직접 답해도 된다.»).
286
+ STRONG_PERMIT_RE = re.compile(
287
+ r"확인\s*없이|묻지\s*(?:말고|않고)|알아서|"
288
+ r"without\s+(?:asking|confirm\w*|approval|prompt\w*|permission)|autonomously", re.I)
289
+ # «허용을 뜻하는 부정 표현» — 부정어처럼 보이지만 금지가 아니다. 부정 판정 전에 문장에서 먼저 지운다.
290
+ ALLOW_NEG_RE = re.compile(
291
+ r"확인\s*없이|(?:묻|확인하)지\s*(?:말고|않고)|never\s+ask\b(?:\s+for\s+(?:confirmation|permission|approval))?|"
292
+ r"don'?t\s+ask\b|do\s+not\s+ask\b|no\s+confirmation|without\s+(?:asking|confirm\w*|approval|prompt\w*|permission)", re.I)
293
+ NEGATE_RE = re.compile(
294
+ r"하지\s*않|하지\s*말|않는다|않는|않음|않습니다|금지|말\s*것|말라|하지\s*마|허용하지|불가|못\s*한다|안\s*한다|"
295
+ r"never|do\s+not|don't|must\s+not|not\s+allowed|forbidden|prohibit|disallow", re.I)
296
+
297
+
298
+ def _split_units(text):
299
+ """(줄번호, 단위 리스트) — 줄 단위로 끊고, 줄 안에서는 문장부호 뒤 공백으로 다시 끊는다."""
300
+ out = []
301
+ for i, line in enumerate(text.splitlines(), 1):
302
+ parts = [p.strip() for p in re.split(r"(?<=[.!?。])\s+", line) if p.strip()]
303
+ out.append((i, parts))
304
+ return out
305
+
306
+
307
+ def h2_scan(text):
308
+ """text → [(줄, 원문 문장)]. 같은 문장, 또는 같은 줄의 바로 다음 문장에 허용 어휘가 있고
309
+ 부정어가 없을 때 걸린다."""
310
+ hits = []
311
+ for lineno, parts in _split_units(text):
312
+ for k, unit in enumerate(parts):
313
+ if not IRREV_RE.search(unit):
314
+ continue
315
+ span = [unit]
316
+ if k + 1 < len(parts):
317
+ span.append(parts[k + 1])
318
+ own = PERMIT_RE.search(unit)
319
+ nxt = len(span) == 2 and STRONG_PERMIT_RE.search(span[1])
320
+ if not own and not nxt:
321
+ continue
322
+ # 부정 판정은 허용 표현을 걷어낸 뒤에 — 「묻지 않고」의 «않고» 가 금지로 읽히지 않게.
323
+ bare_unit = ALLOW_NEG_RE.sub(" ", PERMIT_RE.sub(" ", unit))
324
+ # 비가역 동작이 든 문장 자신이 부정이면 금지문. 허용어가 «다음 문장»에만 있으면 그 문장도 본다.
325
+ if NEGATE_RE.search(bare_unit):
326
+ continue
327
+ if not own and len(span) == 2:
328
+ if NEGATE_RE.search(ALLOW_NEG_RE.sub(" ", PERMIT_RE.sub(" ", span[1]))):
329
+ continue
330
+ hits.append((lineno, unit))
331
+ return hits
332
+
333
+
334
+ # ── 파서 ─────────────────────────────────────────────────────────────────
335
+ class ParseError(Exception):
336
+ pass
337
+
338
+
339
+ def read_text(path):
340
+ try:
341
+ with open(path, "r", encoding="utf-8") as fh:
342
+ return fh.read()
343
+ except (OSError, UnicodeDecodeError) as e:
344
+ raise ParseError("읽기 실패: %s (%s)" % (path, e))
345
+
346
+
347
+ def parse_frontmatter(text, path):
348
+ """→ (dict, {키:줄번호}, 본문 시작 줄번호). 닫는 --- 가 없으면 ParseError."""
349
+ lines = text.lstrip("").splitlines()
350
+ if not lines or lines[0].strip() != "---":
351
+ raise ParseError("frontmatter 없음(첫 줄이 --- 아님): %s" % path)
352
+ end = None
353
+ for i in range(1, len(lines)):
354
+ if lines[i].strip() == "---":
355
+ end = i
356
+ break
357
+ if end is None:
358
+ raise ParseError("frontmatter 닫는 --- 없음: %s" % path)
359
+ fm, where, key = {}, {}, None
360
+ for i in range(1, end):
361
+ ln = lines[i]
362
+ if not ln.strip() or ln.lstrip().startswith("#"):
363
+ continue
364
+ m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", ln)
365
+ if m and not ln.startswith((" ", "\t")):
366
+ key = m.group(1)
367
+ fm[key] = m.group(2).strip()
368
+ where[key] = i + 1
369
+ elif key is not None and ln.startswith((" ", "\t")):
370
+ fm[key] = (fm[key] + " " + ln.strip()).strip()
371
+ else:
372
+ raise ParseError("frontmatter 줄 해석 불가 (%s:%d): %s" % (path, i + 1, ln))
373
+ for k in ("description",):
374
+ if fm.get(k, "") in (">", "|", ">-", "|-"):
375
+ fm[k] = ""
376
+ return fm, where, end + 2
377
+
378
+
379
+ # ── 검사 ─────────────────────────────────────────────────────────────────
380
+ DONE_WHEN_RE = re.compile(
381
+ # 출처: templates/regression_guard.sh 의 done_when_pattern
382
+ # '^##[[:space:]]+(Done When|Completion Criteria)([[:space:]].*)?$' (ERE → Python 이식)
383
+ # 한글 «완료 조건/기준» 은 이 검사기의 확장이다(그쪽 패턴엔 없다).
384
+ r"^##\s+(?:Done When|Completion Criteria)(?:\s.*)?$|^##\s+완료\s*(?:조건|기준)(?:\s.*)?$", re.M)
385
+ RO_CLAIM_RE = re.compile(r"읽기\s*전용|read-?only|수정하지\s*않|변경하지\s*않|(?:파일|코드)[을를]?\s*(?:수정|변경)하지\s*않", re.I)
386
+ WRITE_TOOL_RE = re.compile(r"\b(Bash|Edit|Write|NotebookEdit)\b")
387
+ BASH_LIMIT_RE = re.compile(r"Bash[^\n]{0,40}(?:제한|범위|만\s|only|한정)|(?:읽기\s*전용|read-?only)[^\n]{0,20}(?:명령|command)", re.I)
388
+ FILE_EXT = r"(?:md|py|json|sh|toml|ya?ml|txt|csv|js|ts|html|cfg|ini)"
389
+ PLACEHOLDER_RE = re.compile(r"YYYY|MM-?DD|HHMM|\.\.\.|[<>{}*\[\]]|\bxxx\b|NNN", re.I)
390
+ ROLE_SUFFIX_RE = re.compile(r"(team|orchestrator|tester|reviewer|developer|testing|review|writer|organizer|qa)$")
391
+
392
+
393
+ class Report:
394
+ def __init__(self, target):
395
+ self.target = target
396
+ self.human, self.warn, self.info, self.errors = [], [], [], []
397
+
398
+ def add(self, bucket, rid, path, line, text, detail=""):
399
+ getattr(self, bucket).append({"id": rid, "file": path, "line": line, "text": text, "detail": detail})
400
+
401
+ def verdict(self):
402
+ if self.errors:
403
+ return "HARNESS_ERROR", RC_ERROR
404
+ if self.human:
405
+ return "HUMAN_REVIEW", RC_HUMAN
406
+ return "PASS", RC_PASS
407
+
408
+
409
+ def _line_of(raw, needle):
410
+ idx = raw.find(needle)
411
+ return raw.count("\n", 0, idx) + 1 if idx >= 0 else 0
412
+
413
+
414
+ def check(target, exclude_skills=()):
415
+ rep = Report(target)
416
+ if not os.path.isdir(target):
417
+ rep.errors.append({"id": "E1", "file": target, "line": 0, "text": "대상 디렉터리가 없다", "detail": ""})
418
+ return rep
419
+ root = os.path.abspath(target)
420
+ cl = os.path.join(root, ".claude")
421
+ skip = set(GENERATOR_SKILLS) | set(exclude_skills)
422
+
423
+ docs = [] # (rel, kind, text, fm, where, body_start)
424
+ all_names, agent_names = set(), set()
425
+ n_target = 0
426
+
427
+ def rel(p):
428
+ return os.path.relpath(p, root)
429
+
430
+ def load(path, kind):
431
+ try:
432
+ text = read_text(path)
433
+ fm = where = None
434
+ start = 1
435
+ if kind in ("agent", "skill"):
436
+ fm, where, start = parse_frontmatter(text, rel(path))
437
+ docs.append((rel(path), kind, text, fm, where, start))
438
+ return True
439
+ except ParseError as e:
440
+ rep.errors.append({"id": "E2", "file": rel(path), "line": 0, "text": str(e), "detail": ""})
441
+ return False
442
+
443
+ def present(path):
444
+ """lexists 로 찾는다 — 깨진 링크·디렉터리를 «없음» 으로 접지 않는다(A6). 일반 파일이 아니면 오류."""
445
+ if not os.path.lexists(path):
446
+ return False
447
+ if not os.path.isfile(path):
448
+ rep.errors.append({"id": "E5", "file": rel(path), "line": 0,
449
+ "text": "일반 파일이 아니다(깨진 링크·디렉터리 등) — 읽을 수 없음", "detail": ""})
450
+ return False
451
+ return True
452
+
453
+ # Claude Code 는 루트 CLAUDE.md 와 .claude/CLAUDE.md 둘 다 프로젝트 지침으로 싣는다 — 둘 다 읽는다.
454
+ _seen_cm = set() # 한쪽이 다른 쪽을 가리키는 링크면 같은 파일을 두 번 세지 않는다 (codex 회귀 리뷰)
455
+ for cm in (os.path.join(root, "CLAUDE.md"), os.path.join(cl, "CLAUDE.md")):
456
+ if os.path.exists(cm):
457
+ _real = os.path.realpath(cm)
458
+ if _real in _seen_cm:
459
+ continue
460
+ _seen_cm.add(_real)
461
+ if present(cm):
462
+ n_target += 1
463
+ load(cm, "claude_md")
464
+ elif os.path.lexists(cm):
465
+ n_target += 1
466
+ adir = os.path.join(cl, "agents")
467
+ if os.path.isdir(adir):
468
+ for fn in sorted(os.listdir(adir)):
469
+ if fn.endswith(".md"):
470
+ n_target += 1
471
+ agent_names.add(fn[:-3])
472
+ all_names.add(fn[:-3])
473
+ if present(os.path.join(adir, fn)):
474
+ load(os.path.join(adir, fn), "agent")
475
+ sdir = os.path.join(cl, "skills")
476
+ if os.path.isdir(sdir):
477
+ for d in sorted(os.listdir(sdir)):
478
+ all_names.add(d) # 생성기 스킬 이름도 «실재 이름» 집합엔 들어간다
479
+ if d in skip:
480
+ continue
481
+ # 발견은 listdir 기반 대소문자 무시 — macOS(대소문자 무시 FS)에서는 isfile 로 `skill.md` 와
482
+ # `SKILL.md` 를 못 가르고, 리눅스에서는 `SKILL.md` 고정 결합이 `skill.md` 를 «스킬 없음» 으로 놓친다.
483
+ try:
484
+ entries = sorted(os.listdir(os.path.join(sdir, d)))
485
+ except OSError:
486
+ continue
487
+ cands = [e for e in entries if e.lower() == "skill.md"]
488
+ if not cands:
489
+ continue
490
+ actual = "SKILL.md" if "SKILL.md" in cands else cands[0]
491
+ sp = os.path.join(sdir, d, actual)
492
+ n_target += 1
493
+ if actual != "SKILL.md":
494
+ rep.add("warn", "W7", rel(sp), 1, actual,
495
+ "스킬 정의 파일 이름이 정확히 SKILL.md 가 아님 — 대소문자 구분 파일시스템에서 스킬로 "
496
+ "로드되지 않을 수 있다(미확인: 이 검사기는 로드 여부를 실행해 확인하지 않았다)")
497
+ if present(sp):
498
+ load(sp, "skill")
499
+ settings = []
500
+ for sn in ("settings.json", "settings.local.json"):
501
+ sp = os.path.join(cl, sn)
502
+ if os.path.lexists(sp):
503
+ n_target += 1
504
+ if not present(sp):
505
+ continue
506
+ try:
507
+ raw = read_text(sp)
508
+ data = json.loads(raw)
509
+ except (ParseError, ValueError) as e:
510
+ rep.errors.append({"id": "E3", "file": rel(sp), "line": 0, "text": "settings 읽기/JSON 실패: %s" % e, "detail": ""})
511
+ continue
512
+ settings.append((rel(sp), raw, data))
513
+
514
+ if n_target == 0 and not rep.errors:
515
+ rep.errors.append({"id": "E4", "file": target, "line": 0,
516
+ "text": "검사할 하네스가 없다 (CLAUDE.md · 에이전트 · 스킬 · settings 전부 없음)", "detail": ""})
517
+ if not rep.errors and not settings and all(not d[2].strip() for d in docs):
518
+ rep.errors.append({"id": "E4", "file": target, "line": 0,
519
+ "text": "검사할 내용이 없다 (발견된 산출물이 전부 공백뿐)", "detail": ""})
520
+ if rep.errors:
521
+ return rep
522
+
523
+ # H1 ─ settings
524
+ for path, raw, data in settings:
525
+ if not isinstance(data, dict):
526
+ rep.errors.append({"id": "E3", "file": path, "line": 0, "text": "settings 최상위가 객체가 아니다", "detail": ""})
527
+ continue
528
+ if "permissions" not in data:
529
+ continue
530
+ perms = data["permissions"]
531
+ if not isinstance(perms, dict):
532
+ rep.errors.append({"id": "E3", "file": path, "line": 0, "text": "permissions 가 객체가 아니다", "detail": ""})
533
+ continue
534
+ if "allow" not in perms:
535
+ continue
536
+ allow = perms["allow"]
537
+ if not isinstance(allow, list):
538
+ rep.errors.append({"id": "E3", "file": path, "line": 0, "text": "permissions.allow 가 배열이 아니다", "detail": ""})
539
+ continue
540
+ if any(not isinstance(e, str) for e in allow):
541
+ rep.errors.append({"id": "E3", "file": path, "line": 0, "text": "permissions.allow 원소가 문자열이 아니다", "detail": ""})
542
+ continue
543
+ for entry in allow:
544
+ lab = h1_match(entry)
545
+ if lab:
546
+ ln = _line_of(raw, json.dumps(entry, ensure_ascii=False)) or _line_of(raw, str(entry))
547
+ rep.add("human", "H1", path, ln, entry, lab)
548
+ if rep.errors:
549
+ return rep
550
+
551
+ # S1 ─ 스킬 frontmatter allowed-tools = «묻지 않고 실행» 사전 승인이므로 settings allow 와 같은 판정기.
552
+ # (에이전트 frontmatter 의 tools 는 «사용 가능한 도구» 목록이지 사전 승인이 아니다 — 맨 Bash 는
553
+ # 아래 W3 정보로 남긴다. 둘을 같은 H1 로 세면 모든 생성 에이전트가 사람 확인이 된다.)
554
+ for path, kind, text, fm, where, start in docs:
555
+ if kind == "skill" and "allowed-tools" in fm:
556
+ for ent in tools_bash_entries(fm["allowed-tools"]):
557
+ lab = h1_match(ent)
558
+ if lab:
559
+ rep.add("human", "H1", path, where.get("allowed-tools", 1), ent, "스킬 allowed-tools(사전 승인): " + lab)
560
+
561
+ # H2 ─ 본문
562
+ for path, kind, text, fm, where, start in docs:
563
+ for ln, sent in h2_scan(text):
564
+ rep.add("human", "H2", path, ln, sent, "비가역 동작을 확인 없이 허용")
565
+
566
+ # 에이전트
567
+ for path, kind, text, fm, where, start in docs:
568
+ if kind != "agent":
569
+ continue
570
+ tools = fm.get("tools")
571
+ if tools is None:
572
+ rep.add("warn", "W2", path, 1, "(tools 줄 없음)", "모든 도구 상속")
573
+ m = RO_CLAIM_RE.search(fm.get("description", "") + "\n" + text)
574
+ if m: # tools 없음 = 모든 도구 상속이므로 «읽기 전용» 주장은 쓰기·Bash 상속과 충돌한다
575
+ mm = RO_CLAIM_RE.search(text)
576
+ ln = text[:mm.start()].count("\n") + 1 if mm else 1
577
+ rep.add("warn", "W1", path, ln, "(tools 줄 없음)", "읽기 전용 주장 vs tools 없음 → 쓰기·Bash 상속")
578
+ else:
579
+ if RO_CLAIM_RE.search(fm.get("description", "") + "\n" + text) and WRITE_TOOL_RE.search(tools):
580
+ m = RO_CLAIM_RE.search(text)
581
+ ln = text[:m.start()].count("\n") + 1 if m else where.get("tools", 1)
582
+ rep.add("warn", "W1", path, ln, "tools: %s" % tools, "읽기 전용 주장 vs 쓰기/Bash 도구")
583
+ if re.search(r"\bBash\b", tools) and "Bash(" not in tools and not BASH_LIMIT_RE.search(text):
584
+ rep.add("info", "W3", path, where.get("tools", 1), "tools: %s" % tools, "Bash 범위 제한 서술 없음 (정보)")
585
+
586
+ # 스킬
587
+ for path, kind, text, fm, where, start in docs:
588
+ if kind != "skill":
589
+ continue
590
+ if not fm.get("description", "").strip():
591
+ rep.add("warn", "W6", path, where.get("description", 1), "(description 비어 있음)", "")
592
+ if not DONE_WHEN_RE.search(text):
593
+ rep.add("info", "W5", path, 1, "Done When 절 없음", "FH 기준이다 — 생성기의 결함이 아니다")
594
+
595
+ # W4 ─ 죽은 참조 (+ 입출력 경로 정보)
596
+ basenames = set()
597
+ for dp, dn, fns in os.walk(root):
598
+ dn[:] = [d for d in dn if d != ".git"]
599
+ basenames.update(fns)
600
+ for path, kind, text, fm, where, start in docs:
601
+ fdir = os.path.dirname(os.path.join(root, path))
602
+ for i, line in enumerate(text.splitlines(), 1):
603
+ for tok in re.findall(r"`([^`\n]+)`", line):
604
+ tok = tok.strip()
605
+ if (not tok or re.search(r"[\s$=(),;|\"']", tok) or tok.startswith(("http", "-", "/", "~"))):
606
+ continue
607
+ is_pathlike = "/" in tok or re.search(r"\.%s$" % FILE_EXT, tok)
608
+ if is_pathlike:
609
+ if (tok.endswith("/") and not PLACEHOLDER_RE.search(tok) and not tok.startswith("_workspace")
610
+ and (os.path.isdir(os.path.join(root, tok)) or os.path.isdir(os.path.join(fdir, tok)))):
611
+ continue # 실재하는 디렉터리 — 말할 것 없음
612
+ if tok.startswith("_workspace") or PLACEHOLDER_RE.search(tok) or tok.endswith("/"):
613
+ rep.add("info", "IO", path, i, tok, "아직 없는 입출력 경로(런타임/자리표시자/디렉터리) — 죽은 참조로 세지 않음")
614
+ continue
615
+ if "/" not in tok:
616
+ if tok not in basenames:
617
+ rep.add("info", "IO", path, i, tok, "슬래시 없는 파일명이 트리에 없음 — 런타임 산출일 수 있어 판정하지 않음")
618
+ continue
619
+ cand = tok[2:] if tok.startswith("./") else tok
620
+ # 해석 기준 셋: 대상 루트 · 그 파일이 있는 디렉터리 · .claude/ (스킬 문서가 `skills/x/skill.md` 처럼 쓴다)
621
+ if not (os.path.exists(os.path.join(root, cand)) or os.path.exists(os.path.join(fdir, cand))
622
+ or os.path.exists(os.path.join(cl, cand))):
623
+ rep.add("warn", "W4", path, i, tok, "죽은 참조: 대상 루트·파일 디렉터리 어느 쪽에도 없음")
624
+ elif re.match(r"^[a-z][a-z0-9]*(-[a-z0-9]+)+$", tok) and tok not in all_names:
625
+ first = tok.split("-")[0]
626
+ family = any(n.split("-")[0] == first for n in all_names)
627
+ if family or ROLE_SUFFIX_RE.search(tok):
628
+ rep.add("warn", "W4", path, i, tok, "죽은 참조: 같은 계열 이름의 스킬/에이전트가 실재하지 않음")
629
+ # 같은 (파일,줄,토큰) 중복 제거
630
+ for bucket in ("warn", "info", "human"):
631
+ seen, uniq = set(), []
632
+ for it in getattr(rep, bucket):
633
+ k = (it["id"], it["file"], it["line"], it["text"])
634
+ if k not in seen:
635
+ seen.add(k)
636
+ uniq.append(it)
637
+ setattr(rep, bucket, uniq)
638
+ return rep
639
+
640
+
641
+ # ── 출력 ─────────────────────────────────────────────────────────────────
642
+ def render_text(rep):
643
+ v, rc = rep.verdict()
644
+ lines = ["판정: %s (rc=%d) — 사람 확인 %d · 경고 %d · 정보 %d%s" % (
645
+ v, rc, len(rep.human), len(rep.warn), len(rep.info), " · 오류 %d" % len(rep.errors) if rep.errors else "")]
646
+ lines.append("대상: %s" % rep.target)
647
+ secs = [("오류(HARNESS_ERROR)", rep.errors), ("사람 확인(HUMAN_REVIEW) — 비가역 권한", rep.human),
648
+ ("경고(WARN)", rep.warn), ("정보(INFO)", rep.info)]
649
+ for title, items in secs:
650
+ if not items:
651
+ continue
652
+ lines.append("")
653
+ lines.append("[%s]" % title)
654
+ for it in items:
655
+ tag = it["id"]
656
+ if tag == "W5":
657
+ tag = "W5/FH 기준"
658
+ lines.append(" %s %s:%s — %s%s" % (tag, it["file"], it["line"], it["text"],
659
+ (" (%s)" % it["detail"]) if it["detail"] else ""))
660
+ lines.append("")
661
+ lines.append("※ 이 검사는 기록의 형태만 본다(정규식). PASS 는 안전 보증이 아니고, 비가역 권한의 결론은 사람 몫이다.")
662
+ return "\n".join(lines)
663
+
664
+
665
+ def render_json(rep):
666
+ v, rc = rep.verdict()
667
+ return json.dumps({"verdict": v, "rc": rc, "target": rep.target, "human_review": rep.human,
668
+ "warnings": rep.warn, "info": rep.info, "errors": rep.errors},
669
+ ensure_ascii=False, indent=2)
670
+
671
+
672
+ # ── selftest (known-pair) ───────────────────────────────────────────────
673
+ def selftest():
674
+ bad = []
675
+
676
+ def expect(name, cond):
677
+ if not cond:
678
+ bad.append(name)
679
+ expect("H1+ git push", h1_match("Bash(git push origin:*)") is not None)
680
+ expect("H1+ rm", h1_match("Bash(rm -f todo.json)") is not None)
681
+ expect("H1+ Bash 단독", h1_match("Bash") is not None and h1_match("Bash(*)") is not None)
682
+ expect("H1+ reset --hard", h1_match("Bash(git reset --hard:*)") is not None)
683
+ expect("H1- pytest", h1_match("Bash(python -m pytest:*)") is None)
684
+ expect("H1- git add", h1_match("Bash(git add:*)") is None)
685
+ expect("H1- Read", h1_match("Read(./src/**)") is None)
686
+ expect("H1+ sh:*", h1_match("Bash(sh:*)") is not None)
687
+ expect("H1+ python3 -c:*", h1_match("Bash(python3 -c:*)") is not None)
688
+ expect("H1- python3 fixed script", h1_match("Bash(python3 scripts/x.py:*)") is None)
689
+ expect("H1+ timeout 5 *", h1_match("Bash(timeout 5 *)") is not None)
690
+ expect("H1+ env -i *", h1_match("Bash(env -i *)") is not None)
691
+ expect("H1+ git alias", h1_match("Bash(git -c alias.s=!x s)") is not None)
692
+ expect("glob 후보 ⊇ 모든 머리 집합", (_WRAP_HEADS | _PROGTEXT_HEADS | _PKG_MGR_HEADS | _PKG_EXEC_HEADS
693
+ | set(_INTERP_BASE)) <= set(_GLOB_CANDIDATES))
694
+ expect("H2+ ko", len(h2_scan("git push 는 확인 없이 해도 된다.")) == 1)
695
+ expect("H2- ko", len(h2_scan("git push 는 확인 없이 하지 않는다.")) == 0)
696
+ expect("H2+ en", len(h2_scan("The agent may push to main without asking.")) == 1)
697
+ expect("H2- en", len(h2_scan("Never push to main without asking the user.")) == 0)
698
+ if bad:
699
+ print("selftest FAIL: " + ", ".join(bad))
700
+ return 1
701
+ print("selftest ok (known-pair 18)")
702
+ return 0
703
+
704
+
705
+ def main(argv):
706
+ args = argv[1:]
707
+ if "--selftest" in args:
708
+ return selftest()
709
+ want_json = "--json" in args
710
+ excl, target, i = [], None, 0
711
+ while i < len(args):
712
+ a = args[i]
713
+ if a == "--json":
714
+ pass
715
+ elif a == "--exclude-skill" and i + 1 < len(args):
716
+ i += 1
717
+ excl.append(args[i])
718
+ elif a.startswith("-"):
719
+ sys.stderr.write("알 수 없는 옵션: %s\n" % a)
720
+ return RC_ERROR
721
+ elif target is None:
722
+ target = a
723
+ else:
724
+ sys.stderr.write("대상은 하나만 받는다\n")
725
+ return RC_ERROR
726
+ i += 1
727
+ if target is None:
728
+ sys.stderr.write("사용법: generated_harness_check.py <대상 디렉터리> [--json] [--exclude-skill NAME] | --selftest\n")
729
+ return RC_ERROR
730
+ try:
731
+ rep = check(target, excl)
732
+ except Exception as e: # 계기 자신의 오류도 PASS 로 새지 않게
733
+ sys.stderr.write("HARNESS_ERROR: %s\n" % e)
734
+ return RC_ERROR
735
+ print(render_json(rep) if want_json else render_text(rep))
736
+ return rep.verdict()[1]
737
+
738
+
739
+ if __name__ == "__main__":
740
+ sys.exit(main(sys.argv))