@routinecrew/routinecode 2.31.88 → 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.
Files changed (93) hide show
  1. package/bin/prompt-vault.dat +1 -1
  2. package/bin/rc-credit-turn.js +1 -1
  3. package/bin/rc-grant.js +1 -1
  4. package/bin/rc-team.js +1 -1
  5. package/bin/setup.js +1 -1
  6. package/hooks/lib/agent_budget.py +2 -0
  7. package/hooks/lib/codemode_guard.py +132 -0
  8. package/hooks/lib/copy_guard.py +330 -0
  9. package/hooks/lib/knowledge_items.py +252 -7
  10. package/hooks/lib/knowledge_scope.py +184 -4
  11. package/hooks/lib/knowledge_stock.py +107 -3
  12. package/hooks/lib/known_solution.py +1 -1
  13. package/hooks/lib/repo_pollution.py +173 -0
  14. package/hooks/lib/skill_drafts.py +1 -1
  15. package/hooks/lib/work_kind.py +48 -5
  16. package/hooks/lib/work_kind_events.py +20 -17
  17. package/hooks/pre-agent-spawn.mjs +1 -1
  18. package/hooks/pre-bash-guard.sh +20 -0
  19. package/hooks/session-start.sh +8 -0
  20. package/mcp-dev-tester/dist/attestation.js +1 -1
  21. package/mcp-doc-fetcher/dist/index.js +1 -1
  22. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  23. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  24. package/mcp-intelligence/dist/config-auth.js +1 -1
  25. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  26. package/mcp-intelligence/dist/grounding.js +1 -1
  27. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  28. package/mcp-intelligence/dist/knowledge-guide.js +1 -1
  29. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  30. package/mcp-intelligence/dist/knowledge-migrate.js +1 -1
  31. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  32. package/mcp-intelligence/dist/knowledge-scope.js +1 -1
  33. package/mcp-intelligence/dist/provenance.js +1 -1
  34. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  35. package/mcp-log-watcher/dist/config-auth.js +1 -1
  36. package/mcp-log-watcher/dist/index.js +1 -1
  37. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  38. package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
  39. package/mcp-plan-manager/dist/file-ops.js +1 -1
  40. package/mcp-plan-manager/dist/index.js +1 -1
  41. package/mcp-project-context/dist/index.js +1 -1
  42. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  43. package/mcp-routinecode/dist/attestation.js +1 -1
  44. package/mcp-routinecode/dist/blast-radius.js +1 -1
  45. package/mcp-routinecode/dist/board.js +1 -1
  46. package/mcp-routinecode/dist/changeset.js +1 -1
  47. package/mcp-routinecode/dist/config-auth.js +1 -1
  48. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  49. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  50. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  51. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  52. package/mcp-routinecode/dist/config-map/store.js +1 -1
  53. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  54. package/mcp-routinecode/dist/design-judge.js +1 -1
  55. package/mcp-routinecode/dist/edit-tracker.js +1 -1
  56. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  57. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  58. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  59. package/mcp-routinecode/dist/index.js +1 -1
  60. package/mcp-routinecode/dist/known-solutions.js +1 -1
  61. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  62. package/mcp-routinecode/dist/observed-draft.js +1 -1
  63. package/mcp-routinecode/dist/observed-escalation.js +1 -1
  64. package/mcp-routinecode/dist/routines.js +1 -1
  65. package/mcp-routinecode/dist/rule-engine.js +1 -1
  66. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  67. package/mcp-routinecode/dist/session-registry.js +1 -1
  68. package/mcp-routinecode/dist/test-runner.js +1 -1
  69. package/mcp-routinecode/dist/thinking-judge.js +1 -1
  70. package/mcp-routinecode/dist/verification.js +1 -1
  71. package/mcp-routinecode/dist/viral-loop.js +1 -1
  72. package/package.json +1 -1
  73. package/plugin/agents/analyzer.md.sealed +1 -1
  74. package/plugin/agents/architect.md.sealed +1 -1
  75. package/plugin/agents/crawler.md.sealed +1 -1
  76. package/plugin/agents/explorer.md.sealed +1 -1
  77. package/plugin/agents/implementor-lite.md.sealed +1 -1
  78. package/plugin/agents/implementor.md.sealed +1 -1
  79. package/plugin/agents/looker.md.sealed +1 -1
  80. package/plugin/agents/ops-lite.md.sealed +1 -1
  81. package/plugin/agents/planner.md.sealed +1 -1
  82. package/plugin/agents/recorder.md.sealed +1 -1
  83. package/plugin/agents/reviewer.md.sealed +1 -1
  84. package/plugin/agents/runner-lite.md.sealed +1 -1
  85. package/plugin/agents/verifier.md.sealed +1 -1
  86. package/plugin/commands/analyze.md.sealed +1 -1
  87. package/plugin/commands/plan.md.sealed +1 -1
  88. package/plugin/commands/rc.md.sealed +1 -1
  89. package/plugin/commands/receipt.md.sealed +1 -1
  90. package/plugin/commands/recharge.md.sealed +1 -1
  91. package/plugin/commands/routines.md.sealed +1 -1
  92. package/plugin/commands/share.md.sealed +1 -1
  93. 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
@@ -198,6 +198,19 @@ def load(acct=None):
198
198
  out = [it for it in out if it.get('kid') not in retired]
199
199
  except Exception:
200
200
  pass
201
+ # 설계 36-3 R1: 계정 items.retrigger.json 의 덧붙임 트리거를 합친다(원본 불변, 파일 삭제 = 되돌림).
202
+ ov = retrigger_overlay(a)
203
+ if ov:
204
+ merged = []
205
+ for it in out:
206
+ e = ov.get(it.get('kid'))
207
+ if e and e.get('triggers'):
208
+ have = [json.dumps(x, sort_keys=True) for x in (it.get('triggers') or [])]
209
+ extra = [x for x in e['triggers'] if isinstance(x, dict) and json.dumps(x, sort_keys=True) not in have]
210
+ if extra:
211
+ it = dict(it, triggers=list(it.get('triggers') or []) + extra)
212
+ merged.append(it)
213
+ out = merged
201
214
  return out
202
215
  except Exception:
203
216
  return []
@@ -306,14 +319,78 @@ _CMD_SPLIT_RE = re.compile(r'&&|\|\||[;|\n]')
306
319
  _ENV_PREFIX_RE = re.compile(r'^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*')
307
320
 
308
321
 
322
+ # 명령 낱말 뒤 영어 낱말('python3 has', 'docker is')은 명령 호출이 아니다(설계 36-3 S1 — 실데이터 승격 1건이 'python3 has')
323
+ HEAD_STOPWORDS = frozenset(['has', 'have', 'had', 'is', 'are', 'was', 'were', 'be', 'been', 'not', 'and', 'or', 'the', 'a',
324
+ 'an', 'to', 'in', 'on', 'of', 'for', 'with', 'that', 'this', 'it', 'its', 'can', 'cannot',
325
+ 'will', 'would', 'does', 'do', 'did', 'should', 'must', 'may', 'also', 'only', 'then', 'here',
326
+ 'there', 'itself', 'binary', 'process', 'command', 'commands', 'output', 'when', 'if', 'as',
327
+ 'by', 'at', 'from', 'but', 'so', 'no', 'all', 'any'])
328
+
329
+
309
330
  def command_heads(text):
310
- """문장 안 명령 호출의 머리 2낱말('git status') 집합(소문자)."""
331
+ """문장 안 명령 호출의 머리 2낱말('git status') 집합(소문자). 둘째 낱말이 영어 불용어면 뺀다."""
311
332
  try:
312
- return set('%s %s' % (m.group(1), m.group(2).lower()) for m in CMD_INVOKE_RE.finditer(text or ''))
333
+ return set('%s %s' % (m.group(1), m.group(2).lower()) for m in CMD_INVOKE_RE.finditer(text or '')
334
+ if m.group(2).lower() not in HEAD_STOPWORDS)
313
335
  except Exception:
314
336
  return set()
315
337
 
316
338
 
339
+ # ── 트리거 유도 (설계 36-3 R1·F2) ──────────────────────────────────────────────
340
+ ERR_TEXT_MIN = 8
341
+ _EXC_RE = re.compile(r'\b([A-Z][A-Za-z]*(?:Error|Exception|Exit)):\s*([^\n)\]]{4,100})')
342
+ _QUOTED_RE = re.compile(r"'([^'\n]{8,120})'|\"([^\"\n]{8,120})\"|`([^`\n]{8,120})`")
343
+ _ERR_MARK_RE = re.compile(r'fatal|error|Error|ERR!|not found|No such|denied|failed|cannot|refused|EACCES|ENOENT|ECONN'
344
+ r'|no matches|not a git|Traceback|Unauthorized|forbidden', re.I)
345
+ _SCRIPT_RE = re.compile(r'(?<![\w./-])([A-Za-z0-9][\w-]*\.(?:sh|py|mjs))\b')
346
+
347
+
348
+ def _norm_err(s):
349
+ return ' '.join(str(s or '').split()).casefold()
350
+
351
+
352
+ def derive_triggers(statement, limit=3):
353
+ """진술에서 오류 문구(problem.text)·스크립트 이름(command.regex)을 뽑는다. 결정적·토큰 0. 명령 머리(git status 등)는
354
+ command 분기가 진술에서 직접 맞추므로(레포 조건 포함) 여기서 트리거로 만들지 않는다."""
355
+ out, seen = [], set()
356
+ s = str(statement or '')
357
+
358
+ def add(tr):
359
+ k = json.dumps(tr, sort_keys=True, ensure_ascii=False)
360
+ if k not in seen and len(out) < limit:
361
+ seen.add(k)
362
+ out.append(tr)
363
+ try:
364
+ for m in _EXC_RE.finditer(s):
365
+ txt = ('%s: %s' % (m.group(1), m.group(2))).strip().rstrip('.,;:\'"` ')
366
+ if len(txt) >= ERR_TEXT_MIN:
367
+ add({'type': 'problem', 'match': {'text': txt}})
368
+ for m in _QUOTED_RE.finditer(s):
369
+ q = (m.group(1) or m.group(2) or m.group(3) or '').strip()
370
+ if _ERR_MARK_RE.search(q) and len(q) >= ERR_TEXT_MIN:
371
+ add({'type': 'problem', 'match': {'text': q.rstrip('.,;: ')}})
372
+ for m in _SCRIPT_RE.finditer(s):
373
+ add({'type': 'command', 'match': {'regex': r'(?:^|[\s/;&|])' + re.escape(m.group(1)) + r'\b'}})
374
+ except Exception:
375
+ pass
376
+ return out
377
+
378
+
379
+ RETRIGGER_FILE = 'items.retrigger.json'
380
+
381
+
382
+ def retrigger_overlay(acct=None):
383
+ """계정 items.retrigger.json {'items': {kid: {'triggers': [...], 'round': n, 'at': iso}}}. 없거나 깨졌으면 {}."""
384
+ try:
385
+ a = acct if acct is not None else _ks().account()
386
+ with open(account_path(a, RETRIGGER_FILE), encoding='utf-8') as f:
387
+ d = json.load(f)
388
+ items = d.get('items') if isinstance(d, dict) else None
389
+ return items if isinstance(items, dict) else {}
390
+ except Exception:
391
+ return {}
392
+
393
+
317
394
  def _exec_heads(command):
318
395
  """실행 명령을 && ; | 로 나눈 각 조각의 머리."""
319
396
  out = set()
@@ -365,11 +442,23 @@ def match(event, items):
365
442
  c['_strength'] = st
366
443
  out.append(c)
367
444
  elif typ == 'problem':
368
- pk = event.get('problemKey') or (problem_key_of(event.get('errorText')) if event.get('errorText') else None)
369
- if not pk:
445
+ et = event.get('errorText')
446
+ pk = event.get('problemKey') or (problem_key_of(et) if et else None)
447
+ hay = _norm_err(et) if et else ''
448
+ if not pk and not hay:
370
449
  return []
371
450
  for it in items:
372
- if it.get('problemKey') == pk:
451
+ hit = bool(pk) and it.get('problemKey') == pk
452
+ if not hit and hay:
453
+ # 설계 36-3 E1: 오류 문구 트리거 — 문제 키 해시가 달라도 같은 문구가 오류 출력에 있으면
454
+ for tr in it.get('triggers') or []:
455
+ if not (isinstance(tr, dict) and tr.get('type') == 'problem' and isinstance(tr.get('match'), dict)):
456
+ continue
457
+ txt = _norm_err(tr['match'].get('text'))
458
+ if len(txt) >= ERR_TEXT_MIN and txt in hay:
459
+ hit = True
460
+ break
461
+ if hit:
373
462
  c = dict(it)
374
463
  c['_strength'] = 2
375
464
  out.append(c)
@@ -1277,8 +1366,151 @@ def _touch(path):
1277
1366
  pass
1278
1367
 
1279
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
+
1280
1511
  def pull(force=False, acct=None):
1281
- """서버 지식을 계정 캐시로 받는다(10분에 1번). 반환 = 받은 건수, 건너뜀·실패 = None."""
1512
+ """서버 지식을 계정 캐시로 받는다(10분에 1번). 반환 = 받은 건수, 건너뜀·실패 = None.
1513
+ 응답의 account 가 config 와 다르면 config 를 서버 값에 맞추고 상태를 1회 이전한다(41 T1)."""
1282
1514
  try:
1283
1515
  a = acct if acct is not None else _ks().account()
1284
1516
  cache = account_path(a, 'items.server.jsonl')
@@ -1297,6 +1529,12 @@ def pull(force=False, acct=None):
1297
1529
  status, body = _http('GET', url, key)
1298
1530
  if status != 200 or not isinstance(body, dict) or not isinstance(body.get('items'), list):
1299
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)
1300
1538
  tmp = cache + '.tmp'
1301
1539
  with open(tmp, 'w', encoding='utf-8') as f:
1302
1540
  for r in body['items']:
@@ -1491,6 +1729,7 @@ def flush(acct=None, max_batches=10):
1491
1729
  """대기열을 POST /api/v1/knowledge/items/events 로 보낸다(≤100건 묶음). 반환 = 보낸 건수.
1492
1730
  400 = 영구 거부 → 그 묶음을 버린다. 401·403·429·5xx·네트워크 = 멈추고 다음에 재시도."""
1493
1731
  sent_total = 0
1732
+ srv_account = None
1494
1733
  try:
1495
1734
  p = _pending_path(acct)
1496
1735
  if not p or not os.path.exists(p):
@@ -1520,9 +1759,11 @@ def flush(acct=None, max_batches=10):
1520
1759
  if events:
1521
1760
  body = {'events': events}
1522
1761
  _log_tx(url, body)
1523
- status, _ = _http('POST', url, key, body)
1762
+ status, resp = _http('POST', url, key, body)
1524
1763
  if status == 200:
1525
1764
  sent_total += len(events)
1765
+ if isinstance(resp, dict) and resp.get('account') is not None:
1766
+ srv_account = resp.get('account')
1526
1767
  elif status != 400:
1527
1768
  break
1528
1769
  done += len(chunk)
@@ -1537,6 +1778,10 @@ def flush(acct=None, max_batches=10):
1537
1778
  os.replace(tmp, p)
1538
1779
  finally:
1539
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'])
1540
1785
  except Exception:
1541
1786
  pass
1542
1787
  return sent_total