@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.
Files changed (65) hide show
  1. package/bin/cli.sh +10 -0
  2. package/bin/prompt-vault.dat +1 -1
  3. package/bin/rc-login.js +5 -4
  4. package/bin/rc-savings.js +808 -0
  5. package/bin/rc-suggestions.js +100 -0
  6. package/bin/rc-team.js +1 -1
  7. package/bin/setup.js +1 -1
  8. package/hooks/hooks-config.json +9 -0
  9. package/hooks/lib/agent_budget.py +2 -0
  10. package/hooks/lib/calibration.json +89 -0
  11. package/hooks/lib/card_gate.py +735 -0
  12. package/hooks/lib/cc-surface.json +1 -1
  13. package/hooks/lib/codemode_guard.py +30 -0
  14. package/hooks/lib/command_fix.py +209 -0
  15. package/hooks/lib/delegate_nudge.py +179 -0
  16. package/hooks/lib/deploy_suggest.py +312 -0
  17. package/hooks/lib/emit_raw.py +4 -0
  18. package/hooks/lib/knowledge_items.py +281 -22
  19. package/hooks/lib/knowledge_stock.py +708 -0
  20. package/hooks/lib/known_solution.py +1 -1
  21. package/hooks/lib/ops_guard.py +549 -0
  22. package/hooks/lib/prices.json +8 -0
  23. package/hooks/lib/route_ledger.py +622 -0
  24. package/hooks/lib/route_rules.json +88 -0
  25. package/hooks/lib/savings_emit.py +93 -0
  26. package/hooks/lib/secret_filter.py +11 -0
  27. package/hooks/lib/sync_manager.py +4 -1
  28. package/hooks/post-bash-verify.sh +14 -0
  29. package/hooks/post-edit-track.sh +9 -0
  30. package/hooks/pre-agent-spawn.mjs +1 -1
  31. package/hooks/pre-agent-spawn.sh +22 -2
  32. package/hooks/pre-bash-guard.sh +31 -0
  33. package/hooks/pre-bash-knowledge.sh +12 -2
  34. package/hooks/pre-edit-delegate.sh +15 -0
  35. package/hooks/pre-edit-guard.sh +10 -0
  36. package/hooks/pre-read-guard.sh +10 -0
  37. package/hooks/session-start.sh +6 -0
  38. package/hooks/stop-usage-metrics.sh +6 -0
  39. package/hooks/subagent-stop-usage.sh +36 -4
  40. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  41. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  42. package/mcp-routinecode/dist/index.js +1 -1
  43. package/package.json +1 -1
  44. package/plugin/.claude-plugin/plugin.json +1 -1
  45. package/plugin/agents/analyzer.md.sealed +1 -1
  46. package/plugin/agents/architect.md.sealed +1 -1
  47. package/plugin/agents/crawler.md.sealed +1 -1
  48. package/plugin/agents/explorer.md.sealed +1 -1
  49. package/plugin/agents/implementor-lite.md.sealed +1 -0
  50. package/plugin/agents/implementor.md.sealed +1 -1
  51. package/plugin/agents/looker.md.sealed +1 -1
  52. package/plugin/agents/ops-lite.md.sealed +1 -0
  53. package/plugin/agents/planner.md.sealed +1 -1
  54. package/plugin/agents/recorder.md.sealed +1 -1
  55. package/plugin/agents/reviewer.md.sealed +1 -1
  56. package/plugin/agents/runner-lite.md.sealed +1 -0
  57. package/plugin/agents/verifier.md.sealed +1 -1
  58. package/plugin/commands/analyze.md.sealed +1 -1
  59. package/plugin/commands/plan.md.sealed +1 -1
  60. package/plugin/commands/rc.md.sealed +1 -1
  61. package/plugin/commands/receipt.md.sealed +1 -1
  62. package/plugin/commands/recharge.md.sealed +1 -1
  63. package/plugin/commands/routines.md.sealed +1 -1
  64. package/plugin/commands/share.md.sealed +1 -1
  65. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -166,7 +166,7 @@ def consume_v31(session_id, error_text, command=None, fallback=False):
166
166
  if not rec:
167
167
  return None
168
168
  pk = rec['problemKey']
169
- sel = ki.select([{'type': 'problem', 'problemKey': pk}], session_id=session_id)
169
+ sel = ki.select([{'type': 'problem', 'problemKey': pk, 'errorText': error_text}], session_id=session_id) # 36-3 E1
170
170
  if sel:
171
171
  ki.record_exposure(sel, session_id, 'inject:bash', problem_key=pk)
172
172
  ki.mark_problem_shown(session_id, pk)
@@ -0,0 +1,549 @@
1
+ # -*- coding: utf-8 -*-
2
+ """ops-lite 운영 작업자 Bash 허용목록 — 설계 34 §5.3·§5.6 F5·§6.1 M10 (P1).
3
+
4
+ pre-bash-guard.sh 가 모든 Bash PreToolUse 에서 check_hook(inp, cmd) 를 부른다.
5
+ - ops-lite 가 아닌 호출(메인 세션·다른 에이전트) → None (판정·출력 불변). 내부 오류도 None(fail-open).
6
+ - ops-lite → 허용목록(route_rules.json "ops") 안이면 None, 밖이면 (rule, reason) 을 돌려주고
7
+ route-ledger 에 ev=blocked_cmd 행을 남긴다. ops-lite 판정 중 내부 오류 = 차단(fail-closed).
8
+
9
+ 작업자 판별: 훅 입력 agent_type(서브에이전트 안 도구 호출에 CC 가 넣는 값), 없으면 agent_id →
10
+ <transcript>/subagents/agent-<id>.meta.json 의 agentType.
11
+
12
+ 모드(§5.3):
13
+ 읽기 전용(기본) — route_rules.json ops.commands 의 명령만(세부 규칙은 _check_segment).
14
+ 절차 — scripts/ops/<이름>.sh 만. read_only_scripts(status.sh·wait-*.sh)는 승인 없이,
15
+ 그 밖은 <knowledge>/ops-approvals/<card_id>.json 의 "scripts" 에 이름이 있어야 한다
16
+ (메인 세션이 쓴다. card_id = 프롬프트의 CARD_ID: 줄 또는 Agent tool_use_id).
17
+ ssh <별칭> "<명령>" — 별칭만(옵션·user@·IP 금지), 안쪽 명령도 같은 허용목록(스크립트·ssh 중첩 제외).
18
+ 표준 라이브러리만. 표준 출력에 쓰지 않는다(판정은 호출자가 낸다).
19
+ """
20
+ import fnmatch
21
+ import json
22
+ import os
23
+ import re
24
+ import shlex
25
+ import time
26
+
27
+ HERE = os.path.dirname(os.path.abspath(__file__))
28
+
29
+ try:
30
+ import route_ledger as rl
31
+ except Exception: # pragma: no cover — 같은 디렉터리라 실패하지 않는다
32
+ rl = None
33
+
34
+ SEP_TOKENS = {';', '&&', '||', '|', '|&'}
35
+ FILTERS = {'grep', 'wc', 'sort', 'uniq', 'cut', 'jq', 'head', 'tail'}
36
+ PATH_READERS = {'cat', 'tail', 'head', 'grep', 'ls', 'wc', 'sort', 'uniq', 'cut', 'jq'}
37
+ HEAD_SCAN_BYTES = 64 * 1024
38
+
39
+ DEFAULT_OPS = {'version': 1, 'agent_types': ['ops-lite'], 'approval_dir': 'ops-approvals', 'commands': []}
40
+
41
+
42
+ class Deny(Exception):
43
+ def __init__(self, rule, detail=''):
44
+ Exception.__init__(self, rule)
45
+ self.rule = rule
46
+ self.detail = detail
47
+
48
+
49
+ # ── 규칙 ──
50
+
51
+ def load_ops(rules=None):
52
+ if rules is None:
53
+ rules = rl.load_rules() if rl else {}
54
+ ops = rules.get('ops') if isinstance(rules, dict) else None
55
+ return ops if isinstance(ops, dict) and ops.get('commands') else dict(DEFAULT_OPS)
56
+
57
+
58
+ def _norm_type(t):
59
+ t = str(t or '')
60
+ return t.split(':')[-1] if ':' in t else t
61
+
62
+
63
+ # ── 작업자 판별 ──
64
+
65
+ def _agent_transcript(inp):
66
+ aid = str(inp.get('agent_id') or '').strip()
67
+ if aid.startswith('agent-'):
68
+ aid = aid[len('agent-'):]
69
+ p = inp.get('agent_transcript_path')
70
+ if isinstance(p, str) and p.endswith('.jsonl'):
71
+ return p
72
+ tp = inp.get('transcript_path')
73
+ if not isinstance(tp, str) or not tp.endswith('.jsonl') or not aid:
74
+ return ''
75
+ if '/subagents/' in tp:
76
+ return tp
77
+ return os.path.join(tp[:-len('.jsonl')], 'subagents', 'agent-%s.jsonl' % aid)
78
+
79
+
80
+ def _meta(agent_path):
81
+ if not agent_path:
82
+ return {}
83
+ try:
84
+ with open(agent_path[:-len('.jsonl')] + '.meta.json', encoding='utf-8') as f:
85
+ m = json.load(f)
86
+ return m if isinstance(m, dict) else {}
87
+ except Exception:
88
+ return {}
89
+
90
+
91
+ def agent_type_of(inp):
92
+ """서브에이전트 종류(접두어 없음). 메인 세션 = None."""
93
+ at = inp.get('agent_type')
94
+ if isinstance(at, str) and at:
95
+ return _norm_type(at)
96
+ if not inp.get('agent_id'):
97
+ return None
98
+ m = _meta(_agent_transcript(inp))
99
+ return _norm_type(m.get('agentType')) or None
100
+
101
+
102
+ def is_ops_agent(inp, ops=None):
103
+ at = agent_type_of(inp)
104
+ return bool(at) and at in set((ops or load_ops()).get('agent_types') or ['ops-lite'])
105
+
106
+
107
+ _CARD_ID = re.compile(r'^\s*CARD_ID:\s*([A-Za-z0-9_.-]{1,80})\s*$', re.M)
108
+
109
+
110
+ def card_ids(inp):
111
+ """승인 파일을 찾을 card_id 후보: 프롬프트(작업자 transcript 첫 부분)의 CARD_ID: 줄, Agent tool_use_id."""
112
+ out = []
113
+ path = _agent_transcript(inp)
114
+ if path:
115
+ try:
116
+ with open(path, 'rb') as f:
117
+ head = f.read(HEAD_SCAN_BYTES).decode('utf-8', 'ignore')
118
+ for ln in head.splitlines():
119
+ try:
120
+ o = json.loads(ln)
121
+ except Exception:
122
+ continue
123
+ if not isinstance(o, dict) or o.get('type') != 'user':
124
+ continue
125
+ c = (o.get('message') or {}).get('content')
126
+ text = c if isinstance(c, str) else ' '.join(
127
+ x.get('text', '') for x in (c or []) if isinstance(x, dict) and x.get('type') == 'text')
128
+ m = _CARD_ID.search(text or '')
129
+ if m:
130
+ out.append(m.group(1))
131
+ break
132
+ except Exception:
133
+ pass
134
+ tid = _meta(path).get('toolUseId')
135
+ if isinstance(tid, str) and tid and tid not in out:
136
+ out.append(tid)
137
+ return out
138
+
139
+
140
+ # ── 승인 파일 ──
141
+
142
+ def approval_dir(ops=None):
143
+ base = rl.knowledge_dir() if rl else os.path.expanduser('~/.routinecode/knowledge')
144
+ return os.path.join(base, (ops or load_ops()).get('approval_dir') or 'ops-approvals')
145
+
146
+
147
+ def approved_scripts(ids, ops=None, now=None):
148
+ """승인 파일들의 scripts 합집합. expires_at(ISO, 선택)이 지난 파일은 무시."""
149
+ now = time.time() if now is None else now
150
+ names = set()
151
+ d = approval_dir(ops)
152
+ for cid in ids:
153
+ if not re.fullmatch(r'[A-Za-z0-9_.-]{1,80}', cid or '') or cid.startswith('.'):
154
+ continue
155
+ try:
156
+ with open(os.path.join(d, cid + '.json'), encoding='utf-8') as f:
157
+ a = json.load(f)
158
+ except Exception:
159
+ continue
160
+ if not isinstance(a, dict):
161
+ continue
162
+ exp = a.get('expires_at')
163
+ if exp and rl and (rl.parse_ts(exp) or 0) < now:
164
+ continue
165
+ for s in a.get('scripts') or []:
166
+ if isinstance(s, str):
167
+ names.add(os.path.basename(s))
168
+ return names
169
+
170
+
171
+ # ── 명령 분해 ──
172
+
173
+ def _scan(cmd):
174
+ """따옴표 밖 $·백틱·서브셸·여러 줄을 잡는다. 따옴표 밖 줄바꿈은 ';' 로 바꾼 문자열을 돌려준다."""
175
+ out, q, i = [], None, 0
176
+ while i < len(cmd):
177
+ ch = cmd[i]
178
+ if q == "'":
179
+ if ch == "'":
180
+ q = None
181
+ elif ch == '\\' and q != "'":
182
+ out.append(ch)
183
+ i += 1
184
+ if i < len(cmd):
185
+ if cmd[i] == '\n':
186
+ raise Deny('line_continuation')
187
+ out.append(cmd[i])
188
+ i += 1
189
+ continue
190
+ elif ch == '`' or (ch == '$' and q != "'"):
191
+ raise Deny('expansion', '$·백틱 확장(변수·명령 치환)은 쓸 수 없다')
192
+ elif q == '"':
193
+ if ch == '"':
194
+ q = None
195
+ elif ch in ('"', "'"):
196
+ q = ch
197
+ elif ch == '\n':
198
+ out.append(' ; ')
199
+ i += 1
200
+ continue
201
+ out.append(ch)
202
+ i += 1
203
+ if q:
204
+ raise Deny('unbalanced_quote')
205
+ return ''.join(out)
206
+
207
+
208
+ def _tokens(cmd):
209
+ lx = shlex.shlex(cmd, posix=True, punctuation_chars=True)
210
+ lx.whitespace_split = True
211
+ lx.commenters = ''
212
+ return list(lx)
213
+
214
+
215
+ def _segments(tokens):
216
+ segs, cur = [], []
217
+ for t in tokens:
218
+ if t in SEP_TOKENS:
219
+ if not cur:
220
+ raise Deny('syntax')
221
+ segs.append(cur)
222
+ cur = []
223
+ else:
224
+ cur.append(t)
225
+ if cur:
226
+ segs.append(cur)
227
+ elif segs:
228
+ raise Deny('syntax')
229
+ return segs
230
+
231
+
232
+ def _strip_redirects(seg):
233
+ """허용 리디렉션(>/dev/null, 2>&1, &>/dev/null)만 지우고, 그 밖은 차단."""
234
+ out, i = [], 0
235
+ while i < len(seg):
236
+ t = seg[i]
237
+ if t and set(t) <= set('<>&();|'):
238
+ if t in ('>', '>>', '&>', '&>>'):
239
+ nxt = seg[i + 1] if i + 1 < len(seg) else ''
240
+ if nxt != '/dev/null':
241
+ raise Deny('redirect', '출력 리디렉션은 /dev/null 만 된다')
242
+ if out and out[-1] in ('1', '2'):
243
+ out.pop()
244
+ i += 2
245
+ continue
246
+ if t == '>&':
247
+ nxt = seg[i + 1] if i + 1 < len(seg) else ''
248
+ if nxt not in ('1', '2'):
249
+ raise Deny('redirect')
250
+ if out and out[-1] in ('1', '2'):
251
+ out.pop()
252
+ i += 2
253
+ continue
254
+ if t in ('(', ')'):
255
+ raise Deny('subshell')
256
+ if t == '&':
257
+ raise Deny('background', '백그라운드 실행(&)은 쓸 수 없다')
258
+ if ';' in t or '|' in t:
259
+ raise Deny('syntax')
260
+ raise Deny('redirect', '입력 리디렉션·히어독은 쓸 수 없다')
261
+ out.append(t)
262
+ i += 1
263
+ return out
264
+
265
+
266
+ def _flags(args):
267
+ return [a for a in args if a.startswith('-') and a != '-']
268
+
269
+
270
+ def _match_cmd(tokens, ops):
271
+ best = None
272
+ for pat in ops.get('commands') or []:
273
+ if isinstance(pat, list) and pat and tokens[:len(pat)] == pat and (best is None or len(pat) > len(best)):
274
+ best = pat
275
+ return best
276
+
277
+
278
+ def _flag_hit(flag, banned):
279
+ """긴 옵션은 접두어(--data → --data-raw), 짧은 옵션은 묶음 안 글자(-f → -nf)까지 잡는다."""
280
+ for b in banned:
281
+ if flag == b or (b.startswith('--') and flag.startswith(b)):
282
+ return b
283
+ if not b.startswith('--') and len(b) == 2 and not flag.startswith('--') and b[1] in flag[1:]:
284
+ return b
285
+ return None
286
+
287
+
288
+ def _check_paths(args, ops, cmd0):
289
+ sec = re.compile(ops.get('secret_path_re') or r'(\.env\b|secret|credential)', re.I)
290
+ for a in args:
291
+ if a.startswith('-'):
292
+ continue
293
+ if '..' in a.split('/'):
294
+ raise Deny('path_traversal')
295
+ if sec.search(a):
296
+ raise Deny('secret_path', '비밀 파일 경로는 읽을 수 없다: %s' % a[:40])
297
+ if cmd0 == 'cat':
298
+ logre = re.compile(ops.get('cat_path_re') or r'\.log$', re.I)
299
+ files = [a for a in args if not a.startswith('-')]
300
+ if not files or not all(logre.search(a) for a in files):
301
+ raise Deny('cat_not_log', 'cat 은 로그 파일(*.log, /log/·/logs/ 아래)만 된다')
302
+
303
+
304
+ CURL_VALUE_FLAGS = ('-m', '--max-time', '--connect-timeout', '-w', '--write-out', '--retry', '--retry-delay',
305
+ '--retry-max-time', '-A', '--user-agent')
306
+
307
+
308
+ def _curl_args(args):
309
+ """`-o /dev/null`(상태 코드만 보기)은 허용한다 — 플래그 검사 전에 지운다."""
310
+ out, i = [], 0
311
+ while i < len(args):
312
+ if args[i] in ('-o', '--output') and i + 1 < len(args) and args[i + 1] == '/dev/null':
313
+ i += 2
314
+ continue
315
+ out.append(args[i])
316
+ i += 1
317
+ return out
318
+
319
+
320
+ def _check_curl(args, ops):
321
+ short = set(ops.get('curl_short_deny') or 'XdFTOoKuHbc')
322
+ for a in args:
323
+ if a.startswith('-') and not a.startswith('--') and len(a) > 2:
324
+ hit = set(a[1:]) & short
325
+ if hit:
326
+ raise Deny('curl_write', 'curl 은 -s GET 만 된다(-%s 금지)' % sorted(hit)[0])
327
+ urls, i = [], 0
328
+ while i < len(args):
329
+ a = args[i]
330
+ if a in CURL_VALUE_FLAGS:
331
+ i += 2
332
+ continue
333
+ if not a.startswith('-'):
334
+ urls.append(a)
335
+ i += 1
336
+ if any(not re.match(r'^https?://', u) for u in urls) or not urls:
337
+ raise Deny('curl_url', 'curl 대상은 http(s):// URL 이어야 한다')
338
+
339
+
340
+ def _check_psql(args, ops):
341
+ sel = re.compile(ops.get('psql_select_re') or r'^\s*select\b', re.I)
342
+ wr = re.compile(ops.get('psql_write_re') or r'\b(insert|update|delete|drop|alter|create|truncate)\b', re.I)
343
+ sqls, i = [], 0
344
+ while i < len(args):
345
+ a = args[i]
346
+ if a in ('-c', '--command'):
347
+ if i + 1 >= len(args):
348
+ raise Deny('psql_no_sql')
349
+ sqls.append(args[i + 1])
350
+ i += 2
351
+ continue
352
+ if a.startswith('--command='):
353
+ sqls.append(a.split('=', 1)[1])
354
+ elif a.startswith('-c') and len(a) > 2:
355
+ sqls.append(a[2:])
356
+ i += 1
357
+ if not sqls:
358
+ raise Deny('psql_no_sql', "psql 은 -c 'select …' 로만 쓴다(대화형·파일 실행 금지)")
359
+ for s in sqls:
360
+ body = s.strip().rstrip(';').strip()
361
+ if ';' in body or '\\' in body:
362
+ raise Deny('psql_multi', 'psql -c 는 select 한 문장만 된다')
363
+ if not sel.search(body) or wr.search(body):
364
+ raise Deny('psql_write', "psql 은 읽기(select·show·explain)만 된다 — DB 쓰기는 메인 승인 뒤 절차 스크립트로")
365
+ if re.search(r'\bexplain\s+(\(.*\banalyze\b|analyze\b)', body, re.I):
366
+ raise Deny('psql_write', 'explain analyze 는 실제로 실행되므로 쓸 수 없다')
367
+
368
+
369
+ def _check_segment(seg, ops, ctx, depth):
370
+ seg = _strip_redirects(seg)
371
+ if not seg:
372
+ raise Deny('syntax')
373
+ if re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', seg[0]):
374
+ raise Deny('env_assign', '환경 변수 앞붙임은 쓸 수 없다')
375
+ head = seg[0]
376
+ # 절차 스크립트: bash scripts/ops/x.sh … | scripts/ops/x.sh …
377
+ script_re = re.compile(ops.get('script_re') or r'^(?:\./)?(?:.*/)?scripts/ops/([a-z0-9][a-z0-9-]*\.sh)$')
378
+ sp = seg[1] if head in ('bash', 'sh') and len(seg) > 1 else head
379
+ m = script_re.match(sp)
380
+ if m and (head not in ('bash', 'sh') or len(seg) > 1):
381
+ if depth > 0:
382
+ raise Deny('script_remote', 'scripts/ops 는 ssh 안이 아니라 로컬에서 실행한다(스크립트가 ssh 를 한다)')
383
+ if '..' in sp.split('/'):
384
+ raise Deny('path_traversal')
385
+ name = m.group(1)
386
+ if any(fnmatch.fnmatch(name, p) for p in ops.get('read_only_scripts') or []):
387
+ return
388
+ ctx['procedure'] = name
389
+ if name in ctx['approved']():
390
+ return
391
+ raise Deny('script_not_approved',
392
+ '절차 스크립트 %s 는 승인 파일이 있어야 한다 — 메인에게 %s/<card_id>.json {"scripts":["%s"]} 작성을 요청하라'
393
+ % (name, ops.get('approval_dir') or 'ops-approvals', name))
394
+ pat = _match_cmd(seg, ops)
395
+ if not pat:
396
+ raise Deny('not_allowlisted', '허용목록 밖 명령: %s' % ' '.join(seg[:2])[:40])
397
+ key = ' '.join(pat)
398
+ args = seg[len(pat):]
399
+ if key == 'curl':
400
+ args = _curl_args(args)
401
+ flags = _flags(args)
402
+ banned = (ops.get('deny_flags') or {}).get(key) or []
403
+ for f in flags:
404
+ b = _flag_hit(f, banned)
405
+ if b:
406
+ raise Deny('flag_denied', '%s 에서 %s 금지(대기·폴링은 scripts/ops/wait-*.sh)' % (key, b))
407
+ req = (ops.get('require_flags') or {}).get(key)
408
+ if req and not any(f in req or (len(f) > 2 and not f.startswith('--') and any(
409
+ len(r) == 2 and r[1] in f[1:] for r in req)) for f in flags):
410
+ raise Deny('flag_required', '%s 는 %s 가 필요하다' % (key, '/'.join(req)))
411
+ if key == 'ssh':
412
+ if depth > 0:
413
+ raise Deny('ssh_nested')
414
+ if not args or args[0].startswith('-'):
415
+ raise Deny('ssh_option', 'ssh 는 옵션 없이 `ssh <별칭> "<명령>"` 만 된다(-i 키 경로·-o 금지)')
416
+ host = args[0]
417
+ if not re.match(ops.get('ssh_alias_re') or r'^[A-Za-z][A-Za-z0-9_-]*$', host):
418
+ raise Deny('ssh_alias', 'SSH 호스트는 별칭만 쓴다(IP·user@·도메인 금지)')
419
+ inner = ' '.join(args[1:]).strip()
420
+ if not inner:
421
+ raise Deny('ssh_interactive', 'ssh 는 실행할 명령을 함께 줘야 한다')
422
+ check_command(inner, ops, ctx, depth + 1)
423
+ return
424
+ if key == 'docker exec':
425
+ _check_docker_exec(args, ops, ctx, depth)
426
+ return
427
+ if key == 'docker inspect':
428
+ fmts = []
429
+ for i, a in enumerate(args):
430
+ if a in ('-f', '--format') and i + 1 < len(args):
431
+ fmts.append(args[i + 1])
432
+ elif a.startswith('--format='):
433
+ fmts.append(a.split('=', 1)[1])
434
+ envre = re.compile(ops.get('inspect_format_deny_re') or 'env', re.I)
435
+ if not fmts or any(envre.search(x) for x in fmts):
436
+ raise Deny('inspect_env', "docker inspect 는 --format '{{…}}' 로 필요한 칸만(Env 금지)")
437
+ if key == 'curl':
438
+ _check_curl(args, ops)
439
+ if key == 'psql':
440
+ _check_psql(args, ops)
441
+ if key == 'cd':
442
+ if len(args) > 1:
443
+ raise Deny('syntax')
444
+ return
445
+ if key in (ops.get('stdin_only') or []) and [a for a in args if not a.startswith('-')]:
446
+ raise Deny('stdin_only', '%s 는 파이프 필터로만 쓴다(파일 인자 금지)' % key)
447
+ if key == 'jq' and any(re.search(ops.get('jq_deny_re') or r'\benv\b', a) for a in args):
448
+ raise Deny('jq_env', 'jq 로 환경 변수를 볼 수 없다')
449
+ if head in PATH_READERS:
450
+ _check_paths(args, ops, head)
451
+
452
+
453
+ def _check_docker_exec(args, ops, ctx, depth):
454
+ i = 0
455
+ while i < len(args) and args[i].startswith('-'):
456
+ a = args[i]
457
+ if a in ('-i', '-t', '-it', '-ti'):
458
+ i += 1
459
+ elif a in ('-u', '--user', '-w', '--workdir'):
460
+ i += 2
461
+ else:
462
+ raise Deny('docker_exec_option', 'docker exec 옵션은 -i -t -u -w 만 된다')
463
+ if i + 1 >= len(args):
464
+ raise Deny('docker_exec_cmd')
465
+ inner = args[i + 1:]
466
+ if inner[0] in ('docker', 'ssh', 'bash', 'sh'):
467
+ raise Deny('docker_exec_cmd', 'docker exec 안쪽은 읽기 명령(psql -c select 등)만 된다')
468
+ _check_segment(inner, ops, ctx, depth + 1)
469
+
470
+
471
+ def check_command(cmd, ops=None, ctx=None, depth=0):
472
+ """허용이면 None, 아니면 Deny 를 올린다."""
473
+ ops = ops or load_ops()
474
+ ctx = ctx if ctx is not None else {'approved': lambda: set()}
475
+ if depth > 2:
476
+ raise Deny('too_deep')
477
+ segs = _segments(_tokens(_scan(cmd)))
478
+ if not segs:
479
+ raise Deny('syntax')
480
+ for s in segs:
481
+ _check_segment(s, ops, ctx, depth)
482
+ return None
483
+
484
+
485
+ # ── 원장 ──
486
+
487
+ def mask_head(cmd, n=80):
488
+ s = cmd if isinstance(cmd, str) else ''
489
+ try:
490
+ import secret_filter as sf
491
+ s = sf.redact(s)[0]
492
+ except Exception:
493
+ pass
494
+ s = re.sub(r'[A-Za-z0-9_\-+/=]{32,}', '***', s)
495
+ return s.replace('\n', ' ')[:n]
496
+
497
+
498
+ def record_blocked(inp, cmd, rule, ids, ops, p=None, now=None):
499
+ if not rl or rl.disabled():
500
+ return None
501
+ row = {
502
+ 'ev': 'blocked_cmd',
503
+ 'ts': rl._now_iso(now),
504
+ 'session_id': inp.get('session_id') or '',
505
+ 'agent_id': str(inp.get('agent_id') or ''),
506
+ 'agent_type': agent_type_of(inp) or '',
507
+ 'card_id': ids[0] if ids else None,
508
+ 'cmd_head': mask_head(cmd),
509
+ 'rule': rule,
510
+ 'ops_version': ops.get('version', 1),
511
+ }
512
+ return row if rl.append(row, p) else None
513
+
514
+
515
+ REASON_TAIL = ('읽기 전용: docker ps|logs|inspect --format|stats --no-stream, curl -s(GET), tail/head/df/free/uptime, '
516
+ "systemctl status, journalctl, ls, cat(로그), psql -c 'select …', ssh <별칭> \"<같은 목록>\". "
517
+ '대기는 scripts/ops/wait-*.sh, 쓰기·재기동은 메인 승인 파일이 있는 scripts/ops/<이름>.sh 만.')
518
+
519
+
520
+ def check_hook(inp, cmd, rules=None, p=None, now=None):
521
+ """pre-bash-guard 진입점. None = 이 가드는 관여하지 않음(허용). (rule, reason) = 차단."""
522
+ try:
523
+ ops = load_ops(rules)
524
+ if not is_ops_agent(inp, ops):
525
+ return None
526
+ except Exception:
527
+ return None # 판별 실패 = 관여하지 않음(fail-open)
528
+ ids = []
529
+ try:
530
+ ids = card_ids(inp)
531
+ cache = {}
532
+
533
+ def approved():
534
+ if 'v' not in cache:
535
+ cache['v'] = approved_scripts(ids, ops, now)
536
+ return cache['v']
537
+ check_command(cmd, ops, {'approved': approved})
538
+ return None
539
+ except Deny as d:
540
+ rule, detail = d.rule, d.detail
541
+ except Exception as e: # ops-lite 판정 중 오류 = 차단(fail-closed)
542
+ rule, detail = 'internal_error', type(e).__name__
543
+ try:
544
+ record_blocked(inp, cmd, rule, ids, ops, p, now)
545
+ except Exception:
546
+ pass
547
+ reason = '[RoutineCode ops-lite] 허용목록 밖 명령 차단 (rule=%s%s). %s' % (
548
+ rule, (': ' + detail) if detail else '', REASON_TAIL)
549
+ return rule, reason
@@ -0,0 +1,8 @@
1
+ {
2
+ "_note": "모델 가족별 1M 토큰당 단가 [input, output, cache_read, cache_write]. 단가 표는 이 파일 한 곳 — scripts/route-metrics.py 와 bin/rc-savings.js 가 읽는다. 5.5 세대 공시가(2026-11-16 확인), opus 캐시 쓰기는 공시 없음 → 입력×1.25.",
3
+ "per_1m": {
4
+ "opus": [4, 20, 0.2, 5.0],
5
+ "sonnet": [2, 10, 0.1, 2.5],
6
+ "haiku": [0.1, 0.5, 0.01, 0.125]
7
+ }
8
+ }