@routinecrew/routinecode 2.31.90 → 2.31.92
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/prompt-vault.dat +1 -1
- package/bin/rc-credit-turn.js +1 -1
- package/bin/rc-grant.js +1 -1
- package/bin/rc-team.js +1 -1
- package/hooks/lib/codemode_guard.py +103 -1
- package/hooks/lib/copy_guard.py +330 -0
- package/hooks/lib/knowledge_items.py +158 -2
- package/hooks/lib/knowledge_scope.py +184 -4
- package/hooks/lib/repo_pollution.py +173 -0
- package/hooks/lib/skill_drafts.py +1 -1
- package/hooks/lib/work_kind.py +48 -5
- package/hooks/lib/work_kind_events.py +20 -17
- package/hooks/pre-agent-spawn.mjs +1 -1
- package/hooks/pre-bash-guard.sh +11 -0
- package/hooks/session-start.sh +8 -0
- package/mcp-dev-tester/dist/attestation.js +1 -1
- package/mcp-doc-fetcher/dist/index.js +1 -1
- package/mcp-intelligence/dist/concept-catalog.js +1 -1
- package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
- package/mcp-intelligence/dist/config-auth.js +1 -1
- package/mcp-intelligence/dist/contracts.generated.js +1 -1
- package/mcp-intelligence/dist/grounding.js +1 -1
- package/mcp-intelligence/dist/knowledge-critic.js +1 -1
- package/mcp-intelligence/dist/knowledge-guide.js +1 -1
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-migrate.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-intelligence/dist/knowledge-scope.js +1 -1
- package/mcp-intelligence/dist/provenance.js +1 -1
- package/mcp-intelligence/dist/semantic-embedder.js +1 -1
- package/mcp-log-watcher/dist/config-auth.js +1 -1
- package/mcp-log-watcher/dist/index.js +1 -1
- package/mcp-log-watcher/dist/known-solutions.js +1 -1
- package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-plan-manager/dist/index.js +1 -1
- package/mcp-project-context/dist/index.js +1 -1
- package/mcp-routinecode/dist/agent-tracker.js +1 -1
- package/mcp-routinecode/dist/attestation.js +1 -1
- package/mcp-routinecode/dist/blast-radius.js +1 -1
- package/mcp-routinecode/dist/board.js +1 -1
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/audit.js +1 -1
- package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/store.js +1 -1
- package/mcp-routinecode/dist/contracts.generated.js +1 -1
- package/mcp-routinecode/dist/design-judge.js +1 -1
- 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/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.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/test-runner.js +1 -1
- package/mcp-routinecode/dist/thinking-judge.js +1 -1
- package/mcp-routinecode/dist/verification.js +1 -1
- package/mcp-routinecode/dist/viral-loop.js +1 -1
- package/package.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 -1
- package/plugin/agents/implementor.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- package/plugin/agents/ops-lite.md.sealed +1 -1
- 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 -1
- 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,330 @@
|
|
|
1
|
+
"""복사 명령 선제 판정 — 2026-11-22 13:48 '워크스페이스 통째 복사' 사고 재발 방지.
|
|
2
|
+
|
|
3
|
+
사고: zsh 에서 'set -- $x'(무따옴표) 가 단어 분할되지 않아 $2="" → 원본이 워크스페이스 루트가 됐고,
|
|
4
|
+
dep.sh(bash) 안 무따옴표 대상 $D/ 가 분할돼 rsync 대상이 상대경로(저장소 하위)가 되어
|
|
5
|
+
워크스페이스 전체(28GB, 비밀 포함)가 세 저장소 안으로 복사됐다.
|
|
6
|
+
|
|
7
|
+
규칙 판정
|
|
8
|
+
copy_ancestor rsync / cp -R|-r|-a / ditto 의 원본이 대상의 조상이거나 같은 경로 (cwd·cd·리터럴 변수 해석)
|
|
9
|
+
(워크스페이스 루트형 = 여러 저장소를 자식으로 가진 폴더도 조상 판정에 포함된다)
|
|
10
|
+
unquoted_copy_dest rsync/cp/ditto 의 마지막 인자(대상)가 따옴표 없는 변수 전개 — 본문과 heredoc 스크립트 본문 모두
|
|
11
|
+
zsh_split zsh 에서 'set -- $x' / 'set $x' (무따옴표 단일 변수로 위치인자 분할 기대)
|
|
12
|
+
|
|
13
|
+
어떤 예외도 호출자에서 통과 처리한다(가드 버그가 일반 Bash 를 막으면 안 된다). 파일시스템은 realpath 외에 보지 않는다.
|
|
14
|
+
"""
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import rm_guard as _rg
|
|
20
|
+
_HEREDOC_ANY = _rg._HEREDOC_ANY
|
|
21
|
+
except Exception: # pragma: no cover
|
|
22
|
+
_HEREDOC_ANY = re.compile(r'(?<!<)<<-?[ \t]*(?:(["\'])(?P<q>[^"\'\n]+)\1|\\(?P<e>\w+)|(?P<n>[A-Za-z_]\w*))[^\n]*\n')
|
|
23
|
+
|
|
24
|
+
REASONS = {
|
|
25
|
+
'copy_ancestor': '복사 원본({s})이 대상({d})의 상위 폴더이거나 같은 경로라 자기 안으로 복사됩니다(워크스페이스 통째 복사 사고 형태). '
|
|
26
|
+
'원본과 대상을 다시 확인하고, 대상은 원본 밖(scratchpad 등) 절대경로로 쓰세요.\n'
|
|
27
|
+
'예: rsync -a "$SRC"/ "/private/tmp/claude-501/<세션>/scratchpad/out"/',
|
|
28
|
+
'unquoted_copy_dest': '복사 대상({d})이 따옴표 없는 변수 전개입니다. 값에 공백이 있거나 비어 있으면 단어가 분할돼 엉뚱한 경로로 복사됩니다. '
|
|
29
|
+
'변수는 항상 따옴표로 감싸세요.\n'
|
|
30
|
+
'예: rsync -a "$SRC"/ "$D"/',
|
|
31
|
+
'zsh_split': "zsh 는 따옴표 없는 변수({t})를 단어 분할하지 않아 'set --' 로 위치인자를 나눌 수 없습니다(bash 와 다름). "
|
|
32
|
+
'배열이나 ${{=x}} 를 쓰세요.\n'
|
|
33
|
+
'예: A=(promi promi/promi-backend); for x in "${{A[@]}}"; do ...; done (또는 set -- ${{=x}})',
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def deny_reason(key, **kw):
|
|
38
|
+
return '[RoutineCode] ' + key + ': ' + REASONS[key].format(**kw) + ' (사용자에게 묻지 말고 바로 다시 실행)'
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _Tok:
|
|
42
|
+
__slots__ = ('raw', 'val', 'unq', 'op')
|
|
43
|
+
|
|
44
|
+
def __init__(self, raw='', val='', unq='', op=False):
|
|
45
|
+
self.raw, self.val, self.unq, self.op = raw, val, unq, op
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _tokenize(t):
|
|
49
|
+
"""따옴표·치환을 따라가며 단어(raw/val/unq)와 연산자(; & | 개행 ( ) { })로 나눈다. unq = 따옴표 밖 글자만."""
|
|
50
|
+
out, i, n = [], 0, len(t)
|
|
51
|
+
raw = val = unq = ''
|
|
52
|
+
inword = False
|
|
53
|
+
|
|
54
|
+
def flush():
|
|
55
|
+
nonlocal raw, val, unq, inword
|
|
56
|
+
if inword:
|
|
57
|
+
out.append(_Tok(raw, val, unq))
|
|
58
|
+
raw = val = unq = ''
|
|
59
|
+
inword = False
|
|
60
|
+
|
|
61
|
+
while i < n:
|
|
62
|
+
ch = t[i]
|
|
63
|
+
if ch == '\\' and i + 1 < n and t[i + 1] == '\n':
|
|
64
|
+
i += 2
|
|
65
|
+
continue
|
|
66
|
+
if not inword and ch in ' \t':
|
|
67
|
+
i += 1
|
|
68
|
+
continue
|
|
69
|
+
if inword and ch in ' \t':
|
|
70
|
+
flush()
|
|
71
|
+
i += 1
|
|
72
|
+
continue
|
|
73
|
+
if ch == '#' and not inword:
|
|
74
|
+
j = t.find('\n', i)
|
|
75
|
+
i = n if j < 0 else j
|
|
76
|
+
continue
|
|
77
|
+
if ch in ';\n|':
|
|
78
|
+
flush()
|
|
79
|
+
out.append(_Tok(ch, op=True))
|
|
80
|
+
i += 1
|
|
81
|
+
continue
|
|
82
|
+
if ch == '&':
|
|
83
|
+
if (raw and raw[-1] in '<>') or (i + 1 < n and t[i + 1] == '>'):
|
|
84
|
+
raw += ch; val += ch; unq += ch; inword = True
|
|
85
|
+
else:
|
|
86
|
+
flush()
|
|
87
|
+
out.append(_Tok('&', op=True))
|
|
88
|
+
i += 1
|
|
89
|
+
continue
|
|
90
|
+
if ch in '(){}' and not (ch == '(' and raw.endswith('$')):
|
|
91
|
+
if ch in '{}' and (inword or not (i + 1 >= n or t[i + 1] in ' \t\n;')):
|
|
92
|
+
raw += ch; val += ch; unq += ch; inword = True
|
|
93
|
+
i += 1
|
|
94
|
+
continue
|
|
95
|
+
flush()
|
|
96
|
+
out.append(_Tok(ch, op=True))
|
|
97
|
+
i += 1
|
|
98
|
+
continue
|
|
99
|
+
inword = True
|
|
100
|
+
if ch == "'":
|
|
101
|
+
j = t.find("'", i + 1)
|
|
102
|
+
j = n if j < 0 else j
|
|
103
|
+
raw += t[i:j + 1]; val += t[i + 1:j]
|
|
104
|
+
i = j + 1
|
|
105
|
+
elif ch == '"':
|
|
106
|
+
j, buf = i + 1, ''
|
|
107
|
+
while j < n and t[j] != '"':
|
|
108
|
+
if t[j] == '\\' and j + 1 < n and t[j + 1] in '"\\$`':
|
|
109
|
+
buf += t[j + 1]; j += 2
|
|
110
|
+
else:
|
|
111
|
+
buf += t[j]; j += 1
|
|
112
|
+
raw += t[i:j + 1]; val += buf
|
|
113
|
+
i = j + 1
|
|
114
|
+
elif ch == '\\' and i + 1 < n:
|
|
115
|
+
raw += t[i:i + 2]; val += t[i + 1]
|
|
116
|
+
i += 2
|
|
117
|
+
elif ch == '$' and i + 1 < n and t[i + 1] in '({':
|
|
118
|
+
op_, cl = ('(', ')') if t[i + 1] == '(' else ('{', '}')
|
|
119
|
+
j, d = i + 1, 0
|
|
120
|
+
while j < n:
|
|
121
|
+
if t[j] == op_:
|
|
122
|
+
d += 1
|
|
123
|
+
elif t[j] == cl:
|
|
124
|
+
d -= 1
|
|
125
|
+
if d == 0:
|
|
126
|
+
break
|
|
127
|
+
j += 1
|
|
128
|
+
seg = t[i:j + 1]
|
|
129
|
+
raw += seg; val += seg; unq += seg
|
|
130
|
+
i = j + 1
|
|
131
|
+
else:
|
|
132
|
+
raw += ch; val += ch; unq += ch
|
|
133
|
+
i += 1
|
|
134
|
+
flush()
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _segments(toks):
|
|
139
|
+
seg = []
|
|
140
|
+
for tk in toks:
|
|
141
|
+
if tk.op:
|
|
142
|
+
if seg:
|
|
143
|
+
yield seg
|
|
144
|
+
seg = []
|
|
145
|
+
else:
|
|
146
|
+
seg.append(tk)
|
|
147
|
+
if seg:
|
|
148
|
+
yield seg
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_REDIR = re.compile(r'^(?:\d*[<>]|&>)')
|
|
152
|
+
_REDIR_BARE = re.compile(r'^(?:\d*(?:>>?|<<?<?|>&|<&)|&>>?)$')
|
|
153
|
+
_PREFIX = {'do', 'then', 'else', 'elif', 'if', 'while', 'until', '!', 'sudo', 'command', 'builtin', 'nohup', 'time', 'env', 'exec', 'nice'}
|
|
154
|
+
_ASSIGN = re.compile(r'^([A-Za-z_]\w*)=')
|
|
155
|
+
_PLAIN_VAR = re.compile(r'^\$(?:\{[A-Za-z_]\w*\}|[A-Za-z_]\w*|\d)$')
|
|
156
|
+
_VAR_IN = re.compile(r'\$[({A-Za-z_0-9]|`')
|
|
157
|
+
_REMOTE = re.compile(r'^(?:rsync://|[A-Za-z0-9_.@-]+:)')
|
|
158
|
+
|
|
159
|
+
_RSYNC_VAL = {'-e', '--rsh', '--exclude', '--include', '--exclude-from', '--include-from', '--filter', '-f', '--files-from',
|
|
160
|
+
'--port', '--log-file', '--chmod', '--backup-dir', '--suffix', '-T', '--temp-dir', '--partial-dir',
|
|
161
|
+
'--compare-dest', '--copy-dest', '--link-dest', '--max-size', '--min-size', '--bwlimit', '--timeout',
|
|
162
|
+
'--contimeout', '--rsync-path', '--usermap', '--groupmap', '--chown', '--info', '--debug'}
|
|
163
|
+
_CP_VAL = {'-t', '--target-directory', '-S', '--suffix'}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _subst(s, env):
|
|
167
|
+
for _ in range(3):
|
|
168
|
+
s2 = re.sub(r'\$\{([A-Za-z_]\w*)\}|\$([A-Za-z_]\w*)',
|
|
169
|
+
lambda m: env.get(m.group(1) or m.group(2), m.group(0)), s)
|
|
170
|
+
if s2 == s:
|
|
171
|
+
break
|
|
172
|
+
s = s2
|
|
173
|
+
return s
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _resolve(tok, cwd, env):
|
|
177
|
+
"""리터럴로 정해지는 로컬 경로만 돌려준다. 변수·글롭·원격(host:path)·상대경로+cwd 불명 → None."""
|
|
178
|
+
v = _subst(tok.val, env)
|
|
179
|
+
if not v or _VAR_IN.search(v) or re.search(r'[*?\[]', v):
|
|
180
|
+
return None
|
|
181
|
+
if _REMOTE.match(v) and not v.startswith(('/', '.', '~')):
|
|
182
|
+
return None
|
|
183
|
+
if v.startswith('~'):
|
|
184
|
+
v = os.path.expanduser(v)
|
|
185
|
+
if not os.path.isabs(v):
|
|
186
|
+
if not cwd:
|
|
187
|
+
return None
|
|
188
|
+
v = os.path.join(cwd, v)
|
|
189
|
+
return os.path.normpath(v)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _is_inside(src, dst):
|
|
193
|
+
for s in {src, os.path.realpath(src)}:
|
|
194
|
+
for d in {dst, os.path.realpath(dst)}:
|
|
195
|
+
sb = s.rstrip('/')
|
|
196
|
+
if d.rstrip('/') == sb or d.startswith(sb + '/'):
|
|
197
|
+
return s
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _parse_copy(cmd, args):
|
|
202
|
+
"""(operands, target_dir_token|None, recursive)"""
|
|
203
|
+
ops, target, rec, i = [], None, cmd in ('rsync', 'ditto'), 0
|
|
204
|
+
valopts = _RSYNC_VAL if cmd == 'rsync' else _CP_VAL if cmd == 'cp' else set()
|
|
205
|
+
endopt = False
|
|
206
|
+
while i < len(args):
|
|
207
|
+
a = args[i]
|
|
208
|
+
if not endopt and a.raw == '--':
|
|
209
|
+
endopt = True
|
|
210
|
+
elif not endopt and a.raw.startswith('-') and len(a.raw) > 1:
|
|
211
|
+
name = a.raw.split('=')[0]
|
|
212
|
+
if cmd == 'cp':
|
|
213
|
+
if name in ('--recursive', '--archive') or (not a.raw.startswith('--') and re.search(r'[rRa]', a.raw[1:])):
|
|
214
|
+
rec = True
|
|
215
|
+
if name in valopts and '=' not in a.raw and i + 1 < len(args):
|
|
216
|
+
if name in ('-t', '--target-directory'):
|
|
217
|
+
target = args[i + 1]
|
|
218
|
+
i += 1
|
|
219
|
+
elif name in ('-t', '--target-directory') and '=' in a.raw:
|
|
220
|
+
target = _Tok(a.raw, a.val.split('=', 1)[1], a.unq.split('=', 1)[1] if '=' in a.unq else '')
|
|
221
|
+
else:
|
|
222
|
+
ops.append(a)
|
|
223
|
+
i += 1
|
|
224
|
+
return ops, target, rec
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _scan(text, cwd, env, shell_zsh, rules):
|
|
228
|
+
toks = _tokenize(text)
|
|
229
|
+
cwd = cwd or None
|
|
230
|
+
for seg in _segments(toks):
|
|
231
|
+
words, skip = [], False
|
|
232
|
+
for w in seg:
|
|
233
|
+
if skip:
|
|
234
|
+
skip = False
|
|
235
|
+
continue
|
|
236
|
+
if _REDIR_BARE.match(w.raw):
|
|
237
|
+
skip = True
|
|
238
|
+
continue
|
|
239
|
+
if _REDIR.match(w.raw):
|
|
240
|
+
continue
|
|
241
|
+
words.append(w)
|
|
242
|
+
j = 0
|
|
243
|
+
while j < len(words):
|
|
244
|
+
w = words[j]
|
|
245
|
+
if w.raw in _PREFIX or (j > 0 and w.raw.startswith('-') and words[j - 1].raw in _PREFIX):
|
|
246
|
+
j += 1
|
|
247
|
+
continue
|
|
248
|
+
m = _ASSIGN.match(w.raw)
|
|
249
|
+
if m:
|
|
250
|
+
k = _subst(w.val.split('=', 1)[1], env)
|
|
251
|
+
if not _VAR_IN.search(k):
|
|
252
|
+
env[m.group(1)] = k
|
|
253
|
+
j += 1
|
|
254
|
+
continue
|
|
255
|
+
if w.raw == 'export':
|
|
256
|
+
j += 1
|
|
257
|
+
continue
|
|
258
|
+
break
|
|
259
|
+
words = words[j:]
|
|
260
|
+
if not words:
|
|
261
|
+
continue
|
|
262
|
+
cmd = os.path.basename(words[0].val)
|
|
263
|
+
args = words[1:]
|
|
264
|
+
if cmd in ('cd', 'pushd', 'chdir'):
|
|
265
|
+
ops = [a for a in args if not a.raw.startswith('-')]
|
|
266
|
+
cwd = _resolve(ops[0], cwd, env) if ops else None
|
|
267
|
+
continue
|
|
268
|
+
if cmd == 'set' and 'zsh_split' in rules and shell_zsh:
|
|
269
|
+
past = False
|
|
270
|
+
for a in args:
|
|
271
|
+
if not past and a.raw == '--':
|
|
272
|
+
past = True
|
|
273
|
+
continue
|
|
274
|
+
if not past and a.raw.startswith('-'):
|
|
275
|
+
continue
|
|
276
|
+
past = True
|
|
277
|
+
if _PLAIN_VAR.match(a.raw):
|
|
278
|
+
return deny_reason('zsh_split', t=a.raw)
|
|
279
|
+
continue
|
|
280
|
+
if cmd not in ('rsync', 'cp', 'ditto'):
|
|
281
|
+
continue
|
|
282
|
+
ops, target, rec = _parse_copy(cmd, args)
|
|
283
|
+
if target is not None:
|
|
284
|
+
dst, srcs = target, ops
|
|
285
|
+
elif len(ops) >= 2:
|
|
286
|
+
dst, srcs = ops[-1], ops[:-1]
|
|
287
|
+
else:
|
|
288
|
+
continue
|
|
289
|
+
if not srcs:
|
|
290
|
+
continue
|
|
291
|
+
if 'unquoted_copy_dest' in rules and _VAR_IN.search(dst.unq):
|
|
292
|
+
return deny_reason('unquoted_copy_dest', d=dst.raw)
|
|
293
|
+
if 'copy_ancestor' in rules and rec:
|
|
294
|
+
d = _resolve(dst, cwd, env)
|
|
295
|
+
if d:
|
|
296
|
+
for s in srcs:
|
|
297
|
+
sp = _resolve(s, cwd, env)
|
|
298
|
+
hit = _is_inside(sp, d) if sp else None
|
|
299
|
+
if hit:
|
|
300
|
+
return deny_reason('copy_ancestor', s=hit, d=d)
|
|
301
|
+
return None
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def analyze(cmd, cwd='', shell=''):
|
|
305
|
+
"""반환: None | {'deny': reason}"""
|
|
306
|
+
if not cmd or not re.search(r'\b(?:rsync|cp|ditto|set)\b', cmd):
|
|
307
|
+
return None
|
|
308
|
+
sh = os.path.basename(shell or os.environ.get('SHELL', '') or '')
|
|
309
|
+
shell_zsh = sh not in ('bash', 'sh', 'dash', 'ash', 'ksh') # 모르면 zsh(Claude Code Bash = 사용자 로그인 셸)
|
|
310
|
+
pos, parts, bodies = 0, [], []
|
|
311
|
+
for h in _HEREDOC_ANY.finditer(cmd):
|
|
312
|
+
if h.start() < pos:
|
|
313
|
+
continue
|
|
314
|
+
delim = h.group('q') or h.group('e') or h.group('n')
|
|
315
|
+
end = re.compile(r'^\t*' + re.escape(delim) + r'[ \t]*$', re.M).search(cmd, h.end())
|
|
316
|
+
body_end = end.start() if end else len(cmd)
|
|
317
|
+
bodies.append(cmd[h.end():body_end])
|
|
318
|
+
parts.append(cmd[pos:h.end()])
|
|
319
|
+
parts.append(re.sub(r'[^\n]', ' ', cmd[h.end():body_end]))
|
|
320
|
+
pos = body_end
|
|
321
|
+
parts.append(cmd[pos:])
|
|
322
|
+
env = {}
|
|
323
|
+
r = _scan(''.join(parts), cwd, env, shell_zsh, ('copy_ancestor', 'unquoted_copy_dest', 'zsh_split'))
|
|
324
|
+
if r:
|
|
325
|
+
return {'deny': r}
|
|
326
|
+
for b in bodies:
|
|
327
|
+
r = _scan(b, '', dict(env), False, ('unquoted_copy_dest',))
|
|
328
|
+
if r:
|
|
329
|
+
return {'deny': r}
|
|
330
|
+
return None
|
|
@@ -1366,8 +1366,151 @@ def _touch(path):
|
|
|
1366
1366
|
pass
|
|
1367
1367
|
|
|
1368
1368
|
|
|
1369
|
+
_MIGRATE_SKIP_NAMES = frozenset(['skill-links.json', 'items.server.jsonl'])
|
|
1370
|
+
|
|
1371
|
+
|
|
1372
|
+
def _migrate_skip(name):
|
|
1373
|
+
return (name in _MIGRATE_SKIP_NAMES or name.endswith('.lock') or name.endswith('.stamp')
|
|
1374
|
+
or name.endswith('.tmp') or name.startswith('items.jsonl.bak-') or '.tmp-' in name)
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
def _put_new_file(src, dst):
|
|
1378
|
+
"""dst 가 없을 때만 복사한다(덮어쓰지 않음). 임시 파일 + 하드링크라 동시 실행에도 원자적이다."""
|
|
1379
|
+
import shutil
|
|
1380
|
+
if os.path.exists(dst):
|
|
1381
|
+
return
|
|
1382
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
1383
|
+
tmp = '%s.tmp-%d' % (dst, os.getpid())
|
|
1384
|
+
try:
|
|
1385
|
+
shutil.copy2(src, tmp)
|
|
1386
|
+
try:
|
|
1387
|
+
os.link(tmp, dst)
|
|
1388
|
+
except FileExistsError:
|
|
1389
|
+
pass
|
|
1390
|
+
finally:
|
|
1391
|
+
try:
|
|
1392
|
+
os.remove(tmp)
|
|
1393
|
+
except Exception:
|
|
1394
|
+
pass
|
|
1395
|
+
|
|
1396
|
+
|
|
1397
|
+
def _copy_state(src, dst, top=True):
|
|
1398
|
+
for name in os.listdir(src):
|
|
1399
|
+
if _migrate_skip(name) or (top and name == 'items.jsonl'): # items.jsonl 은 재태깅·병합으로 따로 옮긴다
|
|
1400
|
+
continue
|
|
1401
|
+
s, d = os.path.join(src, name), os.path.join(dst, name)
|
|
1402
|
+
if os.path.isdir(s) and not os.path.islink(s):
|
|
1403
|
+
_copy_state(s, d, top=False)
|
|
1404
|
+
elif os.path.isfile(s):
|
|
1405
|
+
_put_new_file(s, d)
|
|
1406
|
+
|
|
1407
|
+
|
|
1408
|
+
def _read_rows(path):
|
|
1409
|
+
rows = []
|
|
1410
|
+
try:
|
|
1411
|
+
with open(path, encoding='utf-8', errors='replace') as f:
|
|
1412
|
+
for ln in f:
|
|
1413
|
+
if ln.strip():
|
|
1414
|
+
rows.append(ln if ln.endswith('\n') else ln + '\n')
|
|
1415
|
+
except Exception:
|
|
1416
|
+
pass
|
|
1417
|
+
return rows
|
|
1418
|
+
|
|
1419
|
+
|
|
1420
|
+
def _row_key(ln):
|
|
1421
|
+
try:
|
|
1422
|
+
r = json.loads(ln)
|
|
1423
|
+
if isinstance(r, dict):
|
|
1424
|
+
if r.get('id') not in (None, ''):
|
|
1425
|
+
return ('id', str(r.get('id')))
|
|
1426
|
+
return ('pk', r.get('problemKey'), r.get('statement'))
|
|
1427
|
+
except Exception:
|
|
1428
|
+
pass
|
|
1429
|
+
return ('raw', ln)
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
def _retag_rows(lines, new_tid, server_pks):
|
|
1433
|
+
"""problemKey 가 서버(새 공간) 행과 일치하는 행만 tenantId 를 새 공간으로. 나머지는 그대로."""
|
|
1434
|
+
out = []
|
|
1435
|
+
for ln in lines:
|
|
1436
|
+
try:
|
|
1437
|
+
r = json.loads(ln)
|
|
1438
|
+
if isinstance(r, dict) and r.get('problemKey') in server_pks:
|
|
1439
|
+
r['tenantId'] = str(new_tid)
|
|
1440
|
+
ln = json.dumps(r, ensure_ascii=False) + '\n'
|
|
1441
|
+
except Exception:
|
|
1442
|
+
pass
|
|
1443
|
+
out.append(ln)
|
|
1444
|
+
return out
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def migrate_account_state(old, new, server_items):
|
|
1448
|
+
"""옛 계정 폴더 상태를 새 계정 폴더로 옮긴다(41 T1). 파일 단위: 새 폴더에 이미 있는 파일은 덮지 않는다.
|
|
1449
|
+
items.jsonl 은 재태깅한 옛 행을 새 파일에 병합한다(같은 id 는 제외). 옛 폴더는 지우지 않는다.
|
|
1450
|
+
반환 True = 끝남(옛 폴더가 없어 할 일 없음 포함), False = 못 함(잠금 중·실패 — 표식을 남겨 다음에 다시 한다)."""
|
|
1451
|
+
lock = None
|
|
1452
|
+
try:
|
|
1453
|
+
od, nd = account_dir_name(old), account_dir_name(new)
|
|
1454
|
+
if not od or not nd or od == nd:
|
|
1455
|
+
return True
|
|
1456
|
+
src, dst = os.path.join(kn_dir(), od), os.path.join(kn_dir(), nd)
|
|
1457
|
+
if not os.path.isdir(src):
|
|
1458
|
+
return True
|
|
1459
|
+
os.makedirs(dst, exist_ok=True)
|
|
1460
|
+
lk = os.path.join(dst, 'migrate.lock')
|
|
1461
|
+
if not _lock(lk):
|
|
1462
|
+
return False
|
|
1463
|
+
lock = lk
|
|
1464
|
+
_copy_state(src, dst)
|
|
1465
|
+
items = os.path.join(src, 'items.jsonl')
|
|
1466
|
+
if os.path.isfile(items):
|
|
1467
|
+
import shutil
|
|
1468
|
+
if not [n for n in os.listdir(src) if n.startswith('items.jsonl.bak-')]:
|
|
1469
|
+
shutil.copy2(items, os.path.join(src, 'items.jsonl.bak-%s' % time.strftime('%Y%m%dT%H%M%S')))
|
|
1470
|
+
pks = set(r.get('problemKey') for r in (server_items or [])
|
|
1471
|
+
if isinstance(r, dict) and isinstance(r.get('problemKey'), str))
|
|
1472
|
+
moved = _retag_rows(_read_rows(items), new.get('tenantId'), pks) if pks else _read_rows(items)
|
|
1473
|
+
dst_items = os.path.join(dst, 'items.jsonl')
|
|
1474
|
+
have = _read_rows(dst_items)
|
|
1475
|
+
seen = set(_row_key(l) for l in have)
|
|
1476
|
+
add = []
|
|
1477
|
+
for ln in moved:
|
|
1478
|
+
k = _row_key(ln)
|
|
1479
|
+
if k not in seen:
|
|
1480
|
+
seen.add(k)
|
|
1481
|
+
add.append(ln)
|
|
1482
|
+
if add:
|
|
1483
|
+
tmp = '%s.tmp-%d' % (dst_items, os.getpid())
|
|
1484
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
1485
|
+
f.writelines(have + add)
|
|
1486
|
+
os.replace(tmp, dst_items)
|
|
1487
|
+
return True
|
|
1488
|
+
except Exception:
|
|
1489
|
+
return False
|
|
1490
|
+
finally:
|
|
1491
|
+
if lock:
|
|
1492
|
+
_unlock(lock)
|
|
1493
|
+
|
|
1494
|
+
|
|
1495
|
+
def migrate_pending(acct, server_items):
|
|
1496
|
+
"""'이전 대기' 표식이 있으면 현재 계정으로 이전을 시도하고, 끝났을 때만 표식을 지운다(41 T1)."""
|
|
1497
|
+
try:
|
|
1498
|
+
ks = _ks()
|
|
1499
|
+
m = ks.read_migrate_marker()
|
|
1500
|
+
if not m:
|
|
1501
|
+
return False
|
|
1502
|
+
old = {'kind': m.get('kind'), 'tenantId': m.get('tenantId')}
|
|
1503
|
+
if migrate_account_state(old, acct, server_items):
|
|
1504
|
+
ks.clear_migrate_marker()
|
|
1505
|
+
return True
|
|
1506
|
+
except Exception:
|
|
1507
|
+
pass
|
|
1508
|
+
return False
|
|
1509
|
+
|
|
1510
|
+
|
|
1369
1511
|
def pull(force=False, acct=None):
|
|
1370
|
-
"""서버 지식을 계정 캐시로 받는다(10분에 1번). 반환 = 받은 건수, 건너뜀·실패 = None.
|
|
1512
|
+
"""서버 지식을 계정 캐시로 받는다(10분에 1번). 반환 = 받은 건수, 건너뜀·실패 = None.
|
|
1513
|
+
응답의 account 가 config 와 다르면 config 를 서버 값에 맞추고 상태를 1회 이전한다(41 T1)."""
|
|
1371
1514
|
try:
|
|
1372
1515
|
a = acct if acct is not None else _ks().account()
|
|
1373
1516
|
cache = account_path(a, 'items.server.jsonl')
|
|
@@ -1386,6 +1529,12 @@ def pull(force=False, acct=None):
|
|
|
1386
1529
|
status, body = _http('GET', url, key)
|
|
1387
1530
|
if status != 200 or not isinstance(body, dict) or not isinstance(body.get('items'), list):
|
|
1388
1531
|
return None
|
|
1532
|
+
aligned = _ks().align_with_server(body.get('account'))
|
|
1533
|
+
if aligned:
|
|
1534
|
+
a = aligned['new']
|
|
1535
|
+
cache = account_path(a, 'items.server.jsonl')
|
|
1536
|
+
migrate_pending(a, body['items']) # 표식이 남아 있으면 성공한 pull 마다 이전을 이어서 시도한다
|
|
1537
|
+
os.makedirs(os.path.dirname(cache), exist_ok=True)
|
|
1389
1538
|
tmp = cache + '.tmp'
|
|
1390
1539
|
with open(tmp, 'w', encoding='utf-8') as f:
|
|
1391
1540
|
for r in body['items']:
|
|
@@ -1580,6 +1729,7 @@ def flush(acct=None, max_batches=10):
|
|
|
1580
1729
|
"""대기열을 POST /api/v1/knowledge/items/events 로 보낸다(≤100건 묶음). 반환 = 보낸 건수.
|
|
1581
1730
|
400 = 영구 거부 → 그 묶음을 버린다. 401·403·429·5xx·네트워크 = 멈추고 다음에 재시도."""
|
|
1582
1731
|
sent_total = 0
|
|
1732
|
+
srv_account = None
|
|
1583
1733
|
try:
|
|
1584
1734
|
p = _pending_path(acct)
|
|
1585
1735
|
if not p or not os.path.exists(p):
|
|
@@ -1609,9 +1759,11 @@ def flush(acct=None, max_batches=10):
|
|
|
1609
1759
|
if events:
|
|
1610
1760
|
body = {'events': events}
|
|
1611
1761
|
_log_tx(url, body)
|
|
1612
|
-
status,
|
|
1762
|
+
status, resp = _http('POST', url, key, body)
|
|
1613
1763
|
if status == 200:
|
|
1614
1764
|
sent_total += len(events)
|
|
1765
|
+
if isinstance(resp, dict) and resp.get('account') is not None:
|
|
1766
|
+
srv_account = resp.get('account')
|
|
1615
1767
|
elif status != 400:
|
|
1616
1768
|
break
|
|
1617
1769
|
done += len(chunk)
|
|
@@ -1626,6 +1778,10 @@ def flush(acct=None, max_batches=10):
|
|
|
1626
1778
|
os.replace(tmp, p)
|
|
1627
1779
|
finally:
|
|
1628
1780
|
_unlock(lock)
|
|
1781
|
+
if srv_account is not None:
|
|
1782
|
+
aligned = _ks().align_with_server(srv_account)
|
|
1783
|
+
if aligned:
|
|
1784
|
+
pull(force=True, acct=aligned['new'])
|
|
1629
1785
|
except Exception:
|
|
1630
1786
|
pass
|
|
1631
1787
|
return sent_total
|