@routinecrew/routinecode 2.31.86 → 2.31.88
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.
- package/bin/cli.sh +10 -0
- package/bin/prompt-vault.dat +1 -1
- package/bin/rc-login.js +5 -4
- package/bin/rc-savings.js +808 -0
- package/bin/rc-skills.js +1 -1
- package/bin/rc-suggestions.js +100 -0
- package/bin/rc-team.js +1 -1
- package/hooks/hooks-config.json +9 -0
- package/hooks/lib/attest_reader.py +16 -1
- package/hooks/lib/calibration.json +89 -0
- package/hooks/lib/card_gate.py +735 -0
- package/hooks/lib/cc-surface.json +1 -1
- package/hooks/lib/command_fix.py +209 -0
- package/hooks/lib/delegate_nudge.py +179 -0
- package/hooks/lib/deploy_suggest.py +312 -0
- package/hooks/lib/design_pick_nudge.py +86 -0
- package/hooks/lib/emit_raw.py +4 -0
- package/hooks/lib/i18n.py +48 -20
- package/hooks/lib/knowledge_items.py +189 -19
- package/hooks/lib/knowledge_stock.py +604 -0
- package/hooks/lib/ops_guard.py +549 -0
- package/hooks/lib/prices.json +8 -0
- package/hooks/lib/route_ledger.py +622 -0
- package/hooks/lib/route_rules.json +88 -0
- package/hooks/lib/savings_emit.py +93 -0
- package/hooks/lib/secret_filter.py +11 -0
- package/hooks/lib/sync_manager.py +4 -1
- package/hooks/post-bash-verify.sh +14 -0
- package/hooks/post-edit-track.sh +9 -0
- package/hooks/pre-agent-spawn.mjs +1 -1
- package/hooks/pre-agent-spawn.sh +34 -2
- package/hooks/pre-bash-guard.sh +22 -0
- package/hooks/pre-bash-knowledge.sh +12 -2
- package/hooks/pre-credit-guard.sh +1 -1
- package/hooks/pre-edit-delegate.sh +15 -0
- package/hooks/pre-edit-guard.sh +10 -0
- package/hooks/pre-mark-complete.sh +54 -12
- package/hooks/pre-read-guard.sh +10 -0
- package/hooks/session-start.sh +15 -10
- package/hooks/stop-usage-metrics.sh +6 -0
- package/hooks/subagent-stop-usage.sh +36 -4
- package/hooks/user-prompt-submit.sh +9 -0
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-routinecode/dist/criteria-card.js +1 -0
- package/mcp-routinecode/dist/design-judge.js +1 -0
- package/mcp-routinecode/dist/edit-tracker.js +1 -1
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
- package/mcp-routinecode/dist/index.js +1 -1
- package/mcp-routinecode/dist/known-solutions.js +1 -1
- package/mcp-routinecode/dist/ledger-miner.js +1 -1
- package/mcp-routinecode/dist/normalize-sig.js +1 -1
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -1
- package/mcp-routinecode/dist/pattern-matcher.js +1 -1
- package/mcp-routinecode/dist/route-match.js +1 -1
- package/mcp-routinecode/dist/routines.js +1 -1
- package/mcp-routinecode/dist/rule-engine.js +1 -1
- package/mcp-routinecode/dist/rule-promoter.js +1 -1
- package/mcp-routinecode/dist/session-registry.js +1 -1
- package/mcp-routinecode/dist/skill-pack/sync.js +40 -14
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/thinking-judge.js +1 -0
- package/mcp-routinecode/dist/verification.js +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/agents/analyzer.md.sealed +1 -1
- package/plugin/agents/architect.md.sealed +1 -1
- package/plugin/agents/crawler.md.sealed +1 -1
- package/plugin/agents/explorer.md.sealed +1 -1
- package/plugin/agents/implementor-lite.md.sealed +1 -0
- package/plugin/agents/implementor.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- package/plugin/agents/ops-lite.md.sealed +1 -0
- package/plugin/agents/planner.md.sealed +1 -1
- package/plugin/agents/recorder.md.sealed +1 -1
- package/plugin/agents/reviewer.md.sealed +1 -1
- package/plugin/agents/runner-lite.md.sealed +1 -0
- package/plugin/agents/verifier.md.sealed +1 -1
- package/plugin/commands/analyze.md.sealed +1 -1
- package/plugin/commands/plan.md.sealed +1 -1
- package/plugin/commands/rc.md.sealed +1 -1
- package/plugin/commands/receipt.md.sealed +1 -1
- package/plugin/commands/recharge.md.sealed +1 -1
- package/plugin/commands/routines.md.sealed +1 -1
- package/plugin/commands/share.md.sealed +1 -1
- package/plugin/routinecode-prompt.md.sealed +1 -1
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""구현 카드 관문 — 설계 34 §5.1·§5.2·§5.5·§5.6·§6.3 (P2).
|
|
3
|
+
|
|
4
|
+
implementor-lite(haiku) 에만 강제한다. 메인 세션·다른 에이전트는 관여하지 않는다(출력 불변, 내부 오류 = 관여 안 함).
|
|
5
|
+
|
|
6
|
+
agent-pre PreToolUse(Agent) implementor-lite 호출만:
|
|
7
|
+
CARD_ID 없음·형식 오류 → deny(카드 양식 안내), CARD_KIND: risk → deny(implementor(Sonnet) 로),
|
|
8
|
+
arm_of(CARD_ID) == control(§6.3, P0 와 같은 sha256 % round(1/control_ratio)) → deny + 같은 카드를
|
|
9
|
+
routinecode:implementor 에 "ARM: control" 줄과 함께 보내라는 안내. 원장 ev=card_reject|control_redirect.
|
|
10
|
+
path-fix PreToolUse(Read·Glob·Edit·Write·MultiEdit·Bash cd) implementor-lite 만(F5):
|
|
11
|
+
경로가 없고 저장소 루트 아래 같은 이름이 정확히 1개면 deny "경로 정정: <정정 경로>". 원장 ev=path_fix.
|
|
12
|
+
subagent-stop SubagentStop implementor-lite → 관문 G1~G4 + 보고 블록. 실패면 {"decision":"block"}
|
|
13
|
+
(작업자가 계속한다). 카드당 차단은 gate.max_blocks(2)회까지, 그 뒤는 멈추게 두고 gate_fail 기록.
|
|
14
|
+
reviewer → "REVIEW CARD <id>: DEFECTS <n>" 블록을 원장 ev=review 로(출력 없음).
|
|
15
|
+
|
|
16
|
+
관문(§5.5):
|
|
17
|
+
G1 마지막 편집 뒤 run_tests/build_check 호출이 이 작업자 transcript 에 있고, 그 편집 시각 뒤의 통과 증거
|
|
18
|
+
(hooks/lib/attest_reader.read_attestations — 서명 검증된 행, projectDir 가 저장소와 겹치는 것)가 있다.
|
|
19
|
+
증거에는 작업자 id 가 없다 → 작업자 transcript 의 마지막 편집 시각으로 귀속한다.
|
|
20
|
+
G2 작업자가 편집한 기존 시험 파일(HEAD 에 있던 것)에서 HEAD 의 assert 줄이 사라졌고, 그 줄이 작업자 Edit 의
|
|
21
|
+
old_string 에 있었거나 작업자가 파일을 통째로 Write 했다 → 차단(추가만 허용). Bash 로 고친 시험은 보지 않는다.
|
|
22
|
+
G3 보고 TESTS_ADDED 의 이름이 저장소 시험 파일에 있다.
|
|
23
|
+
G4 TESTS_ADDED 중 1개 이상이 작업자가 편집한 시험 파일에 있다(새 시험 0개 = 차단).
|
|
24
|
+
보고 블록(CARD_REPORT/USAGES/ROOT_CAUSE/TESTS_ADDED/CHECK/KEEP/RESULT)이 없거나 CHECK·KEEP 항목 수가 카드보다 적다 → 차단.
|
|
25
|
+
|
|
26
|
+
규칙 = route_rules.json "gate". 끄기: ROUTINECODE_CARD_GATE=off (원장 끄기 ROUTINECODE_ROUTE_LEDGER_DISABLED=1 도 관문을 끈다 —
|
|
27
|
+
차단 횟수를 원장으로 센다). 표준 라이브러리만. 표준 출력에는 훅 응답 JSON 만 쓴다(CLI).
|
|
28
|
+
"""
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
import subprocess
|
|
33
|
+
import sys
|
|
34
|
+
import time
|
|
35
|
+
|
|
36
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
37
|
+
if HERE not in sys.path:
|
|
38
|
+
sys.path.insert(0, HERE)
|
|
39
|
+
|
|
40
|
+
import route_ledger as rl # noqa: E402
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
import ops_guard as og # 작업자 판별(agent_type → meta.json) 재사용
|
|
44
|
+
except Exception: # pragma: no cover
|
|
45
|
+
og = None
|
|
46
|
+
|
|
47
|
+
LITE = 'implementor-lite'
|
|
48
|
+
REVIEWER = 'reviewer'
|
|
49
|
+
EDIT_TOOLS = ('Edit', 'Write', 'MultiEdit', 'NotebookEdit')
|
|
50
|
+
RUN_TOOL_RE = re.compile(r'(^|__)(run_tests|build_check)$')
|
|
51
|
+
HEAD_SCAN = 256 * 1024
|
|
52
|
+
|
|
53
|
+
DEFAULT_GATE = {
|
|
54
|
+
'version': 1,
|
|
55
|
+
'agent_types': [LITE],
|
|
56
|
+
'max_blocks': 2,
|
|
57
|
+
'test_re': r'(^|/)(tests?|__tests__|spec)/|[._-](test|spec)\.[A-Za-z0-9]+$|(^|/)test_[^/]*\.py$',
|
|
58
|
+
'assert_re': (r'(\bassert\w*\b|\bexpect\s*\(|\.should\b|\bcheck\s*\(|\bt\.(ok|equal|is|deepEqual|strictEqual|true|false|throws)\b'
|
|
59
|
+
r'|\.to(Be|Equal|Throw|Match|Contain|Have)\w*\s*\(|\bself\.fail\b|\bpytest\.raises\b)'),
|
|
60
|
+
'attest_kinds': ['tests', 'typecheck', 'build'],
|
|
61
|
+
'path_fix_skip': ['node_modules', '.git', 'dist', 'build', '.venv', 'venv', '__pycache__', '.next', 'coverage'],
|
|
62
|
+
'path_fix_max_entries': 60000,
|
|
63
|
+
'path_fix_max_depth': 12,
|
|
64
|
+
'test_scan_max_files': 3000,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
FORMAT_HELP = (
|
|
68
|
+
'[RoutineCode card] implementor-lite 는 작업 카드 1장만 받는다(설계 34 §5.1). 프롬프트에 아래 블록을 넣어 다시 호출하라. '
|
|
69
|
+
'같은 내용을 .routinecode/cards/<CARD_ID>.md 에도 저장하라.\n'
|
|
70
|
+
'CARD_ID: <6-12자 영소문자·숫자>\n'
|
|
71
|
+
'CARD_KIND: main_code|impl_large|doc|other (risk 는 routinecode:implementor)\n'
|
|
72
|
+
'GOAL: <한 문장>\n'
|
|
73
|
+
'FILES:\n - edit: <저장소 루트 기준 상대경로>\n - read: <상대경로>\n'
|
|
74
|
+
'DONE:\n - <통과해야 할 시험·명령>\n'
|
|
75
|
+
'CHECK:\n - <확인할 것: 경계·최악 조건·인접 결함·보안>\n'
|
|
76
|
+
'KEEP:\n - <바꾸면 안 되는 것: 기존 docstring·시험·공개 API 의 의미>\n'
|
|
77
|
+
'PLAN_REF: <선택>')
|
|
78
|
+
|
|
79
|
+
REPORT_HELP = (
|
|
80
|
+
'완료 보고를 마지막 답에 이 블록 그대로 써라(항목 번호는 카드의 CHECK·KEEP 순서):\n'
|
|
81
|
+
'CARD_REPORT: <CARD_ID>\n'
|
|
82
|
+
'USAGES: `<grep 명령>` -> <건수>\n'
|
|
83
|
+
'ROOT_CAUSE: <file:line | n/a>\n'
|
|
84
|
+
'TESTS_ADDED: <시험 이름>, <시험 이름>\n'
|
|
85
|
+
'CHECK:\n- C1 done|n/a|found-not-fixed: <한 줄>\n'
|
|
86
|
+
'KEEP:\n- K1 kept|found-not-fixed: <한 줄>\n'
|
|
87
|
+
'RESULT: done|partial — <한 줄>')
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def enabled():
|
|
91
|
+
return os.environ.get('ROUTINECODE_CARD_GATE', 'on') != 'off' and not rl.disabled()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def load_gate(rules=None):
|
|
95
|
+
rules = rules if rules is not None else rl.load_rules()
|
|
96
|
+
g = rules.get('gate') if isinstance(rules, dict) else None
|
|
97
|
+
out = dict(DEFAULT_GATE)
|
|
98
|
+
if isinstance(g, dict):
|
|
99
|
+
out.update(g)
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _agent_type(inp):
|
|
104
|
+
if og is not None:
|
|
105
|
+
return og.agent_type_of(inp)
|
|
106
|
+
at = inp.get('agent_type')
|
|
107
|
+
return str(at).split(':')[-1] if at else None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _deny(reason):
|
|
111
|
+
return {'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny',
|
|
112
|
+
'permissionDecisionReason': reason}}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _ts_ms(s):
|
|
116
|
+
"""ISO(Z, 소수초) → epoch ms. 실패 None."""
|
|
117
|
+
t = rl.parse_ts(s)
|
|
118
|
+
if t is None:
|
|
119
|
+
return None
|
|
120
|
+
m = re.match(r'^.{19}\.(\d{1,6})', s)
|
|
121
|
+
frac = int((m.group(1) + '000')[:3]) if m else 0
|
|
122
|
+
return t * 1000 + frac
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ── agent-pre: 카드 필수·위험 배정·대조군 ──
|
|
126
|
+
|
|
127
|
+
def agent_pre(inp, rules=None, p=None, now=None):
|
|
128
|
+
rules = rules if rules is not None else rl.load_rules()
|
|
129
|
+
ti = rl._tool_input(inp)
|
|
130
|
+
st = str(ti.get('subagent_type') or '').split(':')[-1]
|
|
131
|
+
if st != LITE:
|
|
132
|
+
return None
|
|
133
|
+
prompt = ti.get('prompt') if isinstance(ti.get('prompt'), str) else ''
|
|
134
|
+
card = rl.parse_card(prompt) or {}
|
|
135
|
+
ref = card.get('card_ref')
|
|
136
|
+
base = {'ts': rl._now_iso(now), 'session_id': inp.get('session_id') or '', 'card_ref': ref,
|
|
137
|
+
'tool_use_id': inp.get('tool_use_id'), 'kind': card.get('kind'), 'rules_version': rules.get('rules_version', 1)}
|
|
138
|
+
if not ref or not card.get('id_ok'):
|
|
139
|
+
rl.append(dict(base, ev='card_reject', reason='no_card_id' if not ref else 'bad_card_id'), p)
|
|
140
|
+
return _deny(FORMAT_HELP)
|
|
141
|
+
if card.get('kind') == 'risk':
|
|
142
|
+
rl.append(dict(base, ev='card_reject', reason='risk'), p)
|
|
143
|
+
return _deny('[RoutineCode card] CARD_KIND: risk 카드는 Haiku 에 맡기지 않는다(설계 34 §4 F3). '
|
|
144
|
+
'같은 카드를 subagent_type "routinecode:implementor"(Sonnet)로 보내라. CARD_ID 가 taskId 로 쓰이고, '
|
|
145
|
+
'수정 파일 2개 이하면 설계 관문 면제, 3개 이상이면 judge_design 통과가 먼저다.')
|
|
146
|
+
if rl.arm_of(ref, rules) == 'control':
|
|
147
|
+
rl.append(dict(base, ev='control_redirect'), p)
|
|
148
|
+
return _deny('[RoutineCode card] CARD_ID %s 는 대조군이다(설계 34 §6.3, hash(card_id) %% 10 == 0). '
|
|
149
|
+
'같은 카드를 바꾸지 말고 subagent_type "routinecode:implementor"(Sonnet)로 보내라. 카드 블록에 '
|
|
150
|
+
'"ARM: control" 줄을 한 줄 더하라(설계 관문 면제 — taskId 불필요, 설계 34 P3). '
|
|
151
|
+
'관문·리뷰는 같은 카드로 똑같이 거친다.' % ref)
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ── path-fix (F5) ──
|
|
156
|
+
|
|
157
|
+
_CD_RE = re.compile(r'''(?:^|&&|\|\||;)\s*cd\s+("[^"]+"|'[^']+'|[^\s;&|]+)''')
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _repo_root(cwd):
|
|
161
|
+
if not cwd or not os.path.isdir(cwd):
|
|
162
|
+
return None
|
|
163
|
+
try:
|
|
164
|
+
r = subprocess.run(['git', '-C', cwd, 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=3)
|
|
165
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
166
|
+
return os.path.realpath(r.stdout.strip())
|
|
167
|
+
except Exception:
|
|
168
|
+
pass
|
|
169
|
+
return os.path.realpath(cwd)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _under(path, root):
|
|
173
|
+
return path == root or path.startswith(root.rstrip('/') + '/')
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def find_by_basename(root, name, want_dir, gate):
|
|
177
|
+
"""root 아래 basename 이 같은 파일(want_dir=False)·디렉터리 목록. 상한을 넘으면 걷기를 멈춘다(그때까지 찾은 것)."""
|
|
178
|
+
skip = set(gate.get('path_fix_skip') or [])
|
|
179
|
+
max_n = int(gate.get('path_fix_max_entries') or 60000)
|
|
180
|
+
max_d = int(gate.get('path_fix_max_depth') or 12)
|
|
181
|
+
out, n = [], 0
|
|
182
|
+
base_depth = root.rstrip('/').count('/')
|
|
183
|
+
for d, dirs, files in os.walk(root):
|
|
184
|
+
dirs[:] = [x for x in dirs if x not in skip and not os.path.islink(os.path.join(d, x))]
|
|
185
|
+
if d.count('/') - base_depth >= max_d:
|
|
186
|
+
dirs[:] = []
|
|
187
|
+
n += len(dirs) + len(files)
|
|
188
|
+
for x in (dirs if want_dir else files):
|
|
189
|
+
if x == name:
|
|
190
|
+
out.append(os.path.join(d, x))
|
|
191
|
+
if len(out) > 1:
|
|
192
|
+
return out
|
|
193
|
+
if n > max_n:
|
|
194
|
+
break
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _path_targets(inp):
|
|
199
|
+
"""(주어진 경로, want_dir, write_mode) 목록."""
|
|
200
|
+
tool = inp.get('tool_name') or ''
|
|
201
|
+
ti = rl._tool_input(inp)
|
|
202
|
+
if tool in ('Read', 'Edit', 'MultiEdit', 'NotebookEdit'):
|
|
203
|
+
v = ti.get('file_path') or ti.get('notebook_path')
|
|
204
|
+
return [(v, False, False)] if isinstance(v, str) and v else []
|
|
205
|
+
if tool == 'Write':
|
|
206
|
+
v = ti.get('file_path')
|
|
207
|
+
return [(v, False, True)] if isinstance(v, str) and v else []
|
|
208
|
+
if tool == 'Glob':
|
|
209
|
+
v = ti.get('path')
|
|
210
|
+
return [(v, True, False)] if isinstance(v, str) and v else []
|
|
211
|
+
if tool == 'Bash':
|
|
212
|
+
cmd = ti.get('command') if isinstance(ti.get('command'), str) else ''
|
|
213
|
+
out = []
|
|
214
|
+
for m in _CD_RE.finditer(cmd):
|
|
215
|
+
v = m.group(1).strip('\'"')
|
|
216
|
+
if v and v != '-' and '$' not in v and '`' not in v and not v.startswith('~'):
|
|
217
|
+
out.append((v, True, False))
|
|
218
|
+
break # 첫 cd 만(뒤 cd 는 앞 cd 기준이라 판정 불가)
|
|
219
|
+
return out
|
|
220
|
+
return []
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def path_fix(inp, rules=None, p=None, now=None):
|
|
224
|
+
"""None = 관여 안 함. dict = deny 응답."""
|
|
225
|
+
if _agent_type(inp) != LITE:
|
|
226
|
+
return None
|
|
227
|
+
gate = load_gate(rules)
|
|
228
|
+
cwd = inp.get('cwd') if isinstance(inp.get('cwd'), str) else ''
|
|
229
|
+
for given, want_dir, write_mode in _path_targets(inp):
|
|
230
|
+
full = os.path.normpath(given if os.path.isabs(given) else os.path.join(cwd or '/', given))
|
|
231
|
+
if (os.path.isdir(full) if want_dir else os.path.exists(full)):
|
|
232
|
+
continue
|
|
233
|
+
if write_mode and os.path.isdir(os.path.dirname(full)):
|
|
234
|
+
continue # 있는 디렉터리에 새 파일 = 정상 생성
|
|
235
|
+
root = _repo_root(cwd)
|
|
236
|
+
if not root:
|
|
237
|
+
continue
|
|
238
|
+
real_full = os.path.join(os.path.realpath(os.path.dirname(full)) if os.path.exists(os.path.dirname(full))
|
|
239
|
+
else os.path.dirname(full), os.path.basename(full))
|
|
240
|
+
if os.path.isabs(given) and not (_under(full, root) or _under(real_full, root)):
|
|
241
|
+
continue # 저장소 밖 절대경로(/tmp 등)는 건드리지 않는다
|
|
242
|
+
name = os.path.basename(full)
|
|
243
|
+
hits = find_by_basename(root, name, want_dir, gate) if name else []
|
|
244
|
+
if len(hits) != 1 and write_mode:
|
|
245
|
+
parent = os.path.basename(os.path.dirname(full))
|
|
246
|
+
dhits = find_by_basename(root, parent, True, gate) if parent else []
|
|
247
|
+
hits = [os.path.join(dhits[0], name)] if len(dhits) == 1 else hits
|
|
248
|
+
if len(hits) != 1:
|
|
249
|
+
continue
|
|
250
|
+
fixed = hits[0]
|
|
251
|
+
rel = os.path.relpath(fixed, root)
|
|
252
|
+
row = {'ev': 'path_fix', 'ts': rl._now_iso(now), 'session_id': inp.get('session_id') or '',
|
|
253
|
+
'agent_id': str(inp.get('agent_id') or ''), 'tool': inp.get('tool_name'), 'given': given[:200],
|
|
254
|
+
'fixed': rel, 'card_ref': _first_card_ref(inp)}
|
|
255
|
+
rl.append(row, p)
|
|
256
|
+
return _deny('경로 정정: %s (%s). 없는 경로 %s 대신 이 경로로 다시 실행하라. '
|
|
257
|
+
'경로는 저장소 루트(%s) 기준 상대경로로 쓴다.' % (rel, fixed, given, root))
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _first_card_ref(inp):
|
|
262
|
+
try:
|
|
263
|
+
ids = og.card_ids(inp) if og is not None else []
|
|
264
|
+
except Exception:
|
|
265
|
+
ids = []
|
|
266
|
+
for i in ids:
|
|
267
|
+
if rl.CARD_ID_RE.match(i or ''):
|
|
268
|
+
return i
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
# ── 작업자 transcript ──
|
|
273
|
+
|
|
274
|
+
def _text_of(content):
|
|
275
|
+
if isinstance(content, str):
|
|
276
|
+
return content
|
|
277
|
+
return '\n'.join(x.get('text', '') for x in (content or []) if isinstance(x, dict) and x.get('type') == 'text')
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def first_user_text(entries):
|
|
281
|
+
for e in entries:
|
|
282
|
+
if e.get('type') == 'user':
|
|
283
|
+
t = _text_of((e.get('message') or {}).get('content'))
|
|
284
|
+
if t:
|
|
285
|
+
return t
|
|
286
|
+
return ''
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def last_assistant_text(entries):
|
|
290
|
+
"""마지막 텍스트가 있는 응답(message.id 같은 줄 묶음)의 텍스트."""
|
|
291
|
+
last_id, parts = None, []
|
|
292
|
+
for e in entries:
|
|
293
|
+
if e.get('type') != 'assistant':
|
|
294
|
+
continue
|
|
295
|
+
msg = e.get('message') if isinstance(e.get('message'), dict) else {}
|
|
296
|
+
t = _text_of(msg.get('content'))
|
|
297
|
+
if not t:
|
|
298
|
+
continue
|
|
299
|
+
mid = msg.get('id') or e.get('uuid')
|
|
300
|
+
if mid != last_id:
|
|
301
|
+
last_id, parts = mid, []
|
|
302
|
+
parts.append(t)
|
|
303
|
+
return '\n'.join(parts)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def tool_uses(entries):
|
|
307
|
+
"""[(ts_ms, name, input)] 순서대로."""
|
|
308
|
+
out = []
|
|
309
|
+
for e in entries:
|
|
310
|
+
if e.get('type') != 'assistant':
|
|
311
|
+
continue
|
|
312
|
+
ts = _ts_ms(e.get('timestamp'))
|
|
313
|
+
for b in (e.get('message') or {}).get('content') or []:
|
|
314
|
+
if isinstance(b, dict) and b.get('type') == 'tool_use':
|
|
315
|
+
out.append((ts, b.get('name') or '', b.get('input') if isinstance(b.get('input'), dict) else {}))
|
|
316
|
+
return out
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def cwd_of(entries, inp):
|
|
320
|
+
for e in entries:
|
|
321
|
+
if isinstance(e.get('cwd'), str) and e['cwd']:
|
|
322
|
+
return e['cwd']
|
|
323
|
+
return inp.get('cwd') if isinstance(inp.get('cwd'), str) else ''
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ── 보고 블록 ──
|
|
327
|
+
|
|
328
|
+
_RKEY = re.compile(r'^\s*(CARD_REPORT|USAGES|ROOT_CAUSE|TESTS_ADDED|CHECK|KEEP|RESULT):[ \t]*(.*?)\s*$')
|
|
329
|
+
_RCHECK = re.compile(r'^\s*[-*]\s*C(\d+)\s*[:.]?\s*(done|n/a|found-not-fixed)\b\s*[:—-]?\s*(.*)$', re.I)
|
|
330
|
+
_RKEEP = re.compile(r'^\s*[-*]\s*K(\d+)\s*[:.]?\s*(kept|found-not-fixed)\b\s*[:—-]?\s*(.*)$', re.I)
|
|
331
|
+
REPORT_KEYS = ('USAGES', 'ROOT_CAUSE', 'TESTS_ADDED', 'CHECK', 'KEEP', 'RESULT')
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def parse_report(text):
|
|
335
|
+
"""보고 블록 → dict(keys, card_ref, usages, root_cause, tests_added, check{n: status}, keep{n: status}, result)."""
|
|
336
|
+
out = {'keys': set(), 'card_ref': None, 'usages': None, 'root_cause': None, 'tests_added': [],
|
|
337
|
+
'check': {}, 'keep': {}, 'result': None}
|
|
338
|
+
if not isinstance(text, str):
|
|
339
|
+
return out
|
|
340
|
+
cur = None
|
|
341
|
+
for ln in text.splitlines():
|
|
342
|
+
m = _RKEY.match(ln.replace('**', ''))
|
|
343
|
+
if m:
|
|
344
|
+
k, v = m.group(1), m.group(2).strip('` ')
|
|
345
|
+
out['keys'].add(k)
|
|
346
|
+
cur = k
|
|
347
|
+
if k == 'CARD_REPORT':
|
|
348
|
+
out['card_ref'] = v or None
|
|
349
|
+
elif k == 'USAGES':
|
|
350
|
+
out['usages'] = v or None
|
|
351
|
+
elif k == 'ROOT_CAUSE':
|
|
352
|
+
out['root_cause'] = v or None
|
|
353
|
+
elif k == 'RESULT':
|
|
354
|
+
out['result'] = v or None
|
|
355
|
+
elif k == 'TESTS_ADDED':
|
|
356
|
+
out['tests_added'] += _names(v)
|
|
357
|
+
continue
|
|
358
|
+
if cur == 'CHECK':
|
|
359
|
+
mc = _RCHECK.match(ln)
|
|
360
|
+
if mc:
|
|
361
|
+
out['check']['C' + mc.group(1)] = mc.group(2).lower()
|
|
362
|
+
elif cur == 'KEEP':
|
|
363
|
+
mk = _RKEEP.match(ln)
|
|
364
|
+
if mk:
|
|
365
|
+
out['keep']['K' + mk.group(1)] = mk.group(2).lower()
|
|
366
|
+
elif cur == 'TESTS_ADDED':
|
|
367
|
+
mi = re.match(r'^\s*[-*]\s+(.+)$', ln)
|
|
368
|
+
if mi:
|
|
369
|
+
out['tests_added'] += _names(mi.group(1))
|
|
370
|
+
elif ln.strip():
|
|
371
|
+
cur = None
|
|
372
|
+
seen, uniq = set(), []
|
|
373
|
+
for n in out['tests_added']:
|
|
374
|
+
if n not in seen:
|
|
375
|
+
seen.add(n)
|
|
376
|
+
uniq.append(n)
|
|
377
|
+
out['tests_added'] = uniq
|
|
378
|
+
return out
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _names(v):
|
|
382
|
+
if not v or v.strip().lower() in ('none', 'n/a', '-', '없음'):
|
|
383
|
+
return []
|
|
384
|
+
return [x.strip().strip('`\'"') for x in re.split(r'[,;]', v) if x.strip().strip('`\'"')]
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def report_missing(rep, card):
|
|
388
|
+
"""빠진 것 목록(빈 목록 = 보고 완전)."""
|
|
389
|
+
miss = [k for k in REPORT_KEYS if k not in rep['keys']]
|
|
390
|
+
nc, nk = len(card.get('check') or []), len(card.get('keep') or [])
|
|
391
|
+
for i in range(1, nc + 1):
|
|
392
|
+
if 'C%d' % i not in rep['check']:
|
|
393
|
+
miss.append('CHECK C%d' % i)
|
|
394
|
+
for i in range(1, nk + 1):
|
|
395
|
+
if 'K%d' % i not in rep['keep']:
|
|
396
|
+
miss.append('KEEP K%d' % i)
|
|
397
|
+
return miss
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# ── 관문 ──
|
|
401
|
+
|
|
402
|
+
def _git(args, cwd, timeout=10):
|
|
403
|
+
try:
|
|
404
|
+
r = subprocess.run(['git', '-C', cwd] + args, capture_output=True, text=True, timeout=timeout)
|
|
405
|
+
return r.returncode, r.stdout
|
|
406
|
+
except Exception:
|
|
407
|
+
return 1, ''
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _read(path, limit=2 * 1024 * 1024):
|
|
411
|
+
try:
|
|
412
|
+
with open(path, encoding='utf-8', errors='replace') as f:
|
|
413
|
+
return f.read(limit)
|
|
414
|
+
except Exception:
|
|
415
|
+
return None
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _abs(f, cwd):
|
|
419
|
+
return os.path.normpath(f if os.path.isabs(f) else os.path.join(cwd or '/', f))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _related(a, b):
|
|
423
|
+
a, b = os.path.realpath(a), os.path.realpath(b)
|
|
424
|
+
return a == b or a.startswith(b.rstrip('/') + '/') or b.startswith(a.rstrip('/') + '/')
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def g1_check(uses, root, gate, now_ms=None, reader=None):
|
|
428
|
+
"""(통과, 사유). 편집이 없으면 첫 도구 호출 시각을 기준으로 본다."""
|
|
429
|
+
edits = [t for (t, n, _i) in uses if n in EDIT_TOOLS and t is not None]
|
|
430
|
+
start = [t for (t, _n, _i) in uses if t is not None]
|
|
431
|
+
ref = max(edits) if edits else (min(start) if start else 0)
|
|
432
|
+
runs = [t for (t, n, _i) in uses if RUN_TOOL_RE.search(n) and t is not None and t >= ref]
|
|
433
|
+
if not runs:
|
|
434
|
+
return False, '마지막 편집 뒤 run_tests/build_check 호출 없음'
|
|
435
|
+
if reader is None:
|
|
436
|
+
try:
|
|
437
|
+
import attest_reader as ar
|
|
438
|
+
reader = ar.read_attestations
|
|
439
|
+
except Exception:
|
|
440
|
+
return False, '증거 판독기(attest_reader)를 불러오지 못함'
|
|
441
|
+
try:
|
|
442
|
+
atts = reader(since_ms=ref, kinds=list(gate.get('attest_kinds') or ['tests', 'typecheck', 'build']))
|
|
443
|
+
except Exception:
|
|
444
|
+
atts = []
|
|
445
|
+
end = (now_ms or int(time.time() * 1000)) + 5000
|
|
446
|
+
ok = [a for a in atts if a.get('success') is True and (a.get('ts') or 0) <= end
|
|
447
|
+
and (not root or not a.get('projectDir') or _related(str(a.get('projectDir')), root))]
|
|
448
|
+
if not ok:
|
|
449
|
+
return False, '마지막 편집 뒤 통과한 run_tests/build_check 증거 없음'
|
|
450
|
+
return True, ''
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def g2_check(uses, root, cwd, gate):
|
|
454
|
+
"""(통과, 위반 [(rel, line)]). HEAD 에 있던 시험 파일의 assert 줄 삭제·변경."""
|
|
455
|
+
if not root:
|
|
456
|
+
return True, []
|
|
457
|
+
test_re = re.compile(gate['test_re'])
|
|
458
|
+
assert_re = re.compile(gate['assert_re'])
|
|
459
|
+
per = {} # abs → {'olds': set(lines), 'write': bool}
|
|
460
|
+
for (_t, n, i) in uses:
|
|
461
|
+
if n not in ('Edit', 'Write', 'MultiEdit'):
|
|
462
|
+
continue
|
|
463
|
+
fp = i.get('file_path')
|
|
464
|
+
if not isinstance(fp, str) or not fp:
|
|
465
|
+
continue
|
|
466
|
+
a = _abs(fp, cwd)
|
|
467
|
+
rec = per.setdefault(a, {'olds': set(), 'write': False})
|
|
468
|
+
if n == 'Write':
|
|
469
|
+
rec['write'] = True
|
|
470
|
+
elif n == 'Edit':
|
|
471
|
+
rec['olds'].update(x.strip() for x in str(i.get('old_string') or '').splitlines())
|
|
472
|
+
else:
|
|
473
|
+
for e in i.get('edits') or []:
|
|
474
|
+
if isinstance(e, dict):
|
|
475
|
+
rec['olds'].update(x.strip() for x in str(e.get('old_string') or '').splitlines())
|
|
476
|
+
bad = []
|
|
477
|
+
for a, rec in sorted(per.items()):
|
|
478
|
+
if not _under(os.path.realpath(a), root) and not _under(a, root):
|
|
479
|
+
continue
|
|
480
|
+
rel = os.path.relpath(os.path.realpath(a) if _under(os.path.realpath(a), root) else a, root)
|
|
481
|
+
if not test_re.search(rel):
|
|
482
|
+
continue
|
|
483
|
+
rc, head = _git(['show', 'HEAD:' + rel], root)
|
|
484
|
+
if rc != 0:
|
|
485
|
+
continue # 새 시험 파일 = 대상 아님
|
|
486
|
+
cur = _read(a) or ''
|
|
487
|
+
cur_lines = {}
|
|
488
|
+
for x in cur.splitlines():
|
|
489
|
+
s = x.strip()
|
|
490
|
+
cur_lines[s] = cur_lines.get(s, 0) + 1
|
|
491
|
+
for x in head.splitlines():
|
|
492
|
+
s = x.strip()
|
|
493
|
+
if not s or not assert_re.search(s):
|
|
494
|
+
continue
|
|
495
|
+
if cur_lines.get(s, 0) > 0:
|
|
496
|
+
cur_lines[s] -= 1
|
|
497
|
+
continue
|
|
498
|
+
if rec['write'] or s in rec['olds']:
|
|
499
|
+
bad.append((rel, s[:160]))
|
|
500
|
+
return (not bad), bad
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _touched_tests(uses, root, cwd, gate):
|
|
504
|
+
test_re = re.compile(gate['test_re'])
|
|
505
|
+
out = []
|
|
506
|
+
for (_t, n, i) in uses:
|
|
507
|
+
if n in EDIT_TOOLS:
|
|
508
|
+
fp = i.get('file_path') or i.get('notebook_path')
|
|
509
|
+
if isinstance(fp, str) and fp:
|
|
510
|
+
a = _abs(fp, cwd)
|
|
511
|
+
rel = os.path.relpath(a, root) if root and _under(a, root) else a
|
|
512
|
+
if test_re.search(rel) and a not in out:
|
|
513
|
+
out.append(a)
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _repo_test_files(root, gate):
|
|
518
|
+
if not root:
|
|
519
|
+
return []
|
|
520
|
+
test_re = re.compile(gate['test_re'])
|
|
521
|
+
rc, out = _git(['ls-files', '--cached', '--others', '--exclude-standard'], root, timeout=15)
|
|
522
|
+
if rc != 0:
|
|
523
|
+
return []
|
|
524
|
+
fs = [os.path.join(root, x) for x in out.splitlines() if x and test_re.search(x)]
|
|
525
|
+
return fs[:int(gate.get('test_scan_max_files') or 3000)]
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _count(name, text):
|
|
529
|
+
"""이름이 단어 경계로 나온 횟수(test_total 이 test_total_empty 안에서 세지지 않게)."""
|
|
530
|
+
if not name or not text:
|
|
531
|
+
return 0
|
|
532
|
+
return len(re.findall(r'(?<!\w)' + re.escape(name) + r'(?!\w)', text))
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def g34_check(names, uses, root, cwd, gate):
|
|
536
|
+
"""(g3, g4, 없는 이름 목록)."""
|
|
537
|
+
touched = _touched_tests(uses, root, cwd, gate)
|
|
538
|
+
tc = {a: (_read(a) or '') for a in touched}
|
|
539
|
+
heads = {}
|
|
540
|
+
for a in touched:
|
|
541
|
+
h = ''
|
|
542
|
+
if root and _under(a, root):
|
|
543
|
+
rc, out = _git(['show', 'HEAD:' + os.path.relpath(a, root)], root)
|
|
544
|
+
h = out if rc == 0 else ''
|
|
545
|
+
heads[a] = h
|
|
546
|
+
present = [n for n in names if any(_count(n, c) for c in tc.values())]
|
|
547
|
+
# 새 시험 = 편집한 시험 파일에서 HEAD 보다 더 자주 나오는 이름(이미 있던 시험을 새 것으로 보고하면 G4 실패)
|
|
548
|
+
in_touched = [n for n in present if any(_count(n, c) > _count(n, heads[a]) for a, c in tc.items())]
|
|
549
|
+
missing = [n for n in names if n not in present]
|
|
550
|
+
if missing:
|
|
551
|
+
rest = []
|
|
552
|
+
for f in _repo_test_files(root, gate):
|
|
553
|
+
if f in tc:
|
|
554
|
+
continue
|
|
555
|
+
c = _read(f)
|
|
556
|
+
if c is not None:
|
|
557
|
+
rest.append(c)
|
|
558
|
+
missing = [n for n in missing if not any(_count(n, c) for c in rest)]
|
|
559
|
+
return (not missing), bool(in_touched), missing
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _card_from_file(root, ref):
|
|
563
|
+
if not root or not ref or not rl.CARD_ID_RE.match(ref):
|
|
564
|
+
return None
|
|
565
|
+
return rl.parse_card(_read(os.path.join(root, '.routinecode', 'cards', ref + '.md')) or '')
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _blocks_so_far(tool_use_id, p=None):
|
|
569
|
+
n = 0
|
|
570
|
+
for r in rl.read_rows(p, tail=rl.TAIL_BYTES):
|
|
571
|
+
if r.get('ev') == 'gate' and r.get('card_id') == tool_use_id and r.get('blocked'):
|
|
572
|
+
n += 1
|
|
573
|
+
return n
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def evaluate(entries, inp, rules=None, now_ms=None, reader=None):
|
|
577
|
+
"""관문 결과 dict (기록·응답 전). 시험에서 직접 부른다."""
|
|
578
|
+
gate = load_gate(rules)
|
|
579
|
+
cwd = cwd_of(entries, inp)
|
|
580
|
+
root = _repo_root(cwd) if cwd else None
|
|
581
|
+
prompt = first_user_text(entries)
|
|
582
|
+
card = rl.parse_card(prompt) or {}
|
|
583
|
+
if card.get('card_ref') and not card.get('check') and not card.get('keep'):
|
|
584
|
+
fc = _card_from_file(root, card['card_ref'])
|
|
585
|
+
if fc:
|
|
586
|
+
card = dict(card, check=fc.get('check') or [], keep=fc.get('keep') or [])
|
|
587
|
+
last = inp.get('last_assistant_message') if isinstance(inp.get('last_assistant_message'), str) else ''
|
|
588
|
+
rep = parse_report(last or last_assistant_text(entries))
|
|
589
|
+
if not rep['keys']:
|
|
590
|
+
rep = parse_report(last_assistant_text(entries))
|
|
591
|
+
uses = tool_uses(entries)
|
|
592
|
+
miss = report_missing(rep, card)
|
|
593
|
+
g1, g1_why = g1_check(uses, root, gate, now_ms, reader)
|
|
594
|
+
g2, g2_bad = g2_check(uses, root, cwd, gate)
|
|
595
|
+
g3, g4, g3_missing = g34_check(rep['tests_added'], uses, root, cwd, gate)
|
|
596
|
+
return {'card': card, 'report': rep, 'report_missing': miss, 'g1': g1, 'g1_why': g1_why,
|
|
597
|
+
'g2': g2, 'g2_bad': g2_bad, 'g3': g3, 'g3_missing': g3_missing, 'g4': g4, 'root': root, 'gate': gate}
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def block_reason(ev):
|
|
601
|
+
parts = ['[RoutineCode card gate] 카드 %s 완료 관문 미통과 — 고친 뒤 끝내라.' % (ev['card'].get('card_ref') or '?')]
|
|
602
|
+
if not ev['g1']:
|
|
603
|
+
parts.append('G1: %s. 마지막 편집 뒤 run_tests 또는 build_check 를 실행해 통과시켜라.' % ev['g1_why'])
|
|
604
|
+
if not ev['g2']:
|
|
605
|
+
parts.append('G2: 기존 시험의 assert 줄을 지우거나 바꿨다(추가만 허용): %s. 원래대로 되돌리고, 바꿀 필요가 있으면 '
|
|
606
|
+
'KEEP 에 found-not-fixed 로 보고하라.' % '; '.join('%s: %s' % x for x in ev['g2_bad'][:5]))
|
|
607
|
+
if not ev['g3']:
|
|
608
|
+
parts.append('G3: TESTS_ADDED 의 시험이 저장소 시험 파일에 없다: %s. 실제 시험 이름을 쓰거나 시험을 추가하라.'
|
|
609
|
+
% ', '.join(ev['g3_missing'][:8]))
|
|
610
|
+
if not ev['g4']:
|
|
611
|
+
parts.append('G4: 새 시험이 0개다. 이 카드의 변경을 확인하는 시험을 시험 파일에 추가하고 TESTS_ADDED 에 그 이름을 적어라.')
|
|
612
|
+
if ev['report_missing']:
|
|
613
|
+
parts.append('보고 블록 누락: %s.\n%s' % (', '.join(ev['report_missing']), REPORT_HELP))
|
|
614
|
+
return '\n'.join(parts)
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def subagent_stop(inp, rules=None, p=None, now=None, reader=None):
|
|
618
|
+
"""None = 관여 안 함(출력 없음). dict = SubagentStop 응답."""
|
|
619
|
+
at = _agent_type(inp)
|
|
620
|
+
if at == REVIEWER:
|
|
621
|
+
record_review(inp, p, now)
|
|
622
|
+
return None
|
|
623
|
+
if at != LITE:
|
|
624
|
+
return None
|
|
625
|
+
rules = rules if rules is not None else rl.load_rules()
|
|
626
|
+
path = rl.resolve_agent_path(inp)
|
|
627
|
+
if not path or not os.path.exists(path):
|
|
628
|
+
return None
|
|
629
|
+
entries = rl.load_jsonl(path)
|
|
630
|
+
meta = rl.agent_meta(path)
|
|
631
|
+
tool_use_id = meta.get('toolUseId') or rl._norm_agent_id(inp.get('agent_id'))
|
|
632
|
+
ev = evaluate(entries, inp, rules, None if now is None else int(now * 1000), reader)
|
|
633
|
+
failing = not (ev['g1'] and ev['g2'] and ev['g3'] and ev['g4']) or bool(ev['report_missing'])
|
|
634
|
+
prev = _blocks_so_far(tool_use_id, p)
|
|
635
|
+
max_b = int(ev['gate'].get('max_blocks') or 2)
|
|
636
|
+
blocked = failing and prev < max_b
|
|
637
|
+
rep = ev['report']
|
|
638
|
+
row = {'ev': 'gate', 'ts': rl._now_iso(now), 'session_id': inp.get('session_id') or '',
|
|
639
|
+
'card_id': tool_use_id, 'card_ref': ev['card'].get('card_ref'), 'agent_id': rl._norm_agent_id(inp.get('agent_id')),
|
|
640
|
+
'g1': ev['g1'], 'g2': ev['g2'], 'g3': ev['g3'], 'g4': ev['g4'],
|
|
641
|
+
'report_ok': not ev['report_missing'], 'blocked': blocked, 'blocks': prev + (1 if blocked else 0),
|
|
642
|
+
'gate_fail': failing and not blocked, 'tests_added': rep['tests_added'][:20],
|
|
643
|
+
'checklist': rep['check'], 'keep': rep['keep'], 'result': (rep['result'] or '')[:200],
|
|
644
|
+
'root_cause': (rep['root_cause'] or '')[:200], 'gate_version': ev['gate'].get('version', 1)}
|
|
645
|
+
rl.append(row, p)
|
|
646
|
+
if blocked:
|
|
647
|
+
return {'decision': 'block', 'reason': block_reason(ev)}
|
|
648
|
+
return None
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
# ── reviewer 카드 판정 ──
|
|
652
|
+
|
|
653
|
+
_RV_HEAD = re.compile(r'^\s*(?:#+\s*)?REVIEW CARD\s+([a-z0-9]{6,12})\s*:\s*DEFECTS\s+(\d+)\s*$')
|
|
654
|
+
_RV_LINE = re.compile(r'^\s*[-*]\s*(F[1-4]|other)\s*:\s*(.+?)\s*$', re.I)
|
|
655
|
+
_RV_LOC = re.compile(r'\(([^()]*?[^()\s]:\d+[^()]*)\)\s*$')
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def parse_review(text):
|
|
659
|
+
"""[{card_ref, defects, types{F1..}, lines[{type, text, loc}]}]."""
|
|
660
|
+
out, cur = [], None
|
|
661
|
+
if not isinstance(text, str):
|
|
662
|
+
return out
|
|
663
|
+
for ln in text.splitlines():
|
|
664
|
+
m = _RV_HEAD.match(ln.replace('**', ''))
|
|
665
|
+
if m:
|
|
666
|
+
cur = {'card_ref': m.group(1), 'defects': int(m.group(2)), 'types': {}, 'lines': []}
|
|
667
|
+
out.append(cur)
|
|
668
|
+
continue
|
|
669
|
+
if cur is None:
|
|
670
|
+
continue
|
|
671
|
+
mi = _RV_LINE.match(ln)
|
|
672
|
+
if mi:
|
|
673
|
+
typ = mi.group(1).upper() if mi.group(1).lower() != 'other' else 'other'
|
|
674
|
+
body = mi.group(2)
|
|
675
|
+
ml = _RV_LOC.search(body)
|
|
676
|
+
loc = ml.group(1).strip() if ml else None
|
|
677
|
+
txt = body[:ml.start()].strip() if ml else body
|
|
678
|
+
cur['lines'].append({'type': typ, 'text': txt[:300], 'loc': loc})
|
|
679
|
+
cur['types'][typ] = cur['types'].get(typ, 0) + 1
|
|
680
|
+
elif ln.strip() and not ln.startswith((' ', '\t')):
|
|
681
|
+
cur = None
|
|
682
|
+
return out
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def record_review(inp, p=None, now=None):
|
|
686
|
+
path = rl.resolve_agent_path(inp)
|
|
687
|
+
entries = rl.load_jsonl(path) if path and os.path.exists(path) else []
|
|
688
|
+
text = inp.get('last_assistant_message') if isinstance(inp.get('last_assistant_message'), str) else ''
|
|
689
|
+
blocks = parse_review(text) or parse_review(last_assistant_text(entries))
|
|
690
|
+
if not blocks:
|
|
691
|
+
return []
|
|
692
|
+
meta = rl.agent_meta(path) if path else {}
|
|
693
|
+
rid = meta.get('toolUseId') or rl._norm_agent_id(inp.get('agent_id'))
|
|
694
|
+
have = {(r.get('review_id'), r.get('card_ref'), r.get('defects'), json.dumps(r.get('lines'), sort_keys=True))
|
|
695
|
+
for r in rl.read_rows(p, tail=rl.TAIL_BYTES) if r.get('ev') == 'review'}
|
|
696
|
+
out = []
|
|
697
|
+
for b in blocks:
|
|
698
|
+
key = (rid, b['card_ref'], b['defects'], json.dumps(b['lines'], sort_keys=True))
|
|
699
|
+
if key in have:
|
|
700
|
+
continue
|
|
701
|
+
row = {'ev': 'review', 'ts': rl._now_iso(now), 'session_id': inp.get('session_id') or '',
|
|
702
|
+
'review_id': rid, 'card_ref': b['card_ref'], 'defects': b['defects'], 'types': b['types'],
|
|
703
|
+
'lines': b['lines'][:30]}
|
|
704
|
+
if rl.append(row, p):
|
|
705
|
+
out.append(row)
|
|
706
|
+
return out
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
# ── CLI ──
|
|
710
|
+
|
|
711
|
+
def _main(argv):
|
|
712
|
+
if len(argv) < 2 or not enabled():
|
|
713
|
+
return 0
|
|
714
|
+
cmd = argv[1]
|
|
715
|
+
try:
|
|
716
|
+
inp = json.load(sys.stdin)
|
|
717
|
+
if not isinstance(inp, dict):
|
|
718
|
+
return 0
|
|
719
|
+
if cmd == 'agent-pre':
|
|
720
|
+
out = agent_pre(inp)
|
|
721
|
+
elif cmd == 'path-fix':
|
|
722
|
+
out = path_fix(inp)
|
|
723
|
+
elif cmd == 'subagent-stop':
|
|
724
|
+
out = subagent_stop(inp)
|
|
725
|
+
else:
|
|
726
|
+
out = None
|
|
727
|
+
except Exception:
|
|
728
|
+
out = None # fail-open
|
|
729
|
+
if out:
|
|
730
|
+
sys.stdout.write(json.dumps(out, ensure_ascii=False))
|
|
731
|
+
return 0
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
if __name__ == '__main__':
|
|
735
|
+
sys.exit(_main(sys.argv))
|