@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
@@ -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))
@@ -447,7 +447,8 @@ def measure(acct, root=None, now=None):
447
447
  except Exception: # noqa: BLE001 — 파일 하나가 깨져도 나머지는 센다
448
448
  continue
449
449
  for kid, ts, hit in rows:
450
- a = agg.setdefault(kid, {'files': set(), 'reflected': set(), 'first': None})
450
+ a = agg.setdefault(kid, {'files': set(), 'reflected': set(), 'first': None, 'events': []})
451
+ a['events'].append((p, ts, hit))
451
452
  a['files'].add(p)
452
453
  if hit:
453
454
  a['reflected'].add(p)
@@ -456,6 +457,102 @@ def measure(acct, root=None, now=None):
456
457
  return {'files': len(files), 'items': items, 'agg': agg}
457
458
 
458
459
 
460
+ RETRIGGER_MAX_ROUNDS = 2
461
+
462
+
463
+ def _parse_iso(s):
464
+ try:
465
+ return datetime.strptime(str(s), '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).timestamp()
466
+ except Exception:
467
+ return None
468
+
469
+
470
+ def _write_kids(acct, name, kids, source, now):
471
+ rp = ki.account_path(acct, name)
472
+ tmp = rp + '.tmp'
473
+ with open(tmp, 'w', encoding='utf-8') as f:
474
+ json.dump({'kids': sorted(kids), 'updatedAt': _iso(now), 'source': source}, f, ensure_ascii=False, indent=2)
475
+ os.replace(tmp, rp)
476
+
477
+
478
+ def _retrigger_round(acct, items, agg, quiet, retired, now):
479
+ """quiet 지식의 트리거 재작성 회차. items.retrigger.json 만 쓰고(원본 불변) quiet·retired 목록을 갱신한다."""
480
+ res = {'retriggered': 0, 'noTrigger': 0, 'graduated': [], 'retired': []}
481
+ by_kid = {str(it.get('kid')): it for it in items}
482
+ ov = dict(ki.retrigger_overlay(acct))
483
+ changed = False
484
+ for kid in sorted(quiet):
485
+ it = by_kid.get(kid)
486
+ if it is None or kid in retired:
487
+ continue
488
+ e = ov.get(kid)
489
+ if not e:
490
+ have = [json.dumps(x, sort_keys=True) for x in (it.get('triggers') or [])]
491
+ trig = [x for x in ki.derive_triggers(it.get('statement')) if json.dumps(x, sort_keys=True) not in have]
492
+ if trig:
493
+ ov[kid] = {'triggers': trig, 'round': 1, 'at': _iso(now)}
494
+ res['retriggered'] += 1
495
+ changed = True
496
+ else:
497
+ res['noTrigger'] += 1
498
+ continue
499
+ if e.get('ok'):
500
+ continue
501
+ since = _parse_iso(e.get('at'))
502
+ evs = [ev for ev in (agg.get(kid) or {}).get('events', []) if since is None or (ev[1] is not None and ev[1] > since)]
503
+ if any(ev[2] for ev in evs):
504
+ e = dict(e, ok=True)
505
+ res['graduated'].append(kid)
506
+ elif len(set(ev[0] for ev in evs)) >= AUTO_RETIRE_SESSIONS:
507
+ if int(e.get('round') or 1) >= RETRIGGER_MAX_ROUNDS:
508
+ res['retired'].append(kid)
509
+ else:
510
+ e = dict(e, round=int(e.get('round') or 1) + 1, at=_iso(now))
511
+ else:
512
+ continue
513
+ ov[kid] = e
514
+ changed = True
515
+ if changed:
516
+ rp = ki.account_path(acct, ki.RETRIGGER_FILE)
517
+ tmp = rp + '.tmp'
518
+ with open(tmp, 'w', encoding='utf-8') as f:
519
+ json.dump({'items': ov, 'updatedAt': _iso(now)}, f, ensure_ascii=False, indent=2)
520
+ os.replace(tmp, rp)
521
+ if res['graduated']:
522
+ _write_kids(acct, QUIET_FILE, _kids_of(acct, QUIET_FILE) - set(res['graduated']), 'auto-quiet', now)
523
+ if res['retired']:
524
+ _merge_kids(acct, RETIRED_FILE, res['retired'], 'auto-retired-after-retrigger', now)
525
+ return res
526
+
527
+
528
+ def _form_of(it, extra=None):
529
+ trs = list(it.get('triggers') or []) + list(extra or [])
530
+ if any(isinstance(x, dict) and x.get('type') == 'command' for x in trs):
531
+ return 'command'
532
+ if any(isinstance(x, dict) and x.get('type') == 'problem' and isinstance(x.get('match'), dict)
533
+ and x['match'].get('text') for x in trs):
534
+ return 'error'
535
+ if it.get('problemKey'):
536
+ return 'problemKey'
537
+ return 'touch'
538
+
539
+
540
+ def _by_form(items, agg, overlay):
541
+ """F1: 트리거 형태별 [노출 항목 수, 반영 항목 수]."""
542
+ out = {}
543
+ for it in items:
544
+ kid = str(it.get('kid'))
545
+ a = agg.get(kid)
546
+ if not a or not a['files']:
547
+ continue
548
+ f = _form_of(it, (overlay.get(kid) or {}).get('triggers'))
549
+ c = out.setdefault(f, [0, 0])
550
+ c[0] += 1
551
+ if a['reflected']:
552
+ c[1] += 1
553
+ return out
554
+
555
+
459
556
  def _command_eligible(it):
460
557
  if any(isinstance(t, dict) and t.get('type') == 'command' for t in (it.get('triggers') or [])):
461
558
  return True
@@ -523,6 +620,10 @@ def run_auto(acct, root=None, force=False, now=None):
523
620
  _merge_kids(acct, QUIET_FILE, cands, 'auto-quiet', now)
524
621
  retired_after = retired_prior
525
622
 
623
+ # R1·R2(설계 36-3): quiet 지식은 트리거를 다시 쓴다 → 재작성 뒤 반영되면 quiet 해제, 5세션 반영 0 이 2회차면 재움
624
+ rt = _retrigger_round(acct, items, agg, quiet_prior | set(cands), retired_prior, now)
625
+ retired_after = retired_prior | set(rt['retired'])
626
+
526
627
  # D1: 명령 지식이 주입 뒤 같은 문제로 2개 이상 세션에서 다시 마주쳤으면 승격
527
628
  enc = _encounters(acct)
528
629
  promo = []
@@ -547,6 +648,8 @@ def run_auto(acct, root=None, force=False, now=None):
547
648
  'reflectedItems': len(reflected),
548
649
  'reflectRate': round(len(reflected) / float(len(exposed)), 3) if exposed else 0.0,
549
650
  'quietAuto': len(cands), 'promoted': promoted_total,
651
+ 'retriggered': rt['retriggered'], 'noTrigger': rt['noTrigger'], 'graduated': len(rt['graduated']),
652
+ 'retiredAfterRetrigger': len(rt['retired']), 'byForm': _by_form(items, agg, ki.retrigger_overlay(acct)),
550
653
  }
551
654
  hp = ki.account_path(acct, AUTO_FILE)
552
655
  hist = (_read_history(hp) + [entry])[-AUTO_HISTORY_KEEP:]
@@ -569,8 +672,9 @@ def _main(argv):
569
672
  if 'skipped' in r:
570
673
  print('자동 점검 건너뜀(%s).' % r['skipped'])
571
674
  else:
572
- print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 승격 누계 %d' % (
573
- r['exposedItems'], r['reflectedItems'], r['quietAuto'], r['promoted']))
675
+ print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 트리거 재작성 %d · 재작성 후 반영 %d · 재작성 후 재움 %d · 승격 누계 %d' % (
676
+ r['exposedItems'], r['reflectedItems'], r['quietAuto'], r.get('retriggered', 0), r.get('graduated', 0),
677
+ r.get('retiredAfterRetrigger', 0), r['promoted']))
574
678
  return 0
575
679
  if '--report' in argv:
576
680
  out = None
@@ -166,7 +166,7 @@ def consume_v31(session_id, error_text, command=None, fallback=False):
166
166
  if not rec:
167
167
  return None
168
168
  pk = rec['problemKey']
169
- sel = ki.select([{'type': 'problem', 'problemKey': pk}], session_id=session_id)
169
+ sel = ki.select([{'type': 'problem', 'problemKey': pk, 'errorText': error_text}], session_id=session_id) # 36-3 E1
170
170
  if sel:
171
171
  ki.record_exposure(sel, session_id, 'inject:bash', problem_key=pk)
172
172
  ki.mark_problem_shown(session_id, pk)
@@ -0,0 +1,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):