@routinecrew/routinecode 2.31.87 → 2.31.90
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-suggestions.js +100 -0
- package/bin/rc-team.js +1 -1
- package/bin/setup.js +1 -1
- package/hooks/hooks-config.json +9 -0
- package/hooks/lib/agent_budget.py +2 -0
- 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/codemode_guard.py +30 -0
- 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/emit_raw.py +4 -0
- package/hooks/lib/knowledge_items.py +281 -22
- package/hooks/lib/knowledge_stock.py +708 -0
- package/hooks/lib/known_solution.py +1 -1
- 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 +22 -2
- package/hooks/pre-bash-guard.sh +31 -0
- package/hooks/pre-bash-knowledge.sh +12 -2
- package/hooks/pre-edit-delegate.sh +15 -0
- package/hooks/pre-edit-guard.sh +10 -0
- package/hooks/pre-read-guard.sh +10 -0
- package/hooks/session-start.sh +6 -0
- package/hooks/stop-usage-metrics.sh +6 -0
- package/hooks/subagent-stop-usage.sh +36 -4
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-routinecode/dist/index.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,622 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""작업 카드 원장 route-ledger.jsonl — 설계 34 §6.2 (P0 측정 기반, 동작 변경 없음).
|
|
3
|
+
|
|
4
|
+
카드 1개(= 위임 1회) = card_open 1행 + card_close 행(재개되면 누적값으로 다시) + 7일 뒤 refix 보강 행.
|
|
5
|
+
메인 세션의 직접 편집은 main_edit 행으로 남겨 7일 재수정(M8)의 비교 기준과 원천으로 쓴다.
|
|
6
|
+
행은 추가만 한다. 모든 행에 "ev" 가 있다.
|
|
7
|
+
|
|
8
|
+
card_open PreToolUse(Agent) card_id(=tool_use_id) session_id ts agent_type requested_model kind_pre arm rules_version
|
|
9
|
+
[card_ref n_check n_keep plan_ref escalated_from — implementor(-lite) 카드, parse_card]
|
|
10
|
+
[ops_mode card_ref — ops-lite·runner-lite, 프롬프트 OPS_MODE:·CARD_ID: 줄]
|
|
11
|
+
card_close SubagentStop card_id actual_model files_touched kind_post tool_calls usage usage_by_model msg_n
|
|
12
|
+
main_edit PostToolUse(Edit…) session_id ts file kind edit_id (서브에이전트 편집은 건너뛴다)
|
|
13
|
+
main_nudge PreToolUse(Edit…·Bash) 메인 직접 실행 경고(P4 1단계) — hooks/lib/delegate_nudge.py (tool target kind cmd_head phase=warn)
|
|
14
|
+
refix backfill ref src_ev kind arm refix_7d refix_same_session refix_later src_ts
|
|
15
|
+
blocked_cmd PreToolUse(Bash) ops-lite 허용목록 차단 — hooks/lib/ops_guard.py (agent_id card_id cmd_head rule)
|
|
16
|
+
P2(hooks/lib/card_gate.py, card_ref = 프롬프트 CARD_ID):
|
|
17
|
+
card_reject·control_redirect PreToolUse(Agent) implementor-lite 거절(카드 없음·risk)·대조군 재배정(§6.3)
|
|
18
|
+
path_fix PreToolUse implementor-lite 경로 정정(F5) — tool given fixed card_ref
|
|
19
|
+
gate SubagentStop implementor-lite 관문 card_id g1..g4 report_ok blocked blocks gate_fail checklist keep
|
|
20
|
+
review SubagentStop reviewer 카드 판정 card_ref review_id defects types lines
|
|
21
|
+
arm(P2): implementor-lite = haiku, "ARM: control" = control, "ESCALATED_FROM:" = escalated, risk 카드 implementor = risk
|
|
22
|
+
(rules_version 2: implementor 는 Sonnet. 1 의 opus_escalated/opus_risk 는 metrics 가 같은 arm 으로 읽는다)
|
|
23
|
+
|
|
24
|
+
- 분류(classify)는 route_rules.json 한 곳의 정규식을 쓴다. 측정 스크립트(scripts/route-metrics.py)도 같은 파일을 읽는다.
|
|
25
|
+
- arm 은 P0 에서 기록만 한다(control = hash(card_id) % 10 == 0). 배정·라우팅은 바꾸지 않는다.
|
|
26
|
+
- 표준 라이브러리만, 예외를 올리지 않는다, 표준 출력에 아무것도 쓰지 않는다(훅은 백그라운드로 부른다).
|
|
27
|
+
- 끄기: ROUTINECODE_ROUTE_LEDGER_DISABLED=1
|
|
28
|
+
|
|
29
|
+
CLI: python3 route_ledger.py agent-pre | subagent-stop | main-edit (stdin = 훅 입력 JSON)
|
|
30
|
+
python3 route_ledger.py backfill
|
|
31
|
+
"""
|
|
32
|
+
import hashlib
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import re
|
|
36
|
+
import sys
|
|
37
|
+
import time
|
|
38
|
+
|
|
39
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
40
|
+
RULES_PATH = os.path.join(HERE, 'route_rules.json')
|
|
41
|
+
LEDGER_NAME = 'route-ledger.jsonl'
|
|
42
|
+
TAIL_BYTES = 512 * 1024
|
|
43
|
+
REFIX_WINDOW_S = 7 * 86400
|
|
44
|
+
SAME_SESSION_WINDOW_S = 2 * 3600 # route_rules.json refix.same_session_window_s 로 바꿀 수 있다
|
|
45
|
+
BACKFILL_STAMP = 'route-ledger.backfill-at'
|
|
46
|
+
BACKFILL_MIN_INTERVAL_S = 86400
|
|
47
|
+
EDIT_TOOLS = ('Edit', 'Write', 'MultiEdit', 'NotebookEdit')
|
|
48
|
+
EXCLUDE_PARTS = ('/scratchpad/', '/.claude/')
|
|
49
|
+
|
|
50
|
+
DEFAULT_RULES = {
|
|
51
|
+
'rules_version': 1,
|
|
52
|
+
'doc_re': r'\.(md|txt|json|ya?ml|csv)$',
|
|
53
|
+
'risk_re': r'(auth|payment|billing|secret|security|credential|token|oauth|migrat|crypto|grant|seal|permission|rls|webhook)',
|
|
54
|
+
'control_ratio': 0.1,
|
|
55
|
+
'kinds': ['main_code', 'impl_large', 'risk', 'ops_read', 'ops_proc', 'run', 'doc', 'other'],
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def disabled():
|
|
60
|
+
return os.environ.get('ROUTINECODE_ROUTE_LEDGER_DISABLED') == '1'
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def knowledge_dir():
|
|
64
|
+
return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.expanduser('~/.routinecode/knowledge')
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ledger_path():
|
|
68
|
+
return os.path.join(knowledge_dir(), LEDGER_NAME)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_rules(path=None):
|
|
72
|
+
try:
|
|
73
|
+
with open(path or RULES_PATH, encoding='utf-8') as f:
|
|
74
|
+
r = json.load(f)
|
|
75
|
+
if isinstance(r, dict) and r.get('doc_re') and r.get('risk_re'):
|
|
76
|
+
return r
|
|
77
|
+
except Exception:
|
|
78
|
+
pass
|
|
79
|
+
return dict(DEFAULT_RULES)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _now_iso(t=None):
|
|
83
|
+
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() if t is None else t))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse_ts(s):
|
|
87
|
+
"""ISO(UTC, Z 또는 소수초 포함) → epoch 초. 실패면 None."""
|
|
88
|
+
if not isinstance(s, str) or len(s) < 19:
|
|
89
|
+
return None
|
|
90
|
+
try:
|
|
91
|
+
import calendar
|
|
92
|
+
return calendar.timegm(time.strptime(s[:19], '%Y-%m-%dT%H:%M:%S'))
|
|
93
|
+
except Exception:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def norm_type(t):
|
|
98
|
+
t = str(t or 'unknown')
|
|
99
|
+
return t.split(':', 1)[1] if t.startswith('routinecode:') else t
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _kept(p):
|
|
103
|
+
return isinstance(p, str) and bool(p) and not any(x in p for x in EXCLUDE_PARTS)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def classify(files, rules=None):
|
|
107
|
+
"""편집 파일 → kind. 문서만 = doc, 위험 경로 하나라도 = risk, 1~3 = main_code, 4+ = impl_large, 없음 = other."""
|
|
108
|
+
rules = rules or load_rules()
|
|
109
|
+
fs = sorted({f for f in (files or []) if isinstance(f, str) and f})
|
|
110
|
+
if not fs:
|
|
111
|
+
return 'other'
|
|
112
|
+
try:
|
|
113
|
+
doc = re.compile(rules.get('doc_re') or DEFAULT_RULES['doc_re'], re.I)
|
|
114
|
+
risk = re.compile(rules.get('risk_re') or DEFAULT_RULES['risk_re'], re.I)
|
|
115
|
+
except Exception:
|
|
116
|
+
doc = re.compile(DEFAULT_RULES['doc_re'], re.I)
|
|
117
|
+
risk = re.compile(DEFAULT_RULES['risk_re'], re.I)
|
|
118
|
+
if all(doc.search(f) for f in fs):
|
|
119
|
+
return 'doc'
|
|
120
|
+
if any(risk.search(f) for f in fs):
|
|
121
|
+
return 'risk'
|
|
122
|
+
return 'main_code' if len(fs) <= 3 else 'impl_large'
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def arm_of(card_id, rules=None):
|
|
126
|
+
"""재현 가능한 대조군 배정: sha256(card_id) % round(1/control_ratio) == 0 → control."""
|
|
127
|
+
rules = rules or load_rules()
|
|
128
|
+
try:
|
|
129
|
+
ratio = float(rules.get('control_ratio') or 0)
|
|
130
|
+
except Exception:
|
|
131
|
+
ratio = 0.0
|
|
132
|
+
if ratio <= 0 or not card_id:
|
|
133
|
+
return 'treat'
|
|
134
|
+
mod = max(1, int(round(1.0 / ratio)))
|
|
135
|
+
h = int(hashlib.sha256(str(card_id).encode('utf-8')).hexdigest(), 16)
|
|
136
|
+
return 'control' if h % mod == 0 else 'treat'
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
_CARD_KIND = re.compile(r'^\s*CARD_KIND:\s*([A-Za-z_]+)\s*$', re.M)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_OPS_MODE = re.compile(r'^\s*OPS_MODE:\s*(read-only|procedure)\s*$', re.M)
|
|
143
|
+
_CARD_REF = re.compile(r'^\s*CARD_ID:\s*([A-Za-z0-9_.-]{1,80})\s*$', re.M)
|
|
144
|
+
MODE_AGENTS = ('ops-lite', 'runner-lite')
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def parse_ops_mode(prompt):
|
|
148
|
+
if not isinstance(prompt, str):
|
|
149
|
+
return None
|
|
150
|
+
m = _OPS_MODE.search(prompt)
|
|
151
|
+
return m.group(1) if m else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ── 작업 카드(설계 34 §5.1, P2) ──
|
|
155
|
+
# 프롬프트 안의 블록. 칸 이름은 줄 머리에 온다. 목록 칸(FILES·DONE·CHECK·KEEP)은 다음 줄들의 "- " 항목.
|
|
156
|
+
# CARD_ID: <6-12 [a-z0-9]> CARD_KIND: main_code|impl_large|risk|doc|other GOAL: <한 문장>
|
|
157
|
+
# FILES: - edit: <상대경로> - read: <상대경로> DONE: - <시험·명령>
|
|
158
|
+
# CHECK: - <확인할 것> KEEP: - <바꾸면 안 되는 것> PLAN_REF: <선택>
|
|
159
|
+
# ARM: control (대조군 재배정, §6.3) ESCALATED_FROM: <card_id> (승격, §5.5)
|
|
160
|
+
CARD_ID_RE = re.compile(r'^[a-z0-9]{6,12}$')
|
|
161
|
+
CARD_KINDS = ('main_code', 'impl_large', 'risk', 'doc', 'other')
|
|
162
|
+
_CARD_FIELD = re.compile(r'^\s*(CARD_ID|CARD_KIND|GOAL|FILES|DONE|CHECK|KEEP|PLAN_REF|ARM|ESCALATED_FROM):[ \t]*(.*?)\s*$')
|
|
163
|
+
_CARD_ITEM = re.compile(r'^\s*[-*]\s+(.*?)\s*$')
|
|
164
|
+
_LIST_FIELDS = ('FILES', 'DONE', 'CHECK', 'KEEP')
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def parse_card(text):
|
|
168
|
+
"""프롬프트·카드 파일 → dict. 카드 칸이 하나도 없으면 None. 예외를 올리지 않는다.
|
|
169
|
+
|
|
170
|
+
card_ref(CARD_ID 원문, 형식이 틀려도 담고 id_ok 로 표시), kind, goal, files_edit, files_read, done,
|
|
171
|
+
check, keep, plan_ref, arm(ARM 줄), escalated_from."""
|
|
172
|
+
if not isinstance(text, str) or not text:
|
|
173
|
+
return None
|
|
174
|
+
out = {'card_ref': None, 'id_ok': False, 'kind': None, 'goal': None, 'files_edit': [], 'files_read': [],
|
|
175
|
+
'done': [], 'check': [], 'keep': [], 'plan_ref': None, 'arm': None, 'escalated_from': None}
|
|
176
|
+
seen, cur = False, None
|
|
177
|
+
for ln in text.splitlines():
|
|
178
|
+
m = _CARD_FIELD.match(ln)
|
|
179
|
+
if m:
|
|
180
|
+
seen = True
|
|
181
|
+
k, v = m.group(1), m.group(2)
|
|
182
|
+
cur = k if k in _LIST_FIELDS else None
|
|
183
|
+
if k == 'CARD_ID':
|
|
184
|
+
out['card_ref'] = v or None
|
|
185
|
+
out['id_ok'] = bool(CARD_ID_RE.match(v or ''))
|
|
186
|
+
elif k == 'CARD_KIND':
|
|
187
|
+
out['kind'] = v if v in CARD_KINDS else None
|
|
188
|
+
elif k == 'GOAL':
|
|
189
|
+
out['goal'] = v or None
|
|
190
|
+
elif k == 'PLAN_REF':
|
|
191
|
+
out['plan_ref'] = v or None
|
|
192
|
+
elif k == 'ARM':
|
|
193
|
+
out['arm'] = v.lower() or None
|
|
194
|
+
elif k == 'ESCALATED_FROM':
|
|
195
|
+
out['escalated_from'] = v if CARD_ID_RE.match(v or '') else None
|
|
196
|
+
elif v: # 목록 칸에 같은 줄 값: "DONE: npm test"
|
|
197
|
+
_card_item(out, k, v)
|
|
198
|
+
continue
|
|
199
|
+
if cur is None:
|
|
200
|
+
continue
|
|
201
|
+
mi = _CARD_ITEM.match(ln)
|
|
202
|
+
if mi and mi.group(1):
|
|
203
|
+
_card_item(out, cur, mi.group(1))
|
|
204
|
+
elif ln.strip() and not ln.startswith((' ', '\t')):
|
|
205
|
+
cur = None # 들여쓰지 않은 다른 글 = 목록 끝
|
|
206
|
+
return out if seen else None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _card_item(out, field, v):
|
|
210
|
+
if field == 'FILES':
|
|
211
|
+
m = re.match(r'^(edit|read)\s*:\s*(.+)$', v, re.I)
|
|
212
|
+
if m:
|
|
213
|
+
out['files_edit' if m.group(1).lower() == 'edit' else 'files_read'].append(m.group(2).strip())
|
|
214
|
+
else:
|
|
215
|
+
out['files_edit'].append(v)
|
|
216
|
+
else:
|
|
217
|
+
out[field.lower()].append(v)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def parse_kind_pre(prompt, rules=None):
|
|
221
|
+
if not isinstance(prompt, str):
|
|
222
|
+
return None
|
|
223
|
+
m = _CARD_KIND.search(prompt)
|
|
224
|
+
if not m:
|
|
225
|
+
return None
|
|
226
|
+
k = m.group(1)
|
|
227
|
+
kinds = (rules or load_rules()).get('kinds') or DEFAULT_RULES['kinds']
|
|
228
|
+
return k if k in kinds else None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ── 파일 입출력 ──
|
|
232
|
+
|
|
233
|
+
def append(row, p=None):
|
|
234
|
+
try:
|
|
235
|
+
p = p or ledger_path()
|
|
236
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
237
|
+
with open(p, 'a', encoding='utf-8') as f:
|
|
238
|
+
f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + '\n')
|
|
239
|
+
return True
|
|
240
|
+
except Exception:
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def read_rows(p=None, tail=None):
|
|
245
|
+
out = []
|
|
246
|
+
try:
|
|
247
|
+
with open(p or ledger_path(), 'rb') as f:
|
|
248
|
+
if tail:
|
|
249
|
+
f.seek(0, 2)
|
|
250
|
+
n = f.tell()
|
|
251
|
+
f.seek(max(0, n - tail))
|
|
252
|
+
data = f.read().decode('utf-8', 'ignore')
|
|
253
|
+
except Exception:
|
|
254
|
+
return out
|
|
255
|
+
for ln in data.splitlines():
|
|
256
|
+
ln = ln.strip()
|
|
257
|
+
if not ln:
|
|
258
|
+
continue
|
|
259
|
+
try:
|
|
260
|
+
o = json.loads(ln)
|
|
261
|
+
except Exception:
|
|
262
|
+
continue
|
|
263
|
+
if isinstance(o, dict) and o.get('ev'):
|
|
264
|
+
out.append(o)
|
|
265
|
+
return out
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def load_jsonl(path):
|
|
269
|
+
out = []
|
|
270
|
+
try:
|
|
271
|
+
with open(path, errors='replace') as f:
|
|
272
|
+
for ln in f:
|
|
273
|
+
ln = ln.strip()
|
|
274
|
+
if not ln:
|
|
275
|
+
continue
|
|
276
|
+
try:
|
|
277
|
+
o = json.loads(ln)
|
|
278
|
+
except Exception:
|
|
279
|
+
continue
|
|
280
|
+
if isinstance(o, dict):
|
|
281
|
+
out.append(o)
|
|
282
|
+
except Exception:
|
|
283
|
+
return []
|
|
284
|
+
return out
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _tool_input(inp):
|
|
288
|
+
ti = inp.get('tool_input')
|
|
289
|
+
if isinstance(ti, str):
|
|
290
|
+
try:
|
|
291
|
+
ti = json.loads(ti)
|
|
292
|
+
except Exception:
|
|
293
|
+
ti = {}
|
|
294
|
+
return ti if isinstance(ti, dict) else {}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# ── agent-pre ──
|
|
298
|
+
|
|
299
|
+
def agent_pre(inp, rules=None, p=None, now=None):
|
|
300
|
+
rules = rules or load_rules()
|
|
301
|
+
ti = _tool_input(inp)
|
|
302
|
+
card_id = inp.get('tool_use_id')
|
|
303
|
+
if not isinstance(card_id, str) or not card_id:
|
|
304
|
+
return None
|
|
305
|
+
model = ti.get('model')
|
|
306
|
+
row = {
|
|
307
|
+
'ev': 'card_open',
|
|
308
|
+
'card_id': card_id,
|
|
309
|
+
'session_id': inp.get('session_id') or '',
|
|
310
|
+
'ts': _now_iso(now),
|
|
311
|
+
'agent_type': norm_type(ti.get('subagent_type') or 'general-purpose'),
|
|
312
|
+
'requested_model': model if isinstance(model, str) and model else None,
|
|
313
|
+
'kind_pre': parse_kind_pre(ti.get('prompt'), rules),
|
|
314
|
+
'arm': arm_of(card_id, rules),
|
|
315
|
+
'rules_version': rules.get('rules_version', 1),
|
|
316
|
+
}
|
|
317
|
+
if inp.get('agent_id'):
|
|
318
|
+
row['parent_agent_id'] = str(inp.get('agent_id'))
|
|
319
|
+
prompt = ti.get('prompt') if isinstance(ti.get('prompt'), str) else ''
|
|
320
|
+
if row['agent_type'] in MODE_AGENTS:
|
|
321
|
+
mode = parse_ops_mode(prompt)
|
|
322
|
+
if mode:
|
|
323
|
+
row['ops_mode'] = mode
|
|
324
|
+
m = _CARD_REF.search(prompt)
|
|
325
|
+
if m:
|
|
326
|
+
row['card_ref'] = m.group(1)
|
|
327
|
+
elif row['agent_type'] in CARD_AGENTS:
|
|
328
|
+
_card_open_fields(row, prompt)
|
|
329
|
+
return row if append(row, p) else None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
CARD_AGENTS = ('implementor-lite', 'implementor')
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _card_open_fields(row, prompt):
|
|
336
|
+
"""P2 구현 카드: card_ref·n_check·n_keep·plan_ref, arm 재정의(카드가 있을 때만).
|
|
337
|
+
|
|
338
|
+
implementor-lite = haiku / ARM: control = control(대조군, §6.3) / ESCALATED_FROM = escalated(M5) /
|
|
339
|
+
CARD_KIND: risk 인 implementor = risk. CARD_ID 가 없는 implementor 는 P0 그대로(arm_of(tool_use_id))."""
|
|
340
|
+
c = parse_card(prompt)
|
|
341
|
+
if not c or not c.get('card_ref'):
|
|
342
|
+
return
|
|
343
|
+
row['card_ref'] = c['card_ref']
|
|
344
|
+
row['n_check'] = len(c['check'])
|
|
345
|
+
row['n_keep'] = len(c['keep'])
|
|
346
|
+
if c.get('plan_ref'):
|
|
347
|
+
row['plan_ref'] = c['plan_ref']
|
|
348
|
+
if c.get('kind') and not row.get('kind_pre'):
|
|
349
|
+
row['kind_pre'] = c['kind']
|
|
350
|
+
if row['agent_type'] == 'implementor-lite':
|
|
351
|
+
row['arm'] = 'haiku'
|
|
352
|
+
elif c.get('escalated_from'):
|
|
353
|
+
row['arm'] = 'escalated'
|
|
354
|
+
row['escalated_from'] = c['escalated_from']
|
|
355
|
+
elif c.get('arm') == 'control':
|
|
356
|
+
row['arm'] = 'control'
|
|
357
|
+
elif c.get('kind') == 'risk':
|
|
358
|
+
row['arm'] = 'risk'
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ── subagent-stop ──
|
|
362
|
+
|
|
363
|
+
def _norm_agent_id(v):
|
|
364
|
+
if not isinstance(v, str):
|
|
365
|
+
return ''
|
|
366
|
+
v = v.strip()
|
|
367
|
+
return v[len('agent-'):] if v.startswith('agent-') else v
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def resolve_agent_path(inp):
|
|
371
|
+
"""usage_v2.resolve_agent_path 와 같은 규칙: agent_transcript_path, 없으면 메인 transcript 옆 subagents/."""
|
|
372
|
+
p = inp.get('agent_transcript_path')
|
|
373
|
+
if isinstance(p, str) and p:
|
|
374
|
+
return p
|
|
375
|
+
tp = inp.get('transcript_path')
|
|
376
|
+
aid = _norm_agent_id(inp.get('agent_id'))
|
|
377
|
+
if isinstance(tp, str) and tp.endswith('.jsonl') and aid:
|
|
378
|
+
return os.path.join(tp[:-len('.jsonl')] + '/subagents', 'agent-%s.jsonl' % aid)
|
|
379
|
+
return ''
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def agent_meta(agent_path):
|
|
383
|
+
try:
|
|
384
|
+
with open(agent_path[:-len('.jsonl')] + '.meta.json', encoding='utf-8') as f:
|
|
385
|
+
m = json.load(f)
|
|
386
|
+
return m if isinstance(m, dict) else {}
|
|
387
|
+
except Exception:
|
|
388
|
+
return {}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _i(v):
|
|
392
|
+
return v if isinstance(v, int) and not isinstance(v, bool) and v > 0 else 0
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
USAGE_KEYS = (('input', 'input_tokens'), ('output', 'output_tokens'),
|
|
396
|
+
('cache_read', 'cache_read_input_tokens'), ('cache_write', 'cache_creation_input_tokens'))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def summarize_agent(entries):
|
|
400
|
+
"""transcript → (usage 합계, 모델별 usage, 대표 모델, 편집 파일, 도구 호출 수, 응답 수).
|
|
401
|
+
|
|
402
|
+
한 응답(message.id)은 내용 블록마다 줄로 기록되며 같은 usage 를 반복한다 → id 당 필드별 최대값 1회만 센다."""
|
|
403
|
+
per = {}
|
|
404
|
+
files, calls = set(), 0
|
|
405
|
+
for e in entries:
|
|
406
|
+
if e.get('type') != 'assistant':
|
|
407
|
+
continue
|
|
408
|
+
msg = e.get('message') if isinstance(e.get('message'), dict) else {}
|
|
409
|
+
for b in msg.get('content') or []:
|
|
410
|
+
if not isinstance(b, dict) or b.get('type') != 'tool_use':
|
|
411
|
+
continue
|
|
412
|
+
calls += 1
|
|
413
|
+
if b.get('name') in EDIT_TOOLS:
|
|
414
|
+
bi = b.get('input') if isinstance(b.get('input'), dict) else {}
|
|
415
|
+
fp = bi.get('file_path') or bi.get('notebook_path')
|
|
416
|
+
if _kept(fp):
|
|
417
|
+
files.add(fp)
|
|
418
|
+
u = msg.get('usage')
|
|
419
|
+
mid = msg.get('id') if isinstance(msg.get('id'), str) and msg.get('id') else e.get('uuid')
|
|
420
|
+
model = msg.get('model') if isinstance(msg.get('model'), str) else ''
|
|
421
|
+
if not isinstance(u, dict) or not mid or model == '<synthetic>':
|
|
422
|
+
continue
|
|
423
|
+
vals = {k: _i(u.get(src)) for k, src in USAGE_KEYS}
|
|
424
|
+
cur = per.get(mid)
|
|
425
|
+
if cur is None:
|
|
426
|
+
per[mid] = {'u': vals, 'model': model}
|
|
427
|
+
else:
|
|
428
|
+
cur['u'] = {k: max(cur['u'][k], vals[k]) for k in vals}
|
|
429
|
+
cur['model'] = cur['model'] or model
|
|
430
|
+
total = {k: 0 for k, _ in USAGE_KEYS}
|
|
431
|
+
by_model, counts = {}, {}
|
|
432
|
+
for m in per.values():
|
|
433
|
+
mm = m['model'] or 'unknown'
|
|
434
|
+
bm = by_model.setdefault(mm, {k: 0 for k, _ in USAGE_KEYS})
|
|
435
|
+
for k in total:
|
|
436
|
+
total[k] += m['u'][k]
|
|
437
|
+
bm[k] += m['u'][k]
|
|
438
|
+
counts[mm] = counts.get(mm, 0) + 1
|
|
439
|
+
actual = max(counts, key=lambda k: counts[k]) if counts else None
|
|
440
|
+
return total, by_model, actual, sorted(files), calls, len(per)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _last_close(card_id, p=None):
|
|
444
|
+
last = None
|
|
445
|
+
for r in read_rows(p, tail=TAIL_BYTES):
|
|
446
|
+
if r.get('ev') == 'card_close' and r.get('card_id') == card_id:
|
|
447
|
+
last = r
|
|
448
|
+
return last
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def subagent_stop(inp, rules=None, p=None, now=None):
|
|
452
|
+
rules = rules or load_rules()
|
|
453
|
+
path = resolve_agent_path(inp)
|
|
454
|
+
if not path or not os.path.exists(path):
|
|
455
|
+
return None
|
|
456
|
+
meta = agent_meta(path)
|
|
457
|
+
aid = _norm_agent_id(inp.get('agent_id')) or _norm_agent_id(os.path.basename(path)[:-len('.jsonl')])
|
|
458
|
+
card_id = meta.get('toolUseId') or aid # agent_telemetry.py spawnId 와 같다
|
|
459
|
+
if not card_id:
|
|
460
|
+
return None
|
|
461
|
+
total, by_model, actual, files, calls, msg_n = summarize_agent(load_jsonl(path))
|
|
462
|
+
prev = _last_close(card_id, p)
|
|
463
|
+
if prev and prev.get('msg_n') == msg_n and prev.get('usage') == total and prev.get('files_touched') == files:
|
|
464
|
+
return None # 같은 내용으로 다시 멈춤 → 쓰지 않는다(멱등)
|
|
465
|
+
row = {
|
|
466
|
+
'ev': 'card_close',
|
|
467
|
+
'card_id': card_id,
|
|
468
|
+
'agent_id': aid,
|
|
469
|
+
'session_id': inp.get('session_id') or '',
|
|
470
|
+
'ts': _now_iso(now),
|
|
471
|
+
'agent_type': norm_type(inp.get('agent_type') or meta.get('agentType')),
|
|
472
|
+
'actual_model': actual,
|
|
473
|
+
'files_touched': files,
|
|
474
|
+
'kind_post': classify(files, rules),
|
|
475
|
+
'tool_calls': calls,
|
|
476
|
+
'usage': total,
|
|
477
|
+
'usage_by_model': by_model,
|
|
478
|
+
'msg_n': msg_n,
|
|
479
|
+
'rules_version': rules.get('rules_version', 1),
|
|
480
|
+
}
|
|
481
|
+
return row if append(row, p) else None
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
# ── main-edit ──
|
|
485
|
+
|
|
486
|
+
def main_edit(inp, rules=None, p=None, now=None):
|
|
487
|
+
if inp.get('agent_id'): # 서브에이전트 안의 편집(post-agent-budget.sh 와 같은 판별)
|
|
488
|
+
return None
|
|
489
|
+
if inp.get('tool_name') and inp.get('tool_name') not in EDIT_TOOLS:
|
|
490
|
+
return None
|
|
491
|
+
ti = _tool_input(inp)
|
|
492
|
+
fp = ti.get('file_path') or ti.get('notebook_path')
|
|
493
|
+
if not _kept(fp):
|
|
494
|
+
return None
|
|
495
|
+
rules = rules or load_rules()
|
|
496
|
+
ts = _now_iso(now)
|
|
497
|
+
sid = inp.get('session_id') or ''
|
|
498
|
+
eid = inp.get('tool_use_id') or hashlib.sha256(('%s|%s|%s' % (sid, ts, fp)).encode('utf-8')).hexdigest()[:16]
|
|
499
|
+
row = {'ev': 'main_edit', 'edit_id': eid, 'session_id': sid, 'ts': ts, 'file': fp,
|
|
500
|
+
'kind': classify([fp], rules), 'arm': 'main', 'rules_version': rules.get('rules_version', 1)}
|
|
501
|
+
return row if append(row, p) else None
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
# ── backfill ──
|
|
505
|
+
|
|
506
|
+
def same_session_window(rules=None):
|
|
507
|
+
try:
|
|
508
|
+
v = int(((rules or load_rules()).get('refix') or {}).get('same_session_window_s') or SAME_SESSION_WINDOW_S)
|
|
509
|
+
return v if v > 0 else SAME_SESSION_WINDOW_S
|
|
510
|
+
except Exception:
|
|
511
|
+
return SAME_SESSION_WINDOW_S
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def backfill(p=None, now=None, rules=None):
|
|
515
|
+
"""7일이 지난 card_close(카드별 마지막 행)·main_edit 에 refix 보강 행을 단다. 이미 있으면 건너뛴다(멱등).
|
|
516
|
+
|
|
517
|
+
(ts, ts+7일] 안의 다른 main_edit·card_close 가 같은 파일을 편집했으면 재수정이다. 둘로 나눈다(P1):
|
|
518
|
+
refix_same_session = 같은 세션 AND 원 편집 뒤 2시간 안 — 카드를 맡긴 메인이 곧바로 이어서 고친 것
|
|
519
|
+
(작업 안의 후속 편집. P0 기준선 implementor 43% 의 대부분)
|
|
520
|
+
refix_later = 다른 세션 OR 2시간 뒤 — 나중에 다시 고쳐야 했던 것
|
|
521
|
+
refix_7d = refix_later (M8 품질 기준)
|
|
522
|
+
같은 카드의 이후 행, 같은 세션의 이어진 메인 편집(한 작업 안의 반복 편집)은 재수정으로 세지 않는다.
|
|
523
|
+
이전 버전이 쓴 refix 행(refix_later 없음)은 다시 쓰지 않는다 — 지표가 refix_7d 로 읽는다."""
|
|
524
|
+
now = time.time() if now is None else now
|
|
525
|
+
win = same_session_window(rules)
|
|
526
|
+
rows = read_rows(p)
|
|
527
|
+
done = {r.get('ref') for r in rows if r.get('ev') == 'refix'}
|
|
528
|
+
arms = {r.get('card_id'): r.get('arm') for r in rows if r.get('ev') == 'card_open'}
|
|
529
|
+
closes = {}
|
|
530
|
+
for r in rows:
|
|
531
|
+
if r.get('ev') == 'card_close' and r.get('card_id'):
|
|
532
|
+
closes[r['card_id']] = r
|
|
533
|
+
touches = [] # (ts, files, card_id, session_id, ev)
|
|
534
|
+
for r in closes.values():
|
|
535
|
+
t = parse_ts(r.get('ts'))
|
|
536
|
+
if t is not None:
|
|
537
|
+
touches.append((t, set(r.get('files_touched') or []), r.get('card_id'), r.get('session_id'), 'card_close'))
|
|
538
|
+
edits = [r for r in rows if r.get('ev') == 'main_edit']
|
|
539
|
+
for r in edits:
|
|
540
|
+
t = parse_ts(r.get('ts'))
|
|
541
|
+
if t is not None and r.get('file'):
|
|
542
|
+
touches.append((t, {r['file']}, None, r.get('session_id'), 'main_edit'))
|
|
543
|
+
srcs = [('card:' + cid, r, 'card_close') for cid, r in closes.items()]
|
|
544
|
+
srcs += [('edit:' + str(r.get('edit_id')), r, 'main_edit') for r in edits if r.get('edit_id')]
|
|
545
|
+
out = []
|
|
546
|
+
for ref, r, ev in srcs:
|
|
547
|
+
if ref in done:
|
|
548
|
+
continue
|
|
549
|
+
t = parse_ts(r.get('ts'))
|
|
550
|
+
if t is None or now - t < REFIX_WINDOW_S:
|
|
551
|
+
continue
|
|
552
|
+
files = set(r.get('files_touched') or []) if ev == 'card_close' else {r.get('file')}
|
|
553
|
+
same = later = False
|
|
554
|
+
sid = r.get('session_id')
|
|
555
|
+
if files:
|
|
556
|
+
for (t2, f2, cid2, sid2, ev2) in touches:
|
|
557
|
+
if not (t < t2 <= t + REFIX_WINDOW_S) or not (files & f2):
|
|
558
|
+
continue
|
|
559
|
+
if ev == 'card_close' and cid2 == r.get('card_id'):
|
|
560
|
+
continue
|
|
561
|
+
if ev == 'main_edit' and ev2 == 'main_edit' and sid2 and sid2 == sid:
|
|
562
|
+
continue
|
|
563
|
+
if sid and sid2 == sid and t2 - t <= win:
|
|
564
|
+
same = True
|
|
565
|
+
else:
|
|
566
|
+
later = True
|
|
567
|
+
if later and same:
|
|
568
|
+
break
|
|
569
|
+
row = {'ev': 'refix', 'ref': ref, 'src_ev': ev, 'src_ts': r.get('ts'), 'ts': _now_iso(now),
|
|
570
|
+
'kind': r.get('kind_post') if ev == 'card_close' else r.get('kind'),
|
|
571
|
+
'arm': arms.get(r.get('card_id'), 'unknown') if ev == 'card_close' else 'main',
|
|
572
|
+
'agent_type': r.get('agent_type') if ev == 'card_close' else 'main',
|
|
573
|
+
'refix_7d': later, 'refix_same_session': same, 'refix_later': later,
|
|
574
|
+
'same_session_window_s': win}
|
|
575
|
+
if append(row, p):
|
|
576
|
+
out.append(row)
|
|
577
|
+
done.add(ref)
|
|
578
|
+
return out
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def maybe_backfill(p=None, now=None):
|
|
582
|
+
"""하루 한 번만 — SubagentStop 백그라운드 실행 끝에서 부른다."""
|
|
583
|
+
try:
|
|
584
|
+
stamp = os.path.join(os.path.dirname(p or ledger_path()), BACKFILL_STAMP)
|
|
585
|
+
now = time.time() if now is None else now
|
|
586
|
+
try:
|
|
587
|
+
if now - os.path.getmtime(stamp) < BACKFILL_MIN_INTERVAL_S:
|
|
588
|
+
return None
|
|
589
|
+
except OSError:
|
|
590
|
+
pass
|
|
591
|
+
with open(stamp, 'w') as f:
|
|
592
|
+
f.write(str(int(now)))
|
|
593
|
+
return backfill(p, now)
|
|
594
|
+
except Exception:
|
|
595
|
+
return None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _main(argv):
|
|
599
|
+
if disabled() or len(argv) < 2:
|
|
600
|
+
return 0
|
|
601
|
+
cmd = argv[1]
|
|
602
|
+
try:
|
|
603
|
+
if cmd == 'backfill':
|
|
604
|
+
backfill()
|
|
605
|
+
return 0
|
|
606
|
+
inp = json.load(sys.stdin)
|
|
607
|
+
if not isinstance(inp, dict):
|
|
608
|
+
return 0
|
|
609
|
+
if cmd == 'agent-pre':
|
|
610
|
+
agent_pre(inp)
|
|
611
|
+
elif cmd == 'subagent-stop':
|
|
612
|
+
subagent_stop(inp)
|
|
613
|
+
maybe_backfill()
|
|
614
|
+
elif cmd == 'main-edit':
|
|
615
|
+
main_edit(inp)
|
|
616
|
+
except Exception:
|
|
617
|
+
pass
|
|
618
|
+
return 0
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
if __name__ == '__main__':
|
|
622
|
+
sys.exit(_main(sys.argv))
|