@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.
Files changed (89) 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/hooks/lib/codemode_guard.py +103 -1
  6. package/hooks/lib/copy_guard.py +330 -0
  7. package/hooks/lib/knowledge_items.py +158 -2
  8. package/hooks/lib/knowledge_scope.py +184 -4
  9. package/hooks/lib/repo_pollution.py +173 -0
  10. package/hooks/lib/skill_drafts.py +1 -1
  11. package/hooks/lib/work_kind.py +48 -5
  12. package/hooks/lib/work_kind_events.py +20 -17
  13. package/hooks/pre-agent-spawn.mjs +1 -1
  14. package/hooks/pre-bash-guard.sh +11 -0
  15. package/hooks/session-start.sh +8 -0
  16. package/mcp-dev-tester/dist/attestation.js +1 -1
  17. package/mcp-doc-fetcher/dist/index.js +1 -1
  18. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  19. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  20. package/mcp-intelligence/dist/config-auth.js +1 -1
  21. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  22. package/mcp-intelligence/dist/grounding.js +1 -1
  23. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  24. package/mcp-intelligence/dist/knowledge-guide.js +1 -1
  25. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  26. package/mcp-intelligence/dist/knowledge-migrate.js +1 -1
  27. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  28. package/mcp-intelligence/dist/knowledge-scope.js +1 -1
  29. package/mcp-intelligence/dist/provenance.js +1 -1
  30. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  31. package/mcp-log-watcher/dist/config-auth.js +1 -1
  32. package/mcp-log-watcher/dist/index.js +1 -1
  33. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  34. package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
  35. package/mcp-plan-manager/dist/file-ops.js +1 -1
  36. package/mcp-plan-manager/dist/index.js +1 -1
  37. package/mcp-project-context/dist/index.js +1 -1
  38. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  39. package/mcp-routinecode/dist/attestation.js +1 -1
  40. package/mcp-routinecode/dist/blast-radius.js +1 -1
  41. package/mcp-routinecode/dist/board.js +1 -1
  42. package/mcp-routinecode/dist/changeset.js +1 -1
  43. package/mcp-routinecode/dist/config-auth.js +1 -1
  44. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  45. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  46. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  47. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  48. package/mcp-routinecode/dist/config-map/store.js +1 -1
  49. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  50. package/mcp-routinecode/dist/design-judge.js +1 -1
  51. package/mcp-routinecode/dist/edit-tracker.js +1 -1
  52. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  53. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  54. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  55. package/mcp-routinecode/dist/index.js +1 -1
  56. package/mcp-routinecode/dist/known-solutions.js +1 -1
  57. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  58. package/mcp-routinecode/dist/observed-draft.js +1 -1
  59. package/mcp-routinecode/dist/observed-escalation.js +1 -1
  60. package/mcp-routinecode/dist/routines.js +1 -1
  61. package/mcp-routinecode/dist/rule-engine.js +1 -1
  62. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  63. package/mcp-routinecode/dist/session-registry.js +1 -1
  64. package/mcp-routinecode/dist/test-runner.js +1 -1
  65. package/mcp-routinecode/dist/thinking-judge.js +1 -1
  66. package/mcp-routinecode/dist/verification.js +1 -1
  67. package/mcp-routinecode/dist/viral-loop.js +1 -1
  68. package/package.json +1 -1
  69. package/plugin/agents/analyzer.md.sealed +1 -1
  70. package/plugin/agents/architect.md.sealed +1 -1
  71. package/plugin/agents/crawler.md.sealed +1 -1
  72. package/plugin/agents/explorer.md.sealed +1 -1
  73. package/plugin/agents/implementor-lite.md.sealed +1 -1
  74. package/plugin/agents/implementor.md.sealed +1 -1
  75. package/plugin/agents/looker.md.sealed +1 -1
  76. package/plugin/agents/ops-lite.md.sealed +1 -1
  77. package/plugin/agents/planner.md.sealed +1 -1
  78. package/plugin/agents/recorder.md.sealed +1 -1
  79. package/plugin/agents/reviewer.md.sealed +1 -1
  80. package/plugin/agents/runner-lite.md.sealed +1 -1
  81. package/plugin/agents/verifier.md.sealed +1 -1
  82. package/plugin/commands/analyze.md.sealed +1 -1
  83. package/plugin/commands/plan.md.sealed +1 -1
  84. package/plugin/commands/rc.md.sealed +1 -1
  85. package/plugin/commands/receipt.md.sealed +1 -1
  86. package/plugin/commands/recharge.md.sealed +1 -1
  87. package/plugin/commands/routines.md.sealed +1 -1
  88. package/plugin/commands/share.md.sealed +1 -1
  89. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -14,6 +14,7 @@ CLI: python3 knowledge_scope.py --notice → 팀 계정이면 세션 안내
14
14
  """
15
15
  import json
16
16
  import os
17
+ import sys
17
18
 
18
19
  # 서비스 테넌트(routinecode 서비스 자체). 계정 공간으로 인정하지 않는다(36 §16.1).
19
20
  SERVICE_TENANT_ID = '50'
@@ -114,10 +115,189 @@ def team_notice(acct=None):
114
115
  return ''
115
116
 
116
117
 
118
+ # ── 서버 판정 계정 맞추기 (docs/지식체계/41 T1) ─────────────────────────────────
119
+
120
+ _ALIGN_NOTICE = {
121
+ 'en': 'This key records to the {space} space - to change it run: routinecode team switch',
122
+ 'ko': '이 키는 {space} 공간에 기록됩니다 — 바꾸려면 routinecode team switch',
123
+ 'ja': 'このキーは {space} スペースに記録されます — 変更するには routinecode team switch',
124
+ 'zh': '此密钥记录到 {space} 空间 — 如需更改请运行 routinecode team switch',
125
+ 'es': 'Esta clave registra en el espacio {space} — para cambiarlo ejecuta routinecode team switch',
126
+ }
127
+ _PERSONAL_LABEL = {'en': 'personal', 'ko': '개인', 'ja': '個人', 'zh': '个人', 'es': 'personal'}
128
+
129
+
130
+ def knowledge_root():
131
+ return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.expanduser('~/.routinecode/knowledge')
132
+
133
+
134
+ def _notice_path():
135
+ return os.path.join(knowledge_root(), 'account-aligned.notice.json')
136
+
137
+
138
+ def server_account(raw):
139
+ """서버 응답의 account {tenantId, type} 검증 → {'kind','tenantId'(str)}. 서비스 테넌트(50)·0·음수·모양 불량이면 None."""
140
+ try:
141
+ if not isinstance(raw, dict):
142
+ return None
143
+ tid = raw.get('tenantId')
144
+ if isinstance(tid, bool):
145
+ return None
146
+ if isinstance(tid, str) and tid.strip().isdigit():
147
+ tid = int(tid.strip())
148
+ if not isinstance(tid, int) or tid <= 0 or str(tid) == SERVICE_TENANT_ID:
149
+ return None
150
+ kind = raw.get('type')
151
+ if kind not in ('team', 'personal'):
152
+ return None
153
+ return {'kind': kind, 'tenantId': str(tid)}
154
+ except Exception:
155
+ return None
156
+
157
+
158
+ def _marker_path():
159
+ return os.path.join(knowledge_root(), 'account-migrate.pending.json')
160
+
161
+
162
+ def read_migrate_marker():
163
+ """'이전 대기' 표식 {kind, tenantId, dir} — 새 계정 폴더 밖 고정 위치. 없으면 None."""
164
+ try:
165
+ with open(_marker_path(), encoding='utf-8') as f:
166
+ m = json.load(f)
167
+ return m if isinstance(m, dict) and m.get('tenantId') else None
168
+ except Exception:
169
+ return None
170
+
171
+
172
+ def clear_migrate_marker():
173
+ try:
174
+ os.remove(_marker_path())
175
+ except Exception:
176
+ pass
177
+
178
+
179
+ def _write_migrate_marker(old):
180
+ """옛 계정(dir 이름 포함)을 원자적으로 기록한다. 이미 대기 중인 표식(더 옛 계정)이 있으면 덮지 않는다."""
181
+ try:
182
+ if not old or not old.get('tenantId'):
183
+ return False
184
+ if read_migrate_marker():
185
+ return True
186
+ os.makedirs(knowledge_root(), exist_ok=True)
187
+ p = _marker_path()
188
+ tmp = '%s.tmp-%d' % (p, os.getpid())
189
+ with open(tmp, 'w', encoding='utf-8') as f:
190
+ json.dump({'kind': old['kind'], 'tenantId': old['tenantId'],
191
+ 'dir': ('t-' if old['kind'] == 'team' else 'p-') + str(old['tenantId'])}, f)
192
+ os.replace(tmp, p)
193
+ return True
194
+ except Exception:
195
+ return False
196
+
197
+
198
+ def _write_config_atomic(path, cfg):
199
+ """임시 파일 + rename, 권한 600. 실패하면 False(호출자는 훅을 막지 않는다)."""
200
+ tmp = '%s.tmp-%d' % (path, os.getpid())
201
+ try:
202
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
203
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
204
+ f.write(json.dumps(cfg, indent=2, ensure_ascii=False))
205
+ f.flush()
206
+ os.fsync(f.fileno())
207
+ os.chmod(tmp, 0o600)
208
+ os.replace(tmp, path)
209
+ return True
210
+ except Exception:
211
+ try:
212
+ os.remove(tmp)
213
+ except Exception:
214
+ pass
215
+ return False
216
+
217
+
218
+ def _locale():
219
+ try:
220
+ from i18n import get_locale
221
+ return get_locale()
222
+ except Exception:
223
+ return 'en'
224
+
225
+
226
+ def _save_align_notice(acct):
227
+ try:
228
+ loc = _locale()
229
+ space = (acct.get('teamName') or ('#' + str(acct.get('tenantId')))) if acct.get('kind') == 'team' \
230
+ else _PERSONAL_LABEL.get(loc, 'personal')
231
+ msg = (_ALIGN_NOTICE.get(loc) or _ALIGN_NOTICE['en']).format(space=space)
232
+ os.makedirs(knowledge_root(), exist_ok=True)
233
+ p = _notice_path()
234
+ tmp = '%s.tmp-%d' % (p, os.getpid())
235
+ with open(tmp, 'w', encoding='utf-8') as f:
236
+ json.dump({'message': msg}, f, ensure_ascii=False)
237
+ os.replace(tmp, p)
238
+ except Exception:
239
+ pass
240
+
241
+
242
+ def align_notice(consume=True):
243
+ """맞추기가 일어난 뒤 첫 세션 시작에만 안내 1줄. 읽으면 지운다."""
244
+ try:
245
+ p = _notice_path()
246
+ with open(p, encoding='utf-8') as f:
247
+ msg = (json.load(f) or {}).get('message') or ''
248
+ if consume:
249
+ try:
250
+ os.remove(p)
251
+ except Exception:
252
+ pass
253
+ return msg if isinstance(msg, str) else ''
254
+ except Exception:
255
+ return ''
256
+
257
+
258
+ def align_with_server(raw_account):
259
+ """서버가 판정한 계정과 config 가 다르면 config.json 의 teamTenantId·teamName 만 고친다(41 T1).
260
+ 반환 {'old': acct, 'new': acct} (바뀐 경우) 또는 None(무동작·실패). 어떤 실패도 예외를 올리지 않는다."""
261
+ try:
262
+ srv = server_account(raw_account)
263
+ if not srv:
264
+ return None
265
+ path = config_path()
266
+ with open(path, encoding='utf-8') as f:
267
+ cfg = json.load(f)
268
+ if not isinstance(cfg, dict):
269
+ return None
270
+ old = account_from_config(cfg)
271
+ if old['kind'] == srv['kind'] and old['tenantId'] == srv['tenantId']:
272
+ return None
273
+ new_cfg = dict(cfg)
274
+ if srv['kind'] == 'team':
275
+ same_team = old['kind'] == 'team' and old['tenantId'] == srv['tenantId']
276
+ new_cfg['teamTenantId'] = int(srv['tenantId'])
277
+ new_cfg['teamName'] = (cfg.get('teamName') or None) if same_team else None
278
+ else:
279
+ if _norm(cfg.get('tenantId')) != srv['tenantId']:
280
+ # 서버 개인 공간과 로컬 tenantId 가 다르면 건드리지 않는다
281
+ sys.stderr.write('[routinecode] server personal space differs from local config tenantId; config left unchanged\n')
282
+ return None
283
+ new_cfg.pop('teamTenantId', None)
284
+ new_cfg.pop('teamName', None)
285
+ had_marker = read_migrate_marker() is not None
286
+ _write_migrate_marker(old) # config 를 고치기 전에 표식부터 남긴다(중간에 죽어도 이전이 유실되지 않게)
287
+ if not _write_config_atomic(path, new_cfg):
288
+ if not had_marker:
289
+ clear_migrate_marker()
290
+ return None
291
+ new = account(refresh=True)
292
+ _save_align_notice(new)
293
+ return {'old': old, 'new': new}
294
+ except Exception:
295
+ return None
296
+
297
+
117
298
  if __name__ == '__main__':
118
- import sys
119
299
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
120
300
  if '--notice' in sys.argv[1:]:
121
- msg = team_notice()
122
- if msg:
123
- print(msg)
301
+ _lines = [m for m in (align_notice(), team_notice()) if m]
302
+ if _lines:
303
+ print(' | '.join(_lines))
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env python3
2
+ """저장소 오염 감지 — 워크스페이스 사본이 하위 저장소 안으로 복사된 사고(11/22)를 세션 시작 때 발견한다.
3
+
4
+ 판정: 저장소 R 의 미추적(무시 파일 제외) 최상위 항목 이름이
5
+ (a) 워크스페이스 루트의 최상위 항목과 같고 (b) R 이 추적하는 최상위 이름이 아니면 의심.
6
+ 의심이 MIN_SUSPECT 개 이상인 저장소만 보고한다(우연 일치 배제).
7
+ 워크스페이스 루트 = 시작 폴더에서 위로 올라가며 저장소를 품은 직계 자식이 2개 이상인 가장 높은 폴더(최대 3단계).
8
+ 비용: du·-uall 금지, 저장소별 git status 짧은 timeout, 전체 상한 TOTAL_BUDGET 초 — 넘으면 조용히 생략.
9
+ 어떤 예외도 호출자에게 전파하지 않는다.
10
+ """
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from concurrent.futures import ThreadPoolExecutor, wait
16
+
17
+ MIN_SUSPECT = 3
18
+ TOTAL_BUDGET = 1.5
19
+ PER_GIT_TIMEOUT = 1.2
20
+ MAX_REPOS_REPORTED = 3
21
+ SKIP_DIRS = {'node_modules', 'dist', 'build', 'venv', '__pycache__', 'target', '.venv'}
22
+ IGNORE_NAMES = {'.DS_Store', '.git'}
23
+
24
+
25
+ def _is_repo(p):
26
+ g = os.path.join(p, '.git')
27
+ return os.path.isdir(g) or os.path.isfile(g)
28
+
29
+
30
+ def _find_repos(base, max_depth):
31
+ """base 아래 max_depth 단계까지의 저장소 루트(저장소 안으로는 내려가지 않는다). base 자신이 저장소면 [base]."""
32
+ if _is_repo(base):
33
+ return [base]
34
+ out = []
35
+ lvl = [base]
36
+ for _ in range(max_depth):
37
+ nxt = []
38
+ for d in lvl:
39
+ try:
40
+ names = os.listdir(d)
41
+ except Exception:
42
+ continue
43
+ for n in names:
44
+ if n.startswith('.') or n in SKIP_DIRS:
45
+ continue
46
+ p = os.path.join(d, n)
47
+ if os.path.isdir(p) and not os.path.islink(p):
48
+ if _is_repo(p):
49
+ out.append(p)
50
+ else:
51
+ nxt.append(p)
52
+ lvl = nxt
53
+ return out
54
+
55
+
56
+ def _containing_repo(start):
57
+ d = os.path.abspath(start)
58
+ for _ in range(12):
59
+ if _is_repo(d):
60
+ return d
61
+ parent = os.path.dirname(d)
62
+ if parent == d:
63
+ return None
64
+ d = parent
65
+ return None
66
+
67
+
68
+ def _branches_with_repos(base, max_depth):
69
+ """base 의 서로 다른 직계 자식 중 저장소(또는 저장소를 품은 폴더)가 있는 것의 수."""
70
+ tops = set()
71
+ for r in _find_repos(base, max_depth):
72
+ rel = os.path.relpath(r, base)
73
+ tops.add(rel.split(os.sep, 1)[0])
74
+ return len(tops)
75
+
76
+
77
+ def _workspace_root(start, max_depth):
78
+ ws = os.path.abspath(start)
79
+ for _ in range(3):
80
+ parent = os.path.dirname(ws)
81
+ if parent == ws or parent == os.path.dirname(parent):
82
+ break
83
+ if _branches_with_repos(parent, max_depth) >= 2:
84
+ ws = parent
85
+ else:
86
+ break
87
+ return ws
88
+
89
+
90
+ def _git(repo, args, timeout):
91
+ r = subprocess.run(['git', '-C', repo] + args, capture_output=True, timeout=timeout,
92
+ env=dict(os.environ, GIT_OPTIONAL_LOCKS='0', LC_ALL='C'))
93
+ if r.returncode != 0:
94
+ raise RuntimeError('git failed')
95
+ return r.stdout
96
+
97
+
98
+ def _top(path):
99
+ return path.strip('/').split('/', 1)[0]
100
+
101
+
102
+ def _check_repo(repo, ws_names, timeout):
103
+ out = _git(repo, ['-c', 'core.quotepath=off', 'status', '--porcelain', '-z', '-unormal'], timeout)
104
+ untracked = set()
105
+ for ent in out.split(b'\0'):
106
+ if ent.startswith(b'?? '):
107
+ untracked.add(_top(ent[3:].decode('utf-8', 'replace')))
108
+ cand = untracked & ws_names
109
+ if len(cand) < MIN_SUSPECT:
110
+ return []
111
+ tracked = set()
112
+ for ent in _git(repo, ['ls-tree', '--name-only', '-z', 'HEAD'], timeout).split(b'\0'):
113
+ if ent:
114
+ tracked.add(ent.decode('utf-8', 'replace'))
115
+ return sorted(cand - tracked)
116
+
117
+
118
+ def scan(root, max_depth=3):
119
+ """[(저장소 경로, [의심 항목...])] — 의심 항목이 MIN_SUSPECT 개 이상인 저장소만."""
120
+ try:
121
+ deadline = time.monotonic() + TOTAL_BUDGET
122
+ start = os.path.abspath(root)
123
+ own = _containing_repo(start)
124
+ ws = _workspace_root(own or start, max_depth)
125
+ ws_names = set()
126
+ for n in os.listdir(ws):
127
+ if not n.startswith('.') and n not in IGNORE_NAMES:
128
+ ws_names.add(n)
129
+ repos = _find_repos(start, max_depth)
130
+ if own and own not in repos:
131
+ repos.append(own)
132
+ if not repos:
133
+ return []
134
+ results = []
135
+ ex = ThreadPoolExecutor(max_workers=8)
136
+ futs = {ex.submit(_check_repo, r, ws_names, PER_GIT_TIMEOUT): r for r in repos}
137
+ done, _ = wait(list(futs), timeout=max(0.05, deadline - time.monotonic()))
138
+ for f in done:
139
+ try:
140
+ sus = f.result()
141
+ except Exception:
142
+ continue
143
+ if sus:
144
+ results.append((futs[f], sus))
145
+ ex.shutdown(wait=False, cancel_futures=True)
146
+ results.sort(key=lambda t: (-len(t[1]), t[0]))
147
+ return results
148
+ except Exception:
149
+ return []
150
+
151
+
152
+ def warning_line(root):
153
+ """세션 시작 경고 한 줄(저장소 최대 MAX_REPOS_REPORTED 개). 없으면 빈 문자열."""
154
+ try:
155
+ found = scan(root)
156
+ if not found:
157
+ return ''
158
+ parts = []
159
+ for repo, sus in found[:MAX_REPOS_REPORTED]:
160
+ rel = os.path.relpath(repo, root) if repo.startswith(os.path.abspath(root)) else repo
161
+ if rel == '.':
162
+ rel = os.path.basename(os.path.abspath(repo))
163
+ parts.append('%s 에 워크스페이스 사본으로 보이는 미추적 항목 %d개(예: %s)' % (rel, len(sus), ', '.join(sus[:3])))
164
+ return '[RoutineCode] 저장소 오염 의심: ' + ' / '.join(parts) + '. 커밋하지 말고 원본 대조 후 정리하세요.'
165
+ except Exception:
166
+ return ''
167
+
168
+
169
+ if __name__ == '__main__':
170
+ try:
171
+ print(warning_line(sys.argv[1] if len(sys.argv) > 1 else os.getcwd()))
172
+ except Exception:
173
+ pass
@@ -85,7 +85,7 @@ def session_steps(path):
85
85
  if not (isinstance(b, dict) and b.get('type') == 'tool_use' and b.get('name') == 'Bash'):
86
86
  continue
87
87
  cmd = (b.get('input') or {}).get('command', '')
88
- k = wk.classify(cmd)
88
+ k = wk.classify(cmd, cwd)
89
89
  if k['action'] not in wke.WORK_ACTIONS or k['group'] not in ('remote', 'local'):
90
90
  continue
91
91
  if k['group'] == 'local' and (not k.get('target') or k['target'] == '-') and cwd:
@@ -7,6 +7,7 @@
7
7
 
8
8
  classify(command) -> {"group": str, "target": str, "action": str}
9
9
  """
10
+ import os
10
11
  import re
11
12
  import shlex
12
13
 
@@ -143,12 +144,53 @@ def _remote_segments(command):
143
144
  _REMOTE_RANK = ["deploy", "db", "copy"] + [a for a, _ in ACTIONS if a not in ("deploy", "db", "copy")] + ["other", "connect"]
144
145
 
145
146
 
146
- def _local_target(command):
147
- m = re.match(r"\s*cd\s+(\"[^\"]+\"|'[^']+'|\S+)", command)
147
+ def repo_name(cwd):
148
+ """cwd 의 git 루트 폴더 이름(없으면 cwd 마지막 폴더). work_kind_events·skill_drafts 가 같이 쓴다."""
149
+ try:
150
+ d = os.path.abspath(cwd)
151
+ cur = d
152
+ while cur and cur != os.path.dirname(cur):
153
+ if os.path.exists(os.path.join(cur, '.git')):
154
+ return os.path.basename(cur)
155
+ cur = os.path.dirname(cur)
156
+ return os.path.basename(d) or '-'
157
+ except Exception:
158
+ return '-'
159
+
160
+
161
+ def _git_root_name(path):
162
+ cur = path
163
+ while cur and cur != os.path.dirname(cur):
164
+ if os.path.exists(os.path.join(cur, '.git')):
165
+ return os.path.basename(cur)
166
+ cur = os.path.dirname(cur)
167
+ return None
168
+
169
+
170
+ _CD = re.compile(r"\s*cd\s+(\"[^\"]+\"|'[^']+'|[^\s;&|]+)")
171
+ _TMP_MARKS = ('scratchpad', '/tmp/', '/private/tmp/')
172
+
173
+
174
+ def _local_target(command, cwd=None):
175
+ """맨 앞 cd 대상. ; && || | 앞에서 끊는다. cwd 가 있으면 그 기준으로 풀어 git 루트 이름으로 올린다."""
176
+ m = _CD.match(command)
148
177
  if not m:
149
178
  return ""
150
179
  p = m.group(1).strip("'\"").rstrip("/")
151
- return p.rsplit("/", 1)[-1] if p else ""
180
+ if not p:
181
+ return ""
182
+ p = os.path.expandvars(p)
183
+ if "$" in p: # 풀리지 않은 셸 변수 — cwd 기준으로 풀면 가짜 경로가 된다. 옛 규칙(마지막 폴더)으로 둔다
184
+ return p.rsplit("/", 1)[-1]
185
+ if not cwd:
186
+ return p.rsplit("/", 1)[-1]
187
+ full = os.path.normpath(os.path.join(os.path.abspath(cwd), os.path.expanduser(p)))
188
+ name = _git_root_name(full)
189
+ if name:
190
+ return name
191
+ if any(x in full + '/' for x in _TMP_MARKS): # 임시 폴더(scratchpad·/tmp) 작업 — 세션 저장소로 귀속
192
+ return repo_name(cwd)
193
+ return os.path.basename(full) or '-'
152
194
 
153
195
 
154
196
  def _strip_prefix_noise(command):
@@ -167,7 +209,8 @@ def _strip_prefix_noise(command):
167
209
  _ROUTINE = re.compile(r"skills/(rc-routine-[A-Za-z0-9_-]+)/")
168
210
 
169
211
 
170
- def classify(command):
212
+ def classify(command, cwd=None):
213
+ """cwd 가 있으면 cd 대상을 그 기준으로 풀어 저장소 이름으로 올린다."""
171
214
  command = command or ""
172
215
  rm = _ROUTINE.search(command)
173
216
  if rm: # 루틴 스킬 스크립트 실행 — 절감 측정(R6·R7)의 '후' 쪽 호출
@@ -191,7 +234,7 @@ def classify(command):
191
234
  act = action_of(body)
192
235
  if act == "script" and heredocs:
193
236
  act = "inline-script"
194
- return {"group": "local", "target": _local_target(command), "action": act}
237
+ return {"group": "local", "target": _local_target(command, cwd), "action": act}
195
238
 
196
239
 
197
240
  def kind_key(k):
@@ -34,6 +34,8 @@ REFRESH_SEC = 30 * 60
34
34
  STATE_NAME = 'work-sessions.json'
35
35
  STAMP_NAME = 'work-sessions.stamp'
36
36
  KEYS_NAME = 'work-kinds.json'
37
+ COUNTS_NAME = 'work-kind-counts.json' # 종류 키 → 그 종류가 나온 세션 수(스킬 연결 순위용)
38
+ LINK_KEYS_MAX = 200
37
39
  LINKS_NAME = 'skill-links.json'
38
40
  # 반복하는 '일'로 보는 동작 — 읽기·쓰기·git 처럼 모든 일에 섞이는 동작은 뺀다
39
41
  WORK_ACTIONS = frozenset(['deploy', 'db', 'logs', 'status', 'copy', 'cron', 'test', 'build', 'install'])
@@ -93,17 +95,8 @@ def _ts(v):
93
95
 
94
96
 
95
97
  def _repo_name(cwd):
96
- """cwd 의 git 루트 폴더 이름(없으면 cwd 마지막 폴더)."""
97
- try:
98
- d = os.path.abspath(cwd)
99
- cur = d
100
- while cur and cur != os.path.dirname(cur):
101
- if os.path.exists(os.path.join(cur, '.git')):
102
- return os.path.basename(cur)
103
- cur = os.path.dirname(cur)
104
- return os.path.basename(d) or '-'
105
- except Exception:
106
- return '-'
98
+ """cwd 의 git 루트 폴더 이름 (work_kind.repo_name 과 같다)."""
99
+ return wk.repo_name(cwd)
107
100
 
108
101
 
109
102
  def _prompt_text(content):
@@ -157,7 +150,7 @@ def session_work(path):
157
150
  for b in (e.get('message', {}).get('content') or []):
158
151
  if not (isinstance(b, dict) and b.get('type') == 'tool_use' and b.get('name') == 'Bash'):
159
152
  continue
160
- k = wk.classify((b.get('input') or {}).get('command', ''))
153
+ k = wk.classify((b.get('input') or {}).get('command', ''), cwd)
161
154
  if k['action'] not in WORK_ACTIONS or k['group'] not in ('remote', 'local'):
162
155
  continue
163
156
  if k['group'] == 'local' and (not k.get('target') or k['target'] == '-') and cwd:
@@ -207,15 +200,17 @@ def _save(p, d):
207
200
  os.replace(tmp, p)
208
201
 
209
202
 
210
- def skill_links(keys, skills, runs_of, sent):
203
+ def skill_links(keys, skills, runs_of, sent, counts=None):
211
204
  """루틴 스킬 → skill_link 이벤트(바뀐 것만)와 새 보낸 상태. keys={종류 키: fk}, sent={스킬: [fk…]}."""
205
+ counts = counts or {}
212
206
  events, now_sent = [], {}
213
207
  for name, c in sorted(skills.items()):
214
208
  try:
215
209
  rx = re.compile(c['replaces'])
216
210
  except Exception:
217
211
  continue
218
- fks = sorted({fk for k, fk in keys.items() if rx.search(k)})[:50]
212
+ cands = sorted((k for k in keys if rx.search(k)), key=lambda k: (-int(counts.get(k) or 0), k))
213
+ fks = list(dict.fromkeys(keys[k] for k in cands))[:LINK_KEYS_MAX]
219
214
  if not fks:
220
215
  continue
221
216
  st = runs_of.get(name) or {}
@@ -228,7 +223,7 @@ def skill_links(keys, skills, runs_of, sent):
228
223
  events.append(dict({'type': 'skill_link', 'skillName': name, 'familyKeys': fks, 'runs': runs}, **stats))
229
224
  for name, prev in sorted(sent.items()):
230
225
  if name not in now_sent and isinstance(prev, dict) and prev.get('fks'):
231
- events.append({'type': 'skill_link', 'skillName': name, 'familyKeys': prev['fks'][:50], 'runs': int(prev.get('runs') or 0), 'removed': True})
226
+ events.append({'type': 'skill_link', 'skillName': name, 'familyKeys': prev['fks'][:LINK_KEYS_MAX], 'runs': int(prev.get('runs') or 0), 'removed': True})
232
227
  return events, now_sent
233
228
 
234
229
 
@@ -292,7 +287,9 @@ def run(now=None, projects_glob=None, dry_run=False, acct=None, force=False):
292
287
  state = _load(state_p)
293
288
  keys_p = ki.account_path(a, KEYS_NAME)
294
289
  keys = _load(keys_p) if keys_p else {}
295
- backfill = keys_p is not None and not os.path.exists(keys_p)
290
+ counts_p = ki.account_path(a, COUNTS_NAME)
291
+ counts = _load(counts_p) if counts_p else {}
292
+ backfill = keys_p is not None and not (os.path.exists(keys_p) and counts_p and os.path.exists(counts_p))
296
293
  files = []
297
294
  for f in glob.glob(projects_glob or os.path.expanduser('~/.claude/projects/*/*.jsonl')):
298
295
  try:
@@ -307,6 +304,8 @@ def run(now=None, projects_glob=None, dry_run=False, acct=None, force=False):
307
304
  r = session_work(f)
308
305
  if r:
309
306
  keys.update({k: family_key(k) for k in r[2]})
307
+ for k in r[2]:
308
+ counts[k] = int(counts.get(k) or 0) + 1
310
309
  continue
311
310
  files.append((m, f, sid))
312
311
  files.sort()
@@ -319,11 +318,13 @@ def run(now=None, projects_glob=None, dry_run=False, acct=None, force=False):
319
318
  continue
320
319
  _sid, cwd, kinds = r
321
320
  keys.update({k: family_key(k) for k in kinds})
321
+ for k in kinds:
322
+ counts[k] = int(counts.get(k) or 0) + 1
322
323
  events += events_of(_sid, cwd, kinds, lambda c: ki.encounter_area(a, c) if c else None)
323
324
  links_p = ki.account_path(a, LINKS_NAME)
324
325
  skills, runs_of = _skills_and_runs()
325
326
  prev_sent = _load(links_p) if links_p else {}
326
- link_events, now_sent = skill_links(keys, skills, runs_of, prev_sent)
327
+ link_events, now_sent = skill_links(keys, skills, runs_of, prev_sent, counts)
327
328
  if dry_run:
328
329
  return {'sessions': done, 'events': len(events), 'keys': len(keys), 'links': link_events, 'sample': events[:4]}
329
330
  if events:
@@ -335,6 +336,8 @@ def run(now=None, projects_glob=None, dry_run=False, acct=None, force=False):
335
336
  _save(state_p, keep)
336
337
  if keys_p:
337
338
  _save(keys_p, keys)
339
+ if counts_p:
340
+ _save(counts_p, counts)
338
341
  # skill_link 은 대기열에 섞지 않고 따로 보낸다 — 옛 서버가 400 으로 묶음 전체를 버리지 않게. 보낸 때만 상태 갱신.
339
342
  if links_p and link_events and send_links(link_events):
340
343
  _save(links_p, now_sent)