@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
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
{
|
|
13
13
|
"id": "hooks.output_contract",
|
|
14
14
|
"keywords": ["systemmessage", "permissiondecision", "decision block", "hook output", "continue:false", "continue false", "hookspecificoutput", "additionalcontext", "suppressoutput", "updatedinput"],
|
|
15
|
-
"affects": ["hooks/session-start.sh", "hooks/pre-credit-guard.sh", "hooks/pre-edit-check.sh", "hooks/pre-agent-spawn.sh", "hooks/pre-webfetch-guard.sh", "hooks/pre-secret-guard.sh", "hooks/pre-edit-config-gate.sh", "hooks/pre-agent-briefing.sh", "hooks/post-edit-track.sh", "hooks/post-read-config-context.sh", "hooks/post-config-context.sh", "hooks/user-prompt-submit.sh", "hooks/stop-claim-check.v3.sh"],
|
|
15
|
+
"affects": ["hooks/session-start.sh", "hooks/pre-credit-guard.sh", "hooks/pre-edit-check.sh", "hooks/pre-agent-spawn.sh", "hooks/pre-webfetch-guard.sh", "hooks/pre-secret-guard.sh", "hooks/pre-edit-config-gate.sh", "hooks/pre-agent-briefing.sh", "hooks/pre-edit-delegate.sh", "hooks/post-edit-track.sh", "hooks/post-read-config-context.sh", "hooks/post-config-context.sh", "hooks/user-prompt-submit.sh", "hooks/stop-claim-check.v3.sh"],
|
|
16
16
|
"severity_default": "breaking",
|
|
17
17
|
"probe": "hook_output_accepted"
|
|
18
18
|
},
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""zsh 따옴표 없는 글롭 교정 (PreToolUse(Bash) 훅용, 표준 라이브러리만, Python 3.9 호환).
|
|
3
|
+
|
|
4
|
+
fix_command(cmd) -> (fixed_cmd, notes) 또는 None.
|
|
5
|
+
- 교정 대상(따옴표 밖 단어만):
|
|
6
|
+
(a) --include= / --exclude= / --exclude-dir= 값에 * ? [ 가 있으면 값을 작은따옴표로 감싼다.
|
|
7
|
+
값에 쉼표로 나눈 단순 중괄호 목록({a,b})이 있으면 --opt='..a..' --opt='..b..' 로 펼친다.
|
|
8
|
+
(b) find 명령의 -name / -iname / -path / -ipath 바로 다음 단어에 * ? [ 가 있으면 작은따옴표로 감싼다.
|
|
9
|
+
- 건드리지 않음: 따옴표·역슬래시가 든 단어, $( 또는 백틱이 든 단어, 작은따옴표가 든 값.
|
|
10
|
+
- heredoc(<<) 이 있는 명령 전체, 지원하지 않는 중괄호(중첩·범위)가 있으면 None.
|
|
11
|
+
- 실패·예외 = None (호출 측은 None 이면 아무것도 하지 않는다).
|
|
12
|
+
- 이 모듈은 권한을 결정하지 않는다. 교정 명령을 알려 주는 것은 훅이 한다(allow/ask/updatedInput 금지).
|
|
13
|
+
"""
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
_OPS = set('|&;()<>\n')
|
|
17
|
+
_WS = set(' \t\r')
|
|
18
|
+
_LONG_RE = re.compile(r'^(--(?:include|exclude-dir|exclude))=(.*)$', re.S)
|
|
19
|
+
_GLOB_CHARS = ('*', '?', '[')
|
|
20
|
+
_FIND_NAME_OPTS = ('-name', '-iname', '-path', '-ipath')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _Unsupported(Exception):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _has_glob(s):
|
|
28
|
+
return any(ch in s for ch in _GLOB_CHARS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _scan(cmd):
|
|
32
|
+
"""따옴표·이스케이프를 존중하며 단어(word)와 연산자(op)의 원문 구간을 돌려준다.
|
|
33
|
+
|
|
34
|
+
반환: [('w', start, end, quoted, unsafe) | ('op', start, end, False, False)]
|
|
35
|
+
"""
|
|
36
|
+
items = []
|
|
37
|
+
i, n = 0, len(cmd)
|
|
38
|
+
while i < n:
|
|
39
|
+
c = cmd[i]
|
|
40
|
+
if c in _WS:
|
|
41
|
+
i += 1
|
|
42
|
+
continue
|
|
43
|
+
if c in _OPS:
|
|
44
|
+
j = i
|
|
45
|
+
while j < n and cmd[j] in _OPS:
|
|
46
|
+
j += 1
|
|
47
|
+
items.append(('op', i, j, False, False))
|
|
48
|
+
i = j
|
|
49
|
+
continue
|
|
50
|
+
start = i
|
|
51
|
+
quoted = False
|
|
52
|
+
unsafe = False
|
|
53
|
+
while i < n:
|
|
54
|
+
c = cmd[i]
|
|
55
|
+
if c in _WS or c in _OPS:
|
|
56
|
+
break
|
|
57
|
+
if c == '\\':
|
|
58
|
+
quoted = True
|
|
59
|
+
i += 2
|
|
60
|
+
continue
|
|
61
|
+
if c == "'":
|
|
62
|
+
quoted = True
|
|
63
|
+
j = cmd.find("'", i + 1)
|
|
64
|
+
if j < 0:
|
|
65
|
+
raise _Unsupported('unterminated single quote')
|
|
66
|
+
i = j + 1
|
|
67
|
+
continue
|
|
68
|
+
if c == '"':
|
|
69
|
+
quoted = True
|
|
70
|
+
i += 1
|
|
71
|
+
while i < n and cmd[i] != '"':
|
|
72
|
+
i += 2 if cmd[i] == '\\' else 1
|
|
73
|
+
if i >= n:
|
|
74
|
+
raise _Unsupported('unterminated double quote')
|
|
75
|
+
i += 1
|
|
76
|
+
continue
|
|
77
|
+
if c == '`':
|
|
78
|
+
unsafe = True
|
|
79
|
+
j = cmd.find('`', i + 1)
|
|
80
|
+
if j < 0:
|
|
81
|
+
raise _Unsupported('unterminated backtick')
|
|
82
|
+
i = j + 1
|
|
83
|
+
continue
|
|
84
|
+
if c == '$' and i + 1 < n and cmd[i + 1] == '(':
|
|
85
|
+
unsafe = True
|
|
86
|
+
depth = 0
|
|
87
|
+
j = i + 1
|
|
88
|
+
while j < n:
|
|
89
|
+
if cmd[j] == '(':
|
|
90
|
+
depth += 1
|
|
91
|
+
elif cmd[j] == ')':
|
|
92
|
+
depth -= 1
|
|
93
|
+
if depth == 0:
|
|
94
|
+
break
|
|
95
|
+
j += 1
|
|
96
|
+
if j >= n:
|
|
97
|
+
raise _Unsupported('unterminated $(')
|
|
98
|
+
i = j + 1
|
|
99
|
+
continue
|
|
100
|
+
i += 1
|
|
101
|
+
items.append(('w', start, min(i, n), quoted, unsafe))
|
|
102
|
+
return items
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _brace_split(value):
|
|
106
|
+
"""값의 중괄호 목록을 (앞, [항목...], 뒤) 로 나눈다. 목록이 없으면 None.
|
|
107
|
+
|
|
108
|
+
중괄호가 없거나 쉼표가 없는 {x} 는 zsh 가 그대로 두므로 None(펼치지 않음).
|
|
109
|
+
중첩·범위({1..3})·빈 항목은 지원하지 않으므로 _Unsupported.
|
|
110
|
+
"""
|
|
111
|
+
if '{' not in value and '}' not in value:
|
|
112
|
+
return None
|
|
113
|
+
if value.count('{') != 1 or value.count('}') != 1:
|
|
114
|
+
raise _Unsupported('nested or unbalanced braces')
|
|
115
|
+
a = value.index('{')
|
|
116
|
+
b = value.index('}')
|
|
117
|
+
if b < a:
|
|
118
|
+
raise _Unsupported('unbalanced braces')
|
|
119
|
+
group = value[a + 1:b]
|
|
120
|
+
if ',' not in group:
|
|
121
|
+
if '..' in group:
|
|
122
|
+
raise _Unsupported('brace sequence')
|
|
123
|
+
return None
|
|
124
|
+
parts = group.split(',')
|
|
125
|
+
if any(p == '' for p in parts):
|
|
126
|
+
raise _Unsupported('empty brace item')
|
|
127
|
+
return value[:a], parts, value[b + 1:]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _quote_long(prefix, value):
|
|
131
|
+
"""--opt=VALUE 를 교정 문자열로. 쉼표 목록 중괄호는 옵션을 반복해 펼친다."""
|
|
132
|
+
split = _brace_split(value)
|
|
133
|
+
if split is None:
|
|
134
|
+
return prefix + "'" + value + "'"
|
|
135
|
+
pre, parts, post = split
|
|
136
|
+
pieces = [pre + p + post for p in parts]
|
|
137
|
+
return ' '.join(prefix + "'" + p + "'" for p in pieces)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _fix(cmd):
|
|
141
|
+
if '<<' in cmd:
|
|
142
|
+
return None
|
|
143
|
+
items = _scan(cmd)
|
|
144
|
+
segs = [[]]
|
|
145
|
+
for it in items:
|
|
146
|
+
if it[0] == 'op':
|
|
147
|
+
segs.append([])
|
|
148
|
+
else:
|
|
149
|
+
segs[-1].append(it)
|
|
150
|
+
|
|
151
|
+
edits = [] # (start, end, replacement, note)
|
|
152
|
+
for seg in segs:
|
|
153
|
+
if not seg:
|
|
154
|
+
continue
|
|
155
|
+
first_raw = None
|
|
156
|
+
if not seg[0][3] and not seg[0][4]:
|
|
157
|
+
first_raw = _raw(cmd, seg[0])
|
|
158
|
+
is_find = first_raw == 'find'
|
|
159
|
+
for k, it in enumerate(seg):
|
|
160
|
+
raw = _raw(cmd, it)
|
|
161
|
+
if it[3] or it[4]:
|
|
162
|
+
continue
|
|
163
|
+
m = _LONG_RE.match(raw)
|
|
164
|
+
if m and _has_glob(m.group(2)):
|
|
165
|
+
prefix = m.group(1) + '='
|
|
166
|
+
value = m.group(2)
|
|
167
|
+
if "'" in value:
|
|
168
|
+
continue
|
|
169
|
+
fixed = _quote_long(prefix, value)
|
|
170
|
+
edits.append((it[1], it[2], fixed, '%s -> %s' % (raw, fixed)))
|
|
171
|
+
continue
|
|
172
|
+
if is_find and raw in _FIND_NAME_OPTS and k + 1 < len(seg):
|
|
173
|
+
nxt = seg[k + 1]
|
|
174
|
+
nraw = _raw(cmd, nxt)
|
|
175
|
+
if nxt[3] or nxt[4] or "'" in nraw or not _has_glob(nraw):
|
|
176
|
+
continue
|
|
177
|
+
if '{' in nraw or '}' in nraw:
|
|
178
|
+
continue
|
|
179
|
+
fixed = "'" + nraw + "'"
|
|
180
|
+
edits.append((nxt[1], nxt[2], fixed, '%s -> %s' % (nraw, fixed)))
|
|
181
|
+
|
|
182
|
+
if not edits:
|
|
183
|
+
return None
|
|
184
|
+
edits.sort(key=lambda e: e[0], reverse=True)
|
|
185
|
+
out = cmd
|
|
186
|
+
notes = []
|
|
187
|
+
last_start = len(cmd) + 1
|
|
188
|
+
for s, e, rep, note in edits:
|
|
189
|
+
if e > last_start:
|
|
190
|
+
raise _Unsupported('overlapping edits')
|
|
191
|
+
last_start = s
|
|
192
|
+
out = out[:s] + rep + out[e:]
|
|
193
|
+
notes.append(note)
|
|
194
|
+
notes.reverse()
|
|
195
|
+
return out, notes
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _raw(cmd, it):
|
|
199
|
+
return cmd[it[1]:it[2]]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def fix_command(cmd):
|
|
203
|
+
"""따옴표 없는 글롭을 교정한다. (fixed_cmd, notes) 또는 None. 예외를 올리지 않는다."""
|
|
204
|
+
try:
|
|
205
|
+
if not isinstance(cmd, str) or not cmd.strip():
|
|
206
|
+
return None
|
|
207
|
+
return _fix(cmd)
|
|
208
|
+
except Exception:
|
|
209
|
+
return None
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""메인 직접 실행 경고 — 설계 34 §5.4, P4 1단계(경고만, 차단 없음).
|
|
3
|
+
|
|
4
|
+
메인 세션(입력에 agent_id 없음)이
|
|
5
|
+
- 코드 파일을 Edit/Write/MultiEdit 하면 → 파일마다 세션당 1회 경고 (implementor-lite 카드 대상)
|
|
6
|
+
- Bash 로 빌드·테스트를 돌리면(VERIFY, mine.py 와 같은 식) → 세션당 1회 (runner-lite)
|
|
7
|
+
- Bash 로 ssh·scp·rsync·docker 를 쓰면 → 세션당 1회 (ops-lite)
|
|
8
|
+
hookSpecificOutput.additionalContext + systemMessage 로 알리고(permissionDecision 없음 = 다른 훅 판정 그대로),
|
|
9
|
+
원장 route-ledger.jsonl 에 ev=main_nudge 를 남긴다(2주 기준선 — P4 2단계 차단 판단 자료).
|
|
10
|
+
|
|
11
|
+
제외: 문서(route_rules doc_re), .routinecode/ 아래, 스크래치패드·.claude(route_ledger._kept), 서브에이전트.
|
|
12
|
+
끄기: ROUTINECODE_DELEGATE_NUDGE=off. 원장만 끄기: ROUTINECODE_ROUTE_LEDGER_DISABLED=1(경고는 그대로).
|
|
13
|
+
표준 라이브러리만, 예외를 올리지 않는다. 출력은 경고할 때만 JSON 한 줄.
|
|
14
|
+
|
|
15
|
+
CLI: python3 delegate_nudge.py pre-tool (stdin = PreToolUse 입력 JSON)
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
23
|
+
sys.path.insert(0, HERE)
|
|
24
|
+
try:
|
|
25
|
+
import route_ledger as rl
|
|
26
|
+
except Exception: # pragma: no cover — lib 이 깨져도 훅은 조용히 통과
|
|
27
|
+
rl = None
|
|
28
|
+
|
|
29
|
+
EDIT_TOOLS = ('Edit', 'Write', 'MultiEdit')
|
|
30
|
+
# docs2/지능개선/new/data/34/routing/mine.py VERIFY 와 같은 식(측정과 경고가 같은 일을 센다). route_rules.json nudge.verify_re 로 바꿀 수 있다.
|
|
31
|
+
DEFAULT_VERIFY_RE = (r'(npm (run )?(test|build)|pnpm (test|build)|tsc|pytest|jest|vitest|go test|cargo (test|build)'
|
|
32
|
+
r'|node --test|python3? -m pytest|test_|build_check|run_tests)')
|
|
33
|
+
DEFAULT_REMOTE_RE = r'(?:^|[\s;&|(`])(ssh|scp|rsync|docker)(?=\s|$)'
|
|
34
|
+
DEFAULT_DOC_RE = r'\.(md|txt|json|ya?ml|csv)$'
|
|
35
|
+
STATE_MAX = 500
|
|
36
|
+
|
|
37
|
+
MSG_EDIT = ('[RoutineCode] 설계 34: 이 편집은 작업 카드(implementor-lite) 대상입니다 — '
|
|
38
|
+
'예외(직접 요청·1줄·위험 경로)가 아니면 카드로 위임하세요.')
|
|
39
|
+
MSG_RUN = ('[RoutineCode] 설계 34: 빌드·테스트 실행은 작업 카드(runner-lite) 대상입니다 — '
|
|
40
|
+
'예외(직접 요청)가 아니면 카드로 위임하세요. 작업자의 run_tests·build_check 도 증거로 남습니다.')
|
|
41
|
+
MSG_REMOTE = ('[RoutineCode] 설계 34: 서버·배포 확인은 작업 카드(ops-lite, OPS_MODE: read-only) 대상입니다 — '
|
|
42
|
+
'예외(직접 요청)가 아니면 카드로 위임하세요. 쓰기는 승인 파일 뒤 OPS_MODE: procedure.')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def disabled():
|
|
46
|
+
return os.environ.get('ROUTINECODE_DELEGATE_NUDGE', '').lower() in ('off', '0', 'false')
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _rules():
|
|
50
|
+
try:
|
|
51
|
+
return rl.load_rules() if rl else {}
|
|
52
|
+
except Exception:
|
|
53
|
+
return {}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _re(rules, key, default):
|
|
57
|
+
try:
|
|
58
|
+
return re.compile(((rules.get('nudge') or {}).get(key)) or default, re.I)
|
|
59
|
+
except Exception:
|
|
60
|
+
return re.compile(default, re.I)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _tool_input(inp):
|
|
64
|
+
if rl:
|
|
65
|
+
return rl._tool_input(inp)
|
|
66
|
+
ti = inp.get('tool_input')
|
|
67
|
+
return ti if isinstance(ti, dict) else {}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def classify_edit(fp, rules):
|
|
71
|
+
"""경고 대상 코드 파일이면 kind(main_code|risk), 아니면 None."""
|
|
72
|
+
if not isinstance(fp, str) or not fp:
|
|
73
|
+
return None
|
|
74
|
+
if rl and not rl._kept(fp): # /scratchpad/ · /.claude/
|
|
75
|
+
return None
|
|
76
|
+
norm = fp.replace('\\', '/')
|
|
77
|
+
if '/.routinecode/' in norm or norm.startswith('.routinecode/'):
|
|
78
|
+
return None
|
|
79
|
+
try:
|
|
80
|
+
doc = re.compile(rules.get('doc_re') or DEFAULT_DOC_RE, re.I)
|
|
81
|
+
except Exception:
|
|
82
|
+
doc = re.compile(DEFAULT_DOC_RE, re.I)
|
|
83
|
+
if doc.search(norm):
|
|
84
|
+
return None
|
|
85
|
+
return rl.classify([norm], rules) if rl else 'main_code'
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def classify_bash(cmd, rules):
|
|
89
|
+
"""(category, kind, head) — category = run|remote, 아니면 None."""
|
|
90
|
+
if not isinstance(cmd, str) or not cmd.strip():
|
|
91
|
+
return None
|
|
92
|
+
m = _re(rules, 'remote_re', DEFAULT_REMOTE_RE).search(cmd)
|
|
93
|
+
if m:
|
|
94
|
+
return 'remote', 'ops_read', m.group(1).lower()
|
|
95
|
+
m = _re(rules, 'verify_re', DEFAULT_VERIFY_RE).search(cmd)
|
|
96
|
+
if m:
|
|
97
|
+
return 'run', 'run', m.group(0).split()[0][:40]
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def state_path(sid):
|
|
102
|
+
base = os.environ.get('XDG_RUNTIME_DIR') or os.path.expanduser('~/.routinecode/run')
|
|
103
|
+
safe = re.sub(r'[^A-Za-z0-9_-]', '', sid or '')[:64] or 'nosession'
|
|
104
|
+
return os.path.join(base, 'nudge34-%s.json' % safe)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _seen_add(sid, key):
|
|
108
|
+
"""처음 보는 key 면 기록하고 True. 상태 파일이 깨지거나 못 쓰면 True(경고 1회 더는 무해)."""
|
|
109
|
+
p = state_path(sid)
|
|
110
|
+
keys = []
|
|
111
|
+
try:
|
|
112
|
+
with open(p, encoding='utf-8') as f:
|
|
113
|
+
d = json.load(f)
|
|
114
|
+
if isinstance(d, dict) and isinstance(d.get('keys'), list):
|
|
115
|
+
keys = [k for k in d['keys'] if isinstance(k, str)]
|
|
116
|
+
except Exception:
|
|
117
|
+
keys = []
|
|
118
|
+
if key in keys:
|
|
119
|
+
return False
|
|
120
|
+
keys = (keys + [key])[-STATE_MAX:]
|
|
121
|
+
try:
|
|
122
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
123
|
+
tmp = '%s.%d' % (p, os.getpid())
|
|
124
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
125
|
+
json.dump({'keys': keys}, f)
|
|
126
|
+
os.replace(tmp, p)
|
|
127
|
+
except Exception:
|
|
128
|
+
pass
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def pre_tool(inp, now=None):
|
|
133
|
+
"""경고할 때 훅 출력 dict, 아니면 None."""
|
|
134
|
+
if disabled() or not isinstance(inp, dict) or inp.get('agent_id'):
|
|
135
|
+
return None
|
|
136
|
+
tool = inp.get('tool_name') or ''
|
|
137
|
+
ti = _tool_input(inp)
|
|
138
|
+
rules = _rules()
|
|
139
|
+
sid = inp.get('session_id') or ''
|
|
140
|
+
if tool in EDIT_TOOLS:
|
|
141
|
+
fp = ti.get('file_path')
|
|
142
|
+
kind = classify_edit(fp, rules)
|
|
143
|
+
if not kind:
|
|
144
|
+
return None
|
|
145
|
+
key, msg, target, head = 'edit:' + fp, MSG_EDIT, fp, None
|
|
146
|
+
elif tool == 'Bash':
|
|
147
|
+
hit = classify_bash(ti.get('command'), rules)
|
|
148
|
+
if not hit:
|
|
149
|
+
return None
|
|
150
|
+
cat, kind, head = hit
|
|
151
|
+
key, msg, target = 'bash:' + cat, (MSG_REMOTE if cat == 'remote' else MSG_RUN), cat
|
|
152
|
+
else:
|
|
153
|
+
return None
|
|
154
|
+
if not _seen_add(sid, key):
|
|
155
|
+
return None
|
|
156
|
+
if rl and not rl.disabled():
|
|
157
|
+
row = {'ev': 'main_nudge', 'session_id': sid, 'ts': rl._now_iso(now), 'tool': tool, 'target': target,
|
|
158
|
+
'kind': kind, 'arm': 'main', 'phase': 'warn', 'rules_version': rules.get('rules_version', 1)}
|
|
159
|
+
if head:
|
|
160
|
+
row['cmd_head'] = head # 명령 전체는 남기지 않는다(비밀값)
|
|
161
|
+
rl.append(row)
|
|
162
|
+
return {'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'additionalContext': msg}, 'systemMessage': msg}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _main(argv):
|
|
166
|
+
if len(argv) < 2 or argv[1] != 'pre-tool' or disabled():
|
|
167
|
+
return 0
|
|
168
|
+
try:
|
|
169
|
+
inp = json.load(sys.stdin)
|
|
170
|
+
out = pre_tool(inp)
|
|
171
|
+
if out:
|
|
172
|
+
sys.stdout.write(json.dumps(out, ensure_ascii=False))
|
|
173
|
+
except Exception:
|
|
174
|
+
pass
|
|
175
|
+
return 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
if __name__ == '__main__':
|
|
179
|
+
sys.exit(_main(sys.argv))
|