@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
@@ -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)
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  /* rc-min */
3
- import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{existsSync,statSync,readFileSync as a0a,openSync,readSync,closeSync}from'node:fs';import{createHash as a0b}from'node:crypto';import{homedir}from'node:os';const GATE_LOCALES=['en','ko','ja','zh','es'];function gateLocale(){const a=process.env.ROUTINECODE_LOCALE;if(GATE_LOCALES['includes'](a))return a;try{const c=JSON['parse'](a0a(join(homedir(),'.routinecode','config.json'),'utf-8'));if(GATE_LOCALES['includes'](c['locale']))return c['locale'];}catch{}const b=(process.env.LANG||'')['split']('_')[0x0]['toLowerCase']();if(GATE_LOCALES['includes'](b))return b;return'en';}const GATE_STRINGS={'gate.mcp_degraded_design':{'en':'[design-gate]\x20MCP\x20disconnected\x20—\x20design\x20gate\x20skipped\x20(enforced\x20normally\x20in\x20connected\x20sessions).\x20Verify\x20the\x20design\x20manually.','ko':'[design-gate]\x20MCP\x20미연결\x20감지\x20—\x20설계게이트\x20생략(연결\x20세션에서는\x20정상\x20작동).\x20설계\x20검증을\x20수동으로\x20수행하세요.','ja':'[design-gate]\x20MCP未接続を検出\x20—\x20設計ゲートをスキップします(接続セッションでは通常どおり適用)。設計検証を手動で行ってください。','zh':'[design-gate]\x20检测到\x20MCP\x20未连接\x20—\x20跳过设计门禁(已连接会话中正常生效)。请手动完成设计验证。','es':'[design-gate]\x20MCP\x20desconectado\x20—\x20se\x20omite\x20la\x20puerta\x20de\x20diseño\x20(se\x20aplica\x20normalmente\x20en\x20sesiones\x20conectadas).\x20Verifica\x20el\x20diseño\x20manualmente.'},'gate.no_taskid':{'en':'[HOOK:design-gate]\x20Cannot\x20extract\x20taskId\x20from\x20implementor\x20prompt.\x20Include\x20\x22taskId:\x20<id>\x22\x20in\x20CONTEXT\x20section.','ko':'[HOOK:design-gate]\x20implementor\x20프롬프트에서\x20taskId를\x20찾을\x20수\x20없습니다.\x20CONTEXT에\x20\x22taskId:\x20<id>\x22를\x20포함하세요.','ja':'[HOOK:design-gate]\x20implementorプロンプトからtaskIdを抽出できません。CONTEXTに\x20\x22taskId:\x20<id>\x22\x20を含めてください。','zh':'[HOOK:design-gate]\x20无法从\x20implementor\x20提示中提取\x20taskId。请在\x20CONTEXT\x20中包含\x20\x22taskId:\x20<id>\x22。','es':'[HOOK:design-gate]\x20No\x20se\x20puede\x20extraer\x20taskId\x20del\x20prompt\x20del\x20implementor.\x20Incluye\x20\x22taskId:\x20<id>\x22\x20en\x20la\x20sección\x20CONTEXT.'},'gate.design_score_low':{'en':'[HOOK:design-gate]\x20Design\x20phase\x20score\x20{score}/100\x20<\x2090\x20for\x20task\x20{task_id}.\x20Reproduce\x20each\x20judge\x20deduction,\x20fix\x20the\x20design\x20and\x20run\x20judge_design\x20again\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20점수\x20{score}/100\x20<\x2090.\x20심판\x20감점을\x20재현해\x20설계를\x20고치고\x20judge_design을\x20다시\x20실행한\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計スコア\x20{score}/100\x20<\x2090。審査員の減点を再現して設計を修正し、judge_design\x20を再実行してからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计评分\x20{score}/100\x20<\x2090。请复现评审扣分并修复设计,重新运行\x20judge_design\x20后再派发\x20implementor。','es':'[HOOK:design-gate]\x20Puntuación\x20de\x20diseño\x20{score}/100\x20<\x2090\x20para\x20la\x20tarea\x20{task_id}.\x20Reproduce\x20las\x20deducciones\x20del\x20juez,\x20corrige\x20el\x20diseño\x20y\x20ejecuta\x20judge_design\x20de\x20nuevo\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.no_design_verify':{'en':'[HOOK:design-gate]\x20No\x20design\x20verification\x20found\x20for\x20task\x20{task_id}\x20(tier={tier}).\x20Run\x20judge_design\x20(score\x20>=\x2090)\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20검증이\x20없습니다\x20(tier={tier}).\x20judge_design으로\x2090점\x20이상을\x20받은\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計検証が見つかりません(tier={tier})。judge_design\x20で\x2090\x20点以上を得てからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20未找到任务\x20{task_id}\x20的设计验证(tier={tier})。请通过\x20judge_design\x20达到\x2090\x20分以上后再派发\x20implementor。','es':'[HOOK:design-gate]\x20No\x20se\x20encontró\x20verificación\x20de\x20diseño\x20para\x20la\x20tarea\x20{task_id}\x20(tier={tier}).\x20Ejecuta\x20judge_design\x20(>=\x2090)\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.design_not_judged':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20has\x20no\x20judge\x20score.\x20Run\x20judge_design.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계에\x20심판\x20채점이\x20없습니다.\x20judge_design을\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計に審査員の採点がありません。judge_design\x20を実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计没有评审评分。请运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20no\x20tiene\x20puntuación\x20del\x20juez.\x20Ejecuta\x20judge_design.'},'gate.design_stale':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20changed\x20after\x20judging.\x20Run\x20judge_design\x20again.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계가\x20심사\x20뒤에\x20바뀌었습니다.\x20judge_design을\x20다시\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計が審査後に変更されました。judge_design\x20を再実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计在评审后已更改。请重新运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20cambió\x20después\x20de\x20la\x20revisión.\x20Ejecuta\x20judge_design\x20de\x20nuevo.'},'gate.w5_high_risk':{'en':'[risk-gate]\x20{count}\x20HIGH-risk\x20file(s)\x20involved\x20(e.g.\x20{file})\x20—\x20consulting\x20reviewer\x20first\x20is\x20recommended.','ko':'[risk-gate]\x20HIGH\x20risk\x20파일\x20{count}개\x20포함(예:\x20{file})\x20—\x20reviewer\x20선행을\x20권장합니다.','ja':'[risk-gate]\x20HIGHリスクのファイルが{count}件含まれます(例:\x20{file})—\x20reviewerの事前相談を推奨します。','zh':'[risk-gate]\x20包含\x20{count}\x20个高风险文件(如\x20{file})—\x20建议先咨询\x20reviewer。','es':'[risk-gate]\x20{count}\x20archivo(s)\x20de\x20alto\x20riesgo\x20(p.\x20ej.\x20{file})\x20—\x20se\x20recomienda\x20consultar\x20primero\x20al\x20reviewer.'},'gate.w6_full_tier':{'en':'[tier-gate]\x20full-tier\x20task\x20with\x20planName=none\x20—\x20planner-first\x20is\x20recommended\x20(6+\x20file\x20scope\x20is\x20safer\x20with\x20wave\x20decomposition).','ko':'[tier-gate]\x20full\x20tier\x20태스크에\x20planName=none\x20—\x20planner\x20선행을\x20권장합니다\x20(6+\x20파일\x20범위는\x20wave\x20분해가\x20안전).','ja':'[tier-gate]\x20full\x20tierタスクでplanName=none\x20—\x20plannerの先行を推奨します(6ファイル以上はwave分解が安全)。','zh':'[tier-gate]\x20full\x20tier\x20任务且\x20planName=none\x20—\x20建议先用\x20planner(6+\x20文件范围用\x20wave\x20分解更安全)。','es':'[tier-gate]\x20Tarea\x20full-tier\x20con\x20planName=none\x20—\x20se\x20recomienda\x20usar\x20planner\x20primero\x20(ámbitos\x20de\x206+\x20archivos\x20son\x20más\x20seguros\x20con\x20descomposición\x20en\x20waves).'}};function gt(a,b={}){const c=GATE_STRINGS[a]||{};let d=c[gateLocale()]||c['en']||a;for(const [e,f]of Object['entries'](b))d=d['split']('{'+e+'}')['join'](String(f));return d;}async function readStdin(){let a='';for await(const b of process['stdin'])a+=b;return a;}const CARD_ID_LINE=/^\s*CARD_ID:[ \t]*([a-z0-9]{6,12})[ \t]*$/m;function cardGateExempt(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b)return![];const c=dirname(fileURLToPath(import.meta.url));if(/^\s*ARM:[ \t]*control[ \t]*$/m['test'](a)){let l=0.1;for(const o of[join(c,'lib','route_rules.json'),join(c,'..','hooks','lib','route_rules.json')]){try{const p=JSON['parse'](a0a(o,'utf-8'));if(p['control_ratio']!==undefined)l=Number(p['control_ratio'])||0x0;break;}catch{}}if(!(l>0x0))return![];const m=BigInt(Math['max'](0x1,Math['round'](0x1/l))),n=BigInt('0x'+a0b('sha256')['update'](b,'utf8')['digest']('hex'));return n%m===0x0n;}const d=/^\s*ESCALATED_FROM:[ \t]*([a-z0-9]{6,12})[ \t]*$/m['exec'](a)?.[0x1];if(!d||d===b||process.env.ROUTINECODE_ROUTE_LEDGER_DISABLED==='1')return![];const e=process.env.ROUTINECODE_KNOWLEDGE_DIR||join(homedir(),'.routinecode','knowledge'),f=join(e,'route-ledger.jsonl'),g=statSync(f)['size'],i=0x200*0x400,j=openSync(f,'r');let k='';try{const q=Math['max'](0x0,g-i),s=Buffer['alloc'](g-q);readSync(j,s,0x0,s['length'],q),k=s['toString']('utf-8');}finally{closeSync(j);}for(const t of k['split']('\x0a')){if(!t['includes'](d))continue;try{const u=JSON['parse'](t);if(u['ev']==='card_open'&&u['card_ref']===d)return!![];}catch{}}return![];}catch{return![];}}function riskCardInfo(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b||!/^\s*CARD_KIND:[ \t]*risk[ \t]*$/m['test'](a))return null;const c=/^\s*(CARD_ID|CARD_KIND|GOAL|FILES|DONE|CHECK|KEEP|PLAN_REF|ARM|ESCALATED_FROM):[ \t]*(.*?)\s*$/,d=/^\s*[-*]\s+(.*?)\s*$/,e=new Set(),g=i=>{const j=/^(edit|read)\s*:\s*(.+)$/i['exec'](i);if(!j)e['add'](i);else{if(j[0x1]['toLowerCase']()==='edit')e['add'](j[0x2]['trim']());}};let h=![];for(const i of a['split']('\x0a')){const j=c['exec'](i);if(j){h=j[0x1]==='FILES';if(h&&j[0x2])g(j[0x2]);continue;}if(!h)continue;const k=d['exec'](i);if(k&&k[0x1])g(k[0x1]);else{if(i['trim']()&&!/^[ \t]/['test'](i))h=![];}}return{'id':b,'editCount':e['size']};}catch{return null;}}function emit(a){process['stdout']['write'](JSON['stringify'](a)),process['exit'](0x0);}async function main(){let a;try{const x=await readStdin();a=JSON['parse'](x||'{}');}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const b=a['tool_input']??{},d=b['subagent_type']??'',e=typeof b['prompt']==='string'?b['prompt']:'',f=[],g=0x18*0x3c*0x3c*0x3e8;let h=![];try{const y=process.env.XDG_RUNTIME_DIR||join(homedir(),'.routinecode','run'),z=a['session_id']||'';if(z)try{const A=statSync(join(y,'sess-'+z+'.mcp'));if(Date['now']()-A['mtimeMs']<g)h=!![];}catch{}else for(const B of[join(y,'mcp-alive'),'/tmp/mcp-alive']){try{const C=statSync(B);if(Date['now']()-C['mtimeMs']<g){h=!![];break;}}catch{}}}catch{h=![];}const i=new Set(['implementor','routinecode:implementor']);if(i['has'](d)){!h&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},'systemMessage':gt('gate.mcp_degraded_design')});const D=[/taskId[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/task_id[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/TASK_ID[:\s]+['"]?([a-zA-Z0-9_-]+)/,/task[:\s]+['"]?(\d+[a-zA-Z0-9_-]*)/i];let E=null;for(const I of D){const J=I['exec'](e);if(J?.[0x1]){E=J[0x1];break;}}const F=cardGateExempt(e);F&&(f['push']('[design-gate]\x20작업\x20카드(대조군·승격)\x20—\x20설계\x20관문\x20면제(설계\x2034\x20P3).'),E=null);const G=F?null:riskCardInfo(e);let H=![];if(G){if(!E)E=G['id'];G['editCount']>=0x1&&G['editCount']<=0x2&&(H=!![],f['push']('[design-gate]\x20위험\x20카드\x20'+G['id']+':\x20수정\x20파일\x20'+G['editCount']+'개\x20—\x20설계\x20관문\x20면제(2파일\x20이하).\x20카드\x20리뷰는\x20그대로.'));}!E&&!F&&emit({'decision':'block','reason':gt('gate.no_taskid')});if(E){const {existsSync:K,readFileSync:L}=await import('node:fs'),{join:M}=await import('node:path'),{homedir:N}=await import('node:os'),{createHmac:O,createHash:P,timingSafeEqual:Q}=await import('node:crypto'),R=process.env.ROUTINECODE_KNOWLEDGE_DIR||M(N(),'.routinecode','knowledge'),S=M(R,'verification'),T=M(R,'classifications'),U=M(S,'design-'+E+'.json'),V=M(T,E+'.json');let W=null;try{W=L(M(R,'attest','.key'));}catch{}const X=(Z,a0)=>{if(!W||typeof Z!=='string'||!/^[0-9a-f]{64}$/['test'](Z))return![];const a1=O('sha256',W)['update'](JSON['stringify'](a0))['digest']();return Q(Buffer['from'](Z,'hex'),a1);};let Y='standard';if(K(V))try{const Z=JSON['parse'](L(V,'utf-8'));if(X(Z['mac'],['classification',Z['taskId'],Z['tier'],Z['inputsHash']]))Y=Z['tier']||'standard';}catch{}Y==='full'&&/planName[:\s'"]*none/i['test'](e)&&f['push'](gt('gate.w6_full_tier'));if(Y!=='light'&&!H){let a0='none',a1=0x0;try{if(K(U)){const a2=JSON['parse'](L(U,'utf-8')),a3=[a2['phase'],a2['targetId'],a2['currentScore'],a2['passed'],!!a2['forcedPass'],a2['adjustedScore']??null,a2['scoredAt']??null,a2['changeFingerprint']??null,a2['newL1Growth']??0x0,a2['signedViolations']??0x0],a4=a2['judge']&&typeof a2['judge']==='object'?a2['judge']:null,a5=a4?X(a2['mac'],[...a3,a4['model'],a4['planPath'],a4['planSha256']]):X(a2['mac'],a3)||X(a2['mac'],a3['slice'](0x0,0x8));a1=a2['adjustedScore']??a2['currentScore']??0x0;if(!a5)a0='none';else{if(process.env.ROUTINECODE_DESIGN_JUDGE==='off')a0=a4?'scored':'selfscored';else{if(!a4)a0='not_judged';else{let a6=null;try{a6=P('sha256')['update'](L(a4['planPath']))['digest']('hex');}catch{}a0=a6===a4['planSha256']?'scored':'stale';}}}}}catch{a0='none';}if(a0==='none')emit({'decision':'block','reason':gt('gate.no_design_verify',{'task_id':E,'tier':Y})});if(a0==='not_judged')emit({'decision':'block','reason':gt('gate.design_not_judged',{'task_id':E})});if(a0==='stale')emit({'decision':'block','reason':gt('gate.design_stale',{'task_id':E})});if(a1<0x5a)emit({'decision':'block','reason':gt('gate.design_score_low',{'score':a1,'task_id':E})});if(a0==='selfscored')f['push']('[design-gate]\x20task\x20'+E+':\x20설계\x20심판\x20꺼짐(ROUTINECODE_DESIGN_JUDGE=off)\x20—\x20자기\x20채점\x20설계('+a1+'/100)로\x20진행(부채).');}try{const a7=M(N(),'.routinecode','knowledge','file-risk-cache.json');if(K(a7)&&!/reviewer/i['test'](e)){const a8=JSON['parse'](L(a7,'utf-8'))['scores']||{},a9=e['match'](/\/(?:[\w.@-]+\/)+[\w.@-]+\.[A-Za-z0-9]+/g)||[],aa=[];for(const ab of a9){for(const [ac,ad]of Object['entries'](a8)){if((ac===ab||ab['endsWith'](ac)||ac['endsWith'](ab))&&ad&&typeof ad['score']==='number'&&ad['score']>=0x46){aa['push'](ab);break;}}}aa['length']>0x0&&f['push'](gt('gate.w5_high_risk',{'count':aa['length'],'file':aa[0x0]}));}}catch{}}}const l=new Set(['explorer','Explore']);!l['has'](d)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},...f['length']>0x0?{'systemMessage':f['join']('\x0a')}:{}});const n=dirname(fileURLToPath(import.meta.url)),o=resolve(n,'..','mcp-routinecode','dist','agent-tracker.js');!existsSync(o)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});let q;try{({trackSpawn:q}=await import(o));}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const r=/JUSTIFICATION:\s*([\s\S]+?)(?=\n[A-Z_]+:|$)/i['exec'](e),s=r?.[0x1]?.['trim'](),t=/INVOCATION_MODE:\s*(sequential|parallel)/i['exec'](e),u=t?.[0x1]?.['toLowerCase']()??'sequential';let w;try{w=q({'agentType':d,'parentAgent':'unknown','prompt':e,'invocationMode':u,'justification':s});}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}if(!w['accepted']){const ae=['[HOOK:pre-agent-spawn]\x20'+w['reason'],w['suggestion']?'\x0a'+w['suggestion']:'']['join']('');emit({'decision':'block','reason':ae});}emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}main()['catch'](()=>emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}}));
3
+ import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{existsSync,statSync,readFileSync as a0a,openSync,readSync,closeSync}from'node:fs';import{createHash as a0b}from'node:crypto';import{homedir}from'node:os';const GATE_LOCALES=['en','ko','ja','zh','es'];function gateLocale(){const a=process['env']['ROUTINECODE_LOCALE'];if(GATE_LOCALES['includes'](a))return a;try{const c=JSON['parse'](a0a(join(homedir(),'.routinecode','config.json'),'utf-8'));if(GATE_LOCALES['includes'](c['locale']))return c['locale'];}catch{}const b=(process['env']['LANG']||'')['split']('_')[0x0]['toLowerCase']();if(GATE_LOCALES['includes'](b))return b;return'en';}const GATE_STRINGS={'gate.mcp_degraded_design':{'en':'[design-gate]\x20MCP\x20disconnected\x20—\x20design\x20gate\x20skipped\x20(enforced\x20normally\x20in\x20connected\x20sessions).\x20Verify\x20the\x20design\x20manually.','ko':'[design-gate]\x20MCP\x20미연결\x20감지\x20—\x20설계게이트\x20생략(연결\x20세션에서는\x20정상\x20작동).\x20설계\x20검증을\x20수동으로\x20수행하세요.','ja':'[design-gate]\x20MCP未接続を検出\x20—\x20設計ゲートをスキップします(接続セッションでは通常どおり適用)。設計検証を手動で行ってください。','zh':'[design-gate]\x20检测到\x20MCP\x20未连接\x20—\x20跳过设计门禁(已连接会话中正常生效)。请手动完成设计验证。','es':'[design-gate]\x20MCP\x20desconectado\x20—\x20se\x20omite\x20la\x20puerta\x20de\x20diseño\x20(se\x20aplica\x20normalmente\x20en\x20sesiones\x20conectadas).\x20Verifica\x20el\x20diseño\x20manualmente.'},'gate.no_taskid':{'en':'[HOOK:design-gate]\x20Cannot\x20extract\x20taskId\x20from\x20implementor\x20prompt.\x20Include\x20\x22taskId:\x20<id>\x22\x20in\x20CONTEXT\x20section.','ko':'[HOOK:design-gate]\x20implementor\x20프롬프트에서\x20taskId를\x20찾을\x20수\x20없습니다.\x20CONTEXT에\x20\x22taskId:\x20<id>\x22를\x20포함하세요.','ja':'[HOOK:design-gate]\x20implementorプロンプトからtaskIdを抽出できません。CONTEXTに\x20\x22taskId:\x20<id>\x22\x20を含めてください。','zh':'[HOOK:design-gate]\x20无法从\x20implementor\x20提示中提取\x20taskId。请在\x20CONTEXT\x20中包含\x20\x22taskId:\x20<id>\x22。','es':'[HOOK:design-gate]\x20No\x20se\x20puede\x20extraer\x20taskId\x20del\x20prompt\x20del\x20implementor.\x20Incluye\x20\x22taskId:\x20<id>\x22\x20en\x20la\x20sección\x20CONTEXT.'},'gate.design_score_low':{'en':'[HOOK:design-gate]\x20Design\x20phase\x20score\x20{score}/100\x20<\x2090\x20for\x20task\x20{task_id}.\x20Reproduce\x20each\x20judge\x20deduction,\x20fix\x20the\x20design\x20and\x20run\x20judge_design\x20again\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20점수\x20{score}/100\x20<\x2090.\x20심판\x20감점을\x20재현해\x20설계를\x20고치고\x20judge_design을\x20다시\x20실행한\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計スコア\x20{score}/100\x20<\x2090。審査員の減点を再現して設計を修正し、judge_design\x20を再実行してからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计评分\x20{score}/100\x20<\x2090。请复现评审扣分并修复设计,重新运行\x20judge_design\x20后再派发\x20implementor。','es':'[HOOK:design-gate]\x20Puntuación\x20de\x20diseño\x20{score}/100\x20<\x2090\x20para\x20la\x20tarea\x20{task_id}.\x20Reproduce\x20las\x20deducciones\x20del\x20juez,\x20corrige\x20el\x20diseño\x20y\x20ejecuta\x20judge_design\x20de\x20nuevo\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.no_design_verify':{'en':'[HOOK:design-gate]\x20No\x20design\x20verification\x20found\x20for\x20task\x20{task_id}\x20(tier={tier}).\x20Run\x20judge_design\x20(score\x20>=\x2090)\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20검증이\x20없습니다\x20(tier={tier}).\x20judge_design으로\x2090점\x20이상을\x20받은\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計検証が見つかりません(tier={tier})。judge_design\x20で\x2090\x20点以上を得てからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20未找到任务\x20{task_id}\x20的设计验证(tier={tier})。请通过\x20judge_design\x20达到\x2090\x20分以上后再派发\x20implementor。','es':'[HOOK:design-gate]\x20No\x20se\x20encontró\x20verificación\x20de\x20diseño\x20para\x20la\x20tarea\x20{task_id}\x20(tier={tier}).\x20Ejecuta\x20judge_design\x20(>=\x2090)\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.design_not_judged':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20has\x20no\x20judge\x20score.\x20Run\x20judge_design.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계에\x20심판\x20채점이\x20없습니다.\x20judge_design을\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計に審査員の採点がありません。judge_design\x20を実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计没有评审评分。请运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20no\x20tiene\x20puntuación\x20del\x20juez.\x20Ejecuta\x20judge_design.'},'gate.design_stale':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20changed\x20after\x20judging.\x20Run\x20judge_design\x20again.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계가\x20심사\x20뒤에\x20바뀌었습니다.\x20judge_design을\x20다시\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計が審査後に変更されました。judge_design\x20を再実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计在评审后已更改。请重新运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20cambió\x20después\x20de\x20la\x20revisión.\x20Ejecuta\x20judge_design\x20de\x20nuevo.'},'gate.w5_high_risk':{'en':'[risk-gate]\x20{count}\x20HIGH-risk\x20file(s)\x20involved\x20(e.g.\x20{file})\x20—\x20consulting\x20reviewer\x20first\x20is\x20recommended.','ko':'[risk-gate]\x20HIGH\x20risk\x20파일\x20{count}개\x20포함(예:\x20{file})\x20—\x20reviewer\x20선행을\x20권장합니다.','ja':'[risk-gate]\x20HIGHリスクのファイルが{count}件含まれます(例:\x20{file})—\x20reviewerの事前相談を推奨します。','zh':'[risk-gate]\x20包含\x20{count}\x20个高风险文件(如\x20{file})—\x20建议先咨询\x20reviewer。','es':'[risk-gate]\x20{count}\x20archivo(s)\x20de\x20alto\x20riesgo\x20(p.\x20ej.\x20{file})\x20—\x20se\x20recomienda\x20consultar\x20primero\x20al\x20reviewer.'},'gate.w6_full_tier':{'en':'[tier-gate]\x20full-tier\x20task\x20with\x20planName=none\x20—\x20planner-first\x20is\x20recommended\x20(6+\x20file\x20scope\x20is\x20safer\x20with\x20wave\x20decomposition).','ko':'[tier-gate]\x20full\x20tier\x20태스크에\x20planName=none\x20—\x20planner\x20선행을\x20권장합니다\x20(6+\x20파일\x20범위는\x20wave\x20분해가\x20안전).','ja':'[tier-gate]\x20full\x20tierタスクでplanName=none\x20—\x20plannerの先行を推奨します(6ファイル以上はwave分解が安全)。','zh':'[tier-gate]\x20full\x20tier\x20任务且\x20planName=none\x20—\x20建议先用\x20planner(6+\x20文件范围用\x20wave\x20分解更安全)。','es':'[tier-gate]\x20Tarea\x20full-tier\x20con\x20planName=none\x20—\x20se\x20recomienda\x20usar\x20planner\x20primero\x20(ámbitos\x20de\x206+\x20archivos\x20son\x20más\x20seguros\x20con\x20descomposición\x20en\x20waves).'}};function gt(a,b={}){const c=GATE_STRINGS[a]||{};let d=c[gateLocale()]||c['en']||a;for(const [e,f]of Object['entries'](b))d=d['split']('{'+e+'}')['join'](String(f));return d;}async function readStdin(){let a='';for await(const b of process['stdin'])a+=b;return a;}const CARD_ID_LINE=/^\s*CARD_ID:[ \t]*([a-z0-9]{6,12})[ \t]*$/m;function cardGateExempt(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b)return![];const c=dirname(fileURLToPath(import.meta.url));if(/^\s*ARM:[ \t]*control[ \t]*$/m['test'](a)){let l=0.1;for(const o of[join(c,'lib','route_rules.json'),join(c,'..','hooks','lib','route_rules.json')]){try{const p=JSON['parse'](a0a(o,'utf-8'));if(p['control_ratio']!==undefined)l=Number(p['control_ratio'])||0x0;break;}catch{}}if(!(l>0x0))return![];const m=BigInt(Math['max'](0x1,Math['round'](0x1/l))),n=BigInt('0x'+a0b('sha256')['update'](b,'utf8')['digest']('hex'));return n%m===0x0n;}const d=/^\s*ESCALATED_FROM:[ \t]*([a-z0-9]{6,12})[ \t]*$/m['exec'](a)?.[0x1];if(!d||d===b||process['env']['ROUTINECODE_ROUTE_LEDGER_DISABLED']==='1')return![];const e=process['env']['ROUTINECODE_KNOWLEDGE_DIR']||join(homedir(),'.routinecode','knowledge'),f=join(e,'route-ledger.jsonl'),g=statSync(f)['size'],i=0x200*0x400,j=openSync(f,'r');let k='';try{const q=Math['max'](0x0,g-i),s=Buffer['alloc'](g-q);readSync(j,s,0x0,s['length'],q),k=s['toString']('utf-8');}finally{closeSync(j);}for(const t of k['split']('\x0a')){if(!t['includes'](d))continue;try{const u=JSON['parse'](t);if(u['ev']==='card_open'&&u['card_ref']===d)return!![];}catch{}}return![];}catch{return![];}}function riskCardInfo(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b||!/^\s*CARD_KIND:[ \t]*risk[ \t]*$/m['test'](a))return null;const c=/^\s*(CARD_ID|CARD_KIND|GOAL|FILES|DONE|CHECK|KEEP|PLAN_REF|ARM|ESCALATED_FROM):[ \t]*(.*?)\s*$/,d=/^\s*[-*]\s+(.*?)\s*$/,e=new Set(),g=i=>{const j=/^(edit|read)\s*:\s*(.+)$/i['exec'](i);if(!j)e['add'](i);else{if(j[0x1]['toLowerCase']()==='edit')e['add'](j[0x2]['trim']());}};let h=![];for(const i of a['split']('\x0a')){const j=c['exec'](i);if(j){h=j[0x1]==='FILES';if(h&&j[0x2])g(j[0x2]);continue;}if(!h)continue;const k=d['exec'](i);if(k&&k[0x1])g(k[0x1]);else{if(i['trim']()&&!/^[ \t]/['test'](i))h=![];}}return{'id':b,'editCount':e['size']};}catch{return null;}}function emit(a){process['stdout']['write'](JSON['stringify'](a)),process['exit'](0x0);}async function main(){let a;try{const x=await readStdin();a=JSON['parse'](x||'{}');}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const b=a['tool_input']??{},d=b['subagent_type']??'',e=typeof b['prompt']==='string'?b['prompt']:'',f=[],g=0x18*0x3c*0x3c*0x3e8;let h=![];try{const y=process['env']['XDG_RUNTIME_DIR']||join(homedir(),'.routinecode','run'),z=a['session_id']||'';if(z)try{const A=statSync(join(y,'sess-'+z+'.mcp'));if(Date['now']()-A['mtimeMs']<g)h=!![];}catch{}else for(const B of[join(y,'mcp-alive'),'/tmp/mcp-alive']){try{const C=statSync(B);if(Date['now']()-C['mtimeMs']<g){h=!![];break;}}catch{}}}catch{h=![];}const i=new Set(['implementor','routinecode:implementor']);if(i['has'](d)){!h&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},'systemMessage':gt('gate.mcp_degraded_design')});const D=[/taskId[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/task_id[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/TASK_ID[:\s]+['"]?([a-zA-Z0-9_-]+)/,/task[:\s]+['"]?(\d+[a-zA-Z0-9_-]*)/i];let E=null;for(const I of D){const J=I['exec'](e);if(J?.[0x1]){E=J[0x1];break;}}const F=cardGateExempt(e);F&&(f['push']('[design-gate]\x20작업\x20카드(대조군·승격)\x20—\x20설계\x20관문\x20면제(설계\x2034\x20P3).'),E=null);const G=F?null:riskCardInfo(e);let H=![];if(G){if(!E)E=G['id'];G['editCount']>=0x1&&G['editCount']<=0x2&&(H=!![],f['push']('[design-gate]\x20위험\x20카드\x20'+G['id']+':\x20수정\x20파일\x20'+G['editCount']+'개\x20—\x20설계\x20관문\x20면제(2파일\x20이하).\x20카드\x20리뷰는\x20그대로.'));}!E&&!F&&emit({'decision':'block','reason':gt('gate.no_taskid')});if(E){const {existsSync:K,readFileSync:L}=await import('node:fs'),{join:M}=await import('node:path'),{homedir:N}=await import('node:os'),{createHmac:O,createHash:P,timingSafeEqual:Q}=await import('node:crypto'),R=process['env']['ROUTINECODE_KNOWLEDGE_DIR']||M(N(),'.routinecode','knowledge'),S=M(R,'verification'),T=M(R,'classifications'),U=M(S,'design-'+E+'.json'),V=M(T,E+'.json');let W=null;try{W=L(M(R,'attest','.key'));}catch{}const X=(Z,a0)=>{if(!W||typeof Z!=='string'||!/^[0-9a-f]{64}$/['test'](Z))return![];const a1=O('sha256',W)['update'](JSON['stringify'](a0))['digest']();return Q(Buffer['from'](Z,'hex'),a1);};let Y='standard';if(K(V))try{const Z=JSON['parse'](L(V,'utf-8'));if(X(Z['mac'],['classification',Z['taskId'],Z['tier'],Z['inputsHash']]))Y=Z['tier']||'standard';}catch{}Y==='full'&&/planName[:\s'"]*none/i['test'](e)&&f['push'](gt('gate.w6_full_tier'));if(Y!=='light'&&!H){let a0='none',a1=0x0;try{if(K(U)){const a2=JSON['parse'](L(U,'utf-8')),a3=[a2['phase'],a2['targetId'],a2['currentScore'],a2['passed'],!!a2['forcedPass'],a2['adjustedScore']??null,a2['scoredAt']??null,a2['changeFingerprint']??null,a2['newL1Growth']??0x0,a2['signedViolations']??0x0],a4=a2['judge']&&typeof a2['judge']==='object'?a2['judge']:null,a5=a4?X(a2['mac'],[...a3,a4['model'],a4['planPath'],a4['planSha256']]):X(a2['mac'],a3)||X(a2['mac'],a3['slice'](0x0,0x8));a1=a2['adjustedScore']??a2['currentScore']??0x0;if(!a5)a0='none';else{if(process['env']['ROUTINECODE_DESIGN_JUDGE']==='off')a0=a4?'scored':'selfscored';else{if(!a4)a0='not_judged';else{let a6=null;try{a6=P('sha256')['update'](L(a4['planPath']))['digest']('hex');}catch{}a0=a6===a4['planSha256']?'scored':'stale';}}}}}catch{a0='none';}if(a0==='none')emit({'decision':'block','reason':gt('gate.no_design_verify',{'task_id':E,'tier':Y})});if(a0==='not_judged')emit({'decision':'block','reason':gt('gate.design_not_judged',{'task_id':E})});if(a0==='stale')emit({'decision':'block','reason':gt('gate.design_stale',{'task_id':E})});if(a1<0x5a)emit({'decision':'block','reason':gt('gate.design_score_low',{'score':a1,'task_id':E})});if(a0==='selfscored')f['push']('[design-gate]\x20task\x20'+E+':\x20설계\x20심판\x20꺼짐(ROUTINECODE_DESIGN_JUDGE=off)\x20—\x20자기\x20채점\x20설계('+a1+'/100)로\x20진행(부채).');}try{const a7=M(N(),'.routinecode','knowledge','file-risk-cache.json');if(K(a7)&&!/reviewer/i['test'](e)){const a8=JSON['parse'](L(a7,'utf-8'))['scores']||{},a9=e['match'](/\/(?:[\w.@-]+\/)+[\w.@-]+\.[A-Za-z0-9]+/g)||[],aa=[];for(const ab of a9){for(const [ac,ad]of Object['entries'](a8)){if((ac===ab||ab['endsWith'](ac)||ac['endsWith'](ab))&&ad&&typeof ad['score']==='number'&&ad['score']>=0x46){aa['push'](ab);break;}}}aa['length']>0x0&&f['push'](gt('gate.w5_high_risk',{'count':aa['length'],'file':aa[0x0]}));}}catch{}}}const l=new Set(['explorer','Explore']);!l['has'](d)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},...f['length']>0x0?{'systemMessage':f['join']('\x0a')}:{}});const n=dirname(fileURLToPath(import.meta.url)),o=resolve(n,'..','mcp-routinecode','dist','agent-tracker.js');!existsSync(o)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});let q;try{({trackSpawn:q}=await import(o));}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const r=/JUSTIFICATION:\s*([\s\S]+?)(?=\n[A-Z_]+:|$)/i['exec'](e),s=r?.[0x1]?.['trim'](),t=/INVOCATION_MODE:\s*(sequential|parallel)/i['exec'](e),u=t?.[0x1]?.['toLowerCase']()??'sequential';let w;try{w=q({'agentType':d,'parentAgent':'unknown','prompt':e,'invocationMode':u,'justification':s});}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}if(!w['accepted']){const ae=['[HOOK:pre-agent-spawn]\x20'+w['reason'],w['suggestion']?'\x0a'+w['suggestion']:'']['join']('');emit({'decision':'block','reason':ae});}emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}main()['catch'](()=>emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}}));
@@ -123,6 +123,15 @@ except SystemExit:
123
123
  except Exception:
124
124
  pass
125
125
 
126
+ # 설계 37 — 코드 모드 스크립트 안 호출(tool_use_id repl_) 에서 되돌리기 어려운 명령 deny. 모듈 오류는 통과(fail-open).
127
+ try:
128
+ import codemode_guard as _cmg
129
+ _cm_reason = _cmg.check(inp, cmd)
130
+ except Exception:
131
+ _cm_reason = None
132
+ if _cm_reason:
133
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': _cm_reason}})
134
+
126
135
  # rm/rmdir — Claude Code 하네스의 '위험 삭제' 확인창(bypass 에서도 안 꺼짐, 훅 allow 로 승인 불가)을
127
136
  # 사용자에게 노출하지 않는다. 실측 규칙·처리는 lib/rm_guard.py 헤더 참조.
128
137
  # block = 진짜 위험(시스템/홈루트/민감 경로)
@@ -149,6 +158,17 @@ if _rv:
149
158
  _nti['command'] = _rv['rewrite']
150
159
  emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow', 'updatedInput': _nti}})
151
160
 
161
+ # 복사 가드 — 상위 폴더를 하위로 복사 / 무따옴표 대상 / zsh 단어분할 의존 차단(2026-11-22 워크스페이스 통째 복사 사고).
162
+ # 규칙은 lib/copy_guard.py 헤더 참조. 어떤 실패도 통과.
163
+ try:
164
+ import copy_guard as _cg
165
+ _cgv = _cg.analyze(cmd, inp.get('cwd') or os.getcwd(), inp.get('shell') or os.environ.get('SHELL', ''))
166
+ except Exception:
167
+ _cgv = None
168
+ if _cgv and _cgv.get('deny'):
169
+ emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny',
170
+ 'permissionDecisionReason': _cgv['deny']}})
171
+
152
172
  # 설계 18 T3 작성 전 구조 파악 — 대상 추출은 여기서 끝내고 소스 쓰기 대상이 있을 때만 Node 를 띄운다(일반 Bash 는 지연 없음).
153
173
  # 표식 없는 디렉터리의 새 파일 = 맥락과 함께 1회 거절, 기존 파일 = 맥락 공급. 어떤 실패도 가드 판정에 영향 없음.
154
174
  _pf_ctx = ''
@@ -1711,6 +1711,14 @@ if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ -n "$_RC_HOOK_LIB" ]; then
1711
1711
  fi
1712
1712
  fi
1713
1713
 
1714
+ # --- 저장소 오염 감지: 워크스페이스 사본이 하위 저장소 안에 미추적으로 복사된 사고(11/22) 당일 발견. 1.5초 상한·실패 시 침묵 ---
1715
+ if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ -n "$_RC_HOOK_LIB" ] && [ -f "$_RC_HOOK_LIB/repo_pollution.py" ]; then
1716
+ _RC_POLLUTION=$(python3 "$_RC_HOOK_LIB/repo_pollution.py" "${CLAUDE_PROJECT_DIR:-$PWD}" 2>/dev/null)
1717
+ if [ -n "$_RC_POLLUTION" ]; then
1718
+ MESSAGES="${MESSAGES:+$MESSAGES | }${_RC_POLLUTION}"
1719
+ fi
1720
+ fi
1721
+
1714
1722
  # --- 공유 판 (설계 31): 세션 PID → session_id 기록 + 판 요약을 모델 맥락에 (판이 비면 침묵) ---
1715
1723
  RC_BOARD_CTX=""
1716
1724
  if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ -n "$_RC_HOOK_LIB" ] && [ -f "$_RC_HOOK_LIB/board.py" ]; then
@@ -1 +1 @@
1
- import*as a7a from'fs';import*as a7b from'path';import*as a7c from'crypto';import{homedir}from'os';function knowledgeDir(){return process.env.ROUTINECODE_KNOWLEDGE_DIR||a7b['join'](homedir(),'.routinecode','knowledge');}export function attestDir(){return a7b['join'](knowledgeDir(),'attest');}function attestFile(){return a7b['join'](attestDir(),'attestations.jsonl');}function loadKey(){const a=a7b['join'](attestDir(),'.key');try{return a7a['readFileSync'](a);}catch{}try{a7a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),a7a['writeFileSync'](a,a7c['randomBytes'](0x20),{'flag':'wx','mode':0x180});}catch{}try{return a7a['readFileSync'](a);}catch{return null;}}function canonical(a){return JSON['stringify']([a['v'],a['kind'],a['ts'],a['projectDir'],a['success'],a['detail']]);}function sign(a,b){return a7c['createHmac']('sha256',a)['update'](canonical(b))['digest']('hex');}export function normalizeProjectDir(a){if(!a)return null;try{return a7a['realpathSync'](a);}catch{return a7b['resolve'](a);}}const ROTATE_BYTES=0x5*0x400*0x400,KEEP_MS=0x7*0x18*0x3c*0x3c*0x3e8;function rotateIfLarge(){const a=a7b['join'](attestDir(),'.rotate.lock');try{const b=attestFile();if(a7a['statSync'](b)['size']<ROTATE_BYTES)return;try{a7a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}catch{try{if(Date['now']()-a7a['statSync'](a)['mtimeMs']<0x2710)return;a7a['rmSync'](a,{'force':!![]});}catch{return;}a7a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}const c=b+'.'+process['pid']+'.rotating';a7a['renameSync'](b,c);const d=Date['now']()-KEEP_MS,e=a7a['readFileSync'](c,'utf-8')['split']('\x0a')['filter'](g=>{if(!g['trim']())return![];try{return(JSON['parse'](g)['ts']??0x0)>=d;}catch{return![];}});if(e['length'])a7a['appendFileSync'](b,e['join']('\x0a')+'\x0a',{'mode':0x180});a7a['rmSync'](c,{'force':!![]});}catch{}finally{try{if(a7a['readFileSync'](a,'utf-8')===String(process['pid']))a7a['rmSync'](a,{'force':!![]});}catch{}}}export function appendAttestation(a){try{const b=loadKey();if(!b)return![];const c={'v':0x1,'kind':a['kind'],'ts':Date['now'](),'projectDir':normalizeProjectDir(a['projectDir']),'success':a['success'],'detail':a['detail']??{}},d=JSON['stringify']({...c,'mac':sign(b,c)});return a7a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),rotateIfLarge(),a7a['appendFileSync'](attestFile(),d+'\x0a',{'mode':0x180}),!![];}catch{return![];}}export function readAttestations(b={}){let c;try{c=a7a['readFileSync'](attestFile(),'utf-8');}catch{return[];}const d=loadKey();if(!d)return[];const e=normalizeProjectDir(b['projectDir']),f=[];for(const g of c['split']('\x0a')){if(!g['trim']())continue;let h;try{h=JSON['parse'](g);}catch{continue;}if(!h||h['v']!==0x1||typeof h['mac']!=='string')continue;const {mac:i,...j}=h,k=sign(d,j);if(i['length']!==k['length']||!a7c['timingSafeEqual'](Buffer['from'](i),Buffer['from'](k)))continue;if(b['sinceMs']!==undefined&&h['ts']<b['sinceMs'])continue;if(b['kinds']&&!b['kinds']['includes'](h['kind']))continue;if(e&&h['projectDir']&&!(h['projectDir']===e||h['projectDir']['startsWith'](e+a7b['sep'])||e['startsWith'](h['projectDir']+a7b['sep'])))continue;f['push'](h);}return f;}
1
+ import*as a7a from'fs';import*as a7b from'path';import*as a7c from'crypto';import{homedir}from'os';function knowledgeDir(){return process['env']['ROUTINECODE_KNOWLEDGE_DIR']||a7b['join'](homedir(),'.routinecode','knowledge');}export function attestDir(){return a7b['join'](knowledgeDir(),'attest');}function attestFile(){return a7b['join'](attestDir(),'attestations.jsonl');}function loadKey(){const a=a7b['join'](attestDir(),'.key');try{return a7a['readFileSync'](a);}catch{}try{a7a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),a7a['writeFileSync'](a,a7c['randomBytes'](0x20),{'flag':'wx','mode':0x180});}catch{}try{return a7a['readFileSync'](a);}catch{return null;}}function canonical(a){return JSON['stringify']([a['v'],a['kind'],a['ts'],a['projectDir'],a['success'],a['detail']]);}function sign(a,b){return a7c['createHmac']('sha256',a)['update'](canonical(b))['digest']('hex');}export function normalizeProjectDir(a){if(!a)return null;try{return a7a['realpathSync'](a);}catch{return a7b['resolve'](a);}}const ROTATE_BYTES=0x5*0x400*0x400,KEEP_MS=0x7*0x18*0x3c*0x3c*0x3e8;function rotateIfLarge(){const a=a7b['join'](attestDir(),'.rotate.lock');try{const b=attestFile();if(a7a['statSync'](b)['size']<ROTATE_BYTES)return;try{a7a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}catch{try{if(Date['now']()-a7a['statSync'](a)['mtimeMs']<0x2710)return;a7a['rmSync'](a,{'force':!![]});}catch{return;}a7a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}const c=b+'.'+process['pid']+'.rotating';a7a['renameSync'](b,c);const d=Date['now']()-KEEP_MS,e=a7a['readFileSync'](c,'utf-8')['split']('\x0a')['filter'](g=>{if(!g['trim']())return![];try{return(JSON['parse'](g)['ts']??0x0)>=d;}catch{return![];}});if(e['length'])a7a['appendFileSync'](b,e['join']('\x0a')+'\x0a',{'mode':0x180});a7a['rmSync'](c,{'force':!![]});}catch{}finally{try{if(a7a['readFileSync'](a,'utf-8')===String(process['pid']))a7a['rmSync'](a,{'force':!![]});}catch{}}}export function appendAttestation(a){try{const b=loadKey();if(!b)return![];const c={'v':0x1,'kind':a['kind'],'ts':Date['now'](),'projectDir':normalizeProjectDir(a['projectDir']),'success':a['success'],'detail':a['detail']??{}},d=JSON['stringify']({...c,'mac':sign(b,c)});return a7a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),rotateIfLarge(),a7a['appendFileSync'](attestFile(),d+'\x0a',{'mode':0x180}),!![];}catch{return![];}}export function readAttestations(b={}){let c;try{c=a7a['readFileSync'](attestFile(),'utf-8');}catch{return[];}const d=loadKey();if(!d)return[];const e=normalizeProjectDir(b['projectDir']),f=[];for(const g of c['split']('\x0a')){if(!g['trim']())continue;let h;try{h=JSON['parse'](g);}catch{continue;}if(!h||h['v']!==0x1||typeof h['mac']!=='string')continue;const {mac:i,...j}=h,k=sign(d,j);if(i['length']!==k['length']||!a7c['timingSafeEqual'](Buffer['from'](i),Buffer['from'](k)))continue;if(b['sinceMs']!==undefined&&h['ts']<b['sinceMs'])continue;if(b['kinds']&&!b['kinds']['includes'](h['kind']))continue;if(e&&h['projectDir']&&!(h['projectDir']===e||h['projectDir']['startsWith'](e+a7b['sep'])||e['startsWith'](h['projectDir']+a7b['sep'])))continue;f['push'](h);}return f;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Server}from'@modelcontextprotocol/sdk/server/index.js';import{StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import{CallToolRequestSchema,ListToolsRequestSchema}from'@modelcontextprotocol/sdk/types.js';import{execFileSync}from'child_process';import{tmpdir}from'os';import{join}from'path';function isPrivateIp(a){const b=a['replace'](/^\[|\]$/g,'')['toLowerCase']();return b==='0.0.0.0'||b==='::1'||b==='::'||/^127\./['test'](b)||/^10\./['test'](b)||/^192\.168\./['test'](b)||/^169\.254\./['test'](b)||/^172\.(1[6-9]|2\d|3[01])\./['test'](b)||/^(fc|fd)[0-9a-f]{2}:/['test'](b)||/^fe80:/['test'](b)||/^::ffff:127\./['test'](b)||/^::ffff:10\./['test'](b)||/^::ffff:192\.168\./['test'](b)||/^::ffff:169\.254\./['test'](b);}async function assertPublicUrl(a){let b;try{b=new URL(a);}catch{throw new Error('invalid\x20URL:\x20'+a);}if(b['protocol']!=='http:'&&b['protocol']!=='https:')throw new Error('blocked\x20scheme:\x20'+b['protocol']);const c=b['hostname']['replace'](/^\[|\]$/g,'')['toLowerCase'](),d=(process.env.ROUTINECODE_DOCFETCH_ALLOW_HOSTS||'')['split'](',')['map'](f=>f['trim']()['toLowerCase']())['filter'](Boolean);if(d['includes'](c))return;if(c==='localhost'||c['endsWith']('.localhost')||isPrivateIp(c))throw new Error('blocked\x20private/link-local\x20host:\x20'+c+'\x20(set\x20ROUTINECODE_DOCFETCH_ALLOW_HOSTS\x20to\x20allow)');const e=/^[0-9.]+$/['test'](c)||c['includes'](':');if(!e){const {lookup:f}=await import('node:dns/promises');let g=[];try{g=await f(c,{'all':!![]});}catch{return;}const h=g['find'](i=>isPrivateIp(i['address']));if(h)throw new Error('blocked:\x20'+c+'\x20resolves\x20to\x20private\x20IP\x20'+h['address']+'\x20(possible\x20DNS\x20rebinding)');}}const server=new Server({'name':'mcp-doc-fetcher','version':'1.0.0'},{'capabilities':{'tools':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>({'tools':[{'name':'crawl_sitemap','description':'Crawl\x20a\x20sitemap.xml\x20and\x20extract\x20all\x20page\x20URLs.\x20Tries\x20/sitemap.xml,\x20/sitemap-0.xml,\x20/docs/sitemap.xml.','inputSchema':{'type':'object','properties':{'base_url':{'type':'string','description':'Base\x20URL\x20of\x20the\x20documentation\x20site'}},'required':['base_url']}},{'name':'fetch_doc_page','description':'Fetch\x20a\x20documentation\x20page\x20and\x20extract\x20text\x20content\x20(strips\x20HTML\x20tags).','inputSchema':{'type':'object','properties':{'url':{'type':'string','description':'URL\x20to\x20fetch'},'max_length':{'type':'number','description':'Max\x20character\x20length\x20(default:\x2010000)'}},'required':['url']}},{'name':'clone_repo_shallow','description':'Shallow\x20clone\x20a\x20GitHub\x20repository\x20to\x20temp\x20directory.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'dest':{'type':'string','description':'Optional\x20destination\x20directory'}},'required':['repo']}},{'name':'search_github_issues','description':'Search\x20GitHub\x20issues\x20and\x20PRs\x20by\x20query.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'query':{'type':'string','description':'Search\x20query'},'state':{'type':'string','enum':['open','closed','all'],'description':'Issue\x20state\x20(default:\x20all)'},'limit':{'type':'number','description':'Max\x20results\x20(default:\x2010)'}},'required':['repo','query']}},{'name':'get_releases','description':'Get\x20recent\x20releases\x20from\x20a\x20GitHub\x20repository.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'count':{'type':'number','description':'Number\x20of\x20releases\x20(default:\x205)'}},'required':['repo']}},{'name':'build_permalink','description':'Build\x20a\x20GitHub\x20permalink\x20URL\x20from\x20repo,\x20SHA,\x20file\x20path,\x20and\x20optional\x20line\x20range.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'sha':{'type':'string','description':'Commit\x20SHA'},'path':{'type':'string','description':'File\x20path\x20within\x20repository'},'start_line':{'type':'number','description':'Start\x20line\x20(optional)'},'end_line':{'type':'number','description':'End\x20line\x20(optional)'}},'required':['repo','sha','path']}}]})),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];try{switch(b){case'crawl_sitemap':{const d=c['base_url']['replace'](/\/$/,''),f=['/sitemap.xml','/sitemap-0.xml','/docs/sitemap.xml','/sitemap_index.xml'];let g=[];await assertPublicUrl(d);for(const h of f){try{const i=await fetch(d+h,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)});if(!i['ok'])continue;const j=await i['text'](),k=/<loc>([^<]+)<\/loc>/g;let l;while((l=k['exec'](j))!==null){g['push'](l[0x1]);}if(g['length']>0x0)break;}catch{continue;}}return ok(JSON['stringify']({'base_url':d,'urls_found':g['length'],'urls':g['slice'](0x0,0x64)},null,0x2));}case'fetch_doc_page':{const m=c['url'],n=c?.['max_length']||0x2710;await assertPublicUrl(m);const o=await fetch(m,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x3a98)});if(!o['ok'])return err('HTTP\x20'+o['status']+':\x20'+o['statusText']);let p=await o['text'](),q=p['replace'](/<script[^>]*>[\s\S]*?<\/script>/gi,'')['replace'](/<style[^>]*>[\s\S]*?<\/style>/gi,'')['replace'](/<nav[^>]*>[\s\S]*?<\/nav>/gi,'')['replace'](/<footer[^>]*>[\s\S]*?<\/footer>/gi,'')['replace'](/<header[^>]*>[\s\S]*?<\/header>/gi,'')['replace'](/<[^>]+>/g,'\x20')['replace'](/&nbsp;/g,'\x20')['replace'](/&amp;/g,'&')['replace'](/&lt;/g,'<')['replace'](/&gt;/g,'>')['replace'](/&quot;/g,'\x22')['replace'](/\s+/g,'\x20')['trim']();return q['length']>n&&(q=q['slice'](0x0,n)+'\x0a...(truncated)'),ok(q);}case'clone_repo_shallow':{const r=c['repo'];if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](r))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');const s=r['split']('/')['pop']()||r,t=c?.['dest']||join(tmpdir(),s);try{execFileSync('git',['clone','--depth','1','https://github.com/'+r+'.git',t],{'timeout':0xea60,'stdio':'pipe'});const u=execFileSync('git',['rev-parse','HEAD'],{'cwd':t,'encoding':'utf-8','timeout':0x1388})['trim']();return ok(JSON['stringify']({'path':t,'sha':u,'repo':r},null,0x2));}catch(v){return err('Clone\x20failed:\x20'+v['message']?.['split']('\x0a')[0x0]);}}case'search_github_issues':{const w=c['repo'],x=c['query'],y=c?.['state']||'all',z=c?.['limit']||0xa;if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](w))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');if(!['open','closed','all']['includes'](y))return err('Invalid\x20state.\x20Expected:\x20open,\x20closed,\x20or\x20all');try{const A=execFileSync('gh',['search','issues',x,'--repo',w,'--state',y,'--limit',String(z),'--json','number,title,state,url,createdAt'],{'encoding':'utf-8','timeout':0x3a98});return ok(A);}catch(B){try{const C='https://api.github.com/search/issues?q='+encodeURIComponent(x+'\x20repo:'+w)+'&per_page='+z,D=await fetch(C,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)}),E=await D['json'](),F=(E['items']||[])['map'](G=>({'number':G['number'],'title':G['title'],'state':G['state'],'url':G['html_url']}));return ok(JSON['stringify'](F,null,0x2));}catch{return err('GitHub\x20search\x20failed\x20(no\x20gh\x20CLI\x20and\x20API\x20fallback\x20failed)');}}}case'get_releases':{const G=c['repo'],H=c?.['count']||0x5;if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](G))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');try{const I=execFileSync('gh',['api','repos/'+G+'/releases','--jq','.[0:'+H+']\x20|\x20.[]\x20|\x20{tag_name,\x20name,\x20published_at,\x20html_url}'],{'encoding':'utf-8','timeout':0x2710});return ok(I);}catch{try{const J=await fetch('https://api.github.com/repos/'+G+'/releases?per_page='+H,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)}),K=await J['json'](),L=K['map'](M=>({'tag_name':M['tag_name'],'name':M['name'],'published_at':M['published_at'],'html_url':M['html_url']}));return ok(JSON['stringify'](L,null,0x2));}catch{return err('Failed\x20to\x20fetch\x20releases');}}}case'build_permalink':{const M=c['repo'],N=c['sha'],O=c['path'],P=c?.['start_line'],Q=c?.['end_line'];let R='https://github.com/'+M+'/blob/'+N+'/'+O;return P&&(R+='#L'+P,Q&&Q!==P&&(R+='-L'+Q)),ok(R);}default:return err('Unknown\x20tool:\x20'+b);}}catch(S){return err(S instanceof Error?S['message']:String(S));}});function ok(a){return{'content':[{'type':'text','text':a}]};}function err(a){return{'content':[{'type':'text','text':'Error:\x20'+a}],'isError':!![]};}async function main(){const a=new StdioServerTransport();await server['connect'](a),console['error']('[MCP]\x20Doc\x20Fetcher\x20server\x20started');}main()['catch'](a=>{console['error']('[MCP]\x20Fatal\x20error:',a),process['exit'](0x1);});
2
+ import{Server}from'@modelcontextprotocol/sdk/server/index.js';import{StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import{CallToolRequestSchema,ListToolsRequestSchema}from'@modelcontextprotocol/sdk/types.js';import{execFileSync}from'child_process';import{tmpdir}from'os';import{join}from'path';function isPrivateIp(a){const b=a['replace'](/^\[|\]$/g,'')['toLowerCase']();return b==='0.0.0.0'||b==='::1'||b==='::'||/^127\./['test'](b)||/^10\./['test'](b)||/^192\.168\./['test'](b)||/^169\.254\./['test'](b)||/^172\.(1[6-9]|2\d|3[01])\./['test'](b)||/^(fc|fd)[0-9a-f]{2}:/['test'](b)||/^fe80:/['test'](b)||/^::ffff:127\./['test'](b)||/^::ffff:10\./['test'](b)||/^::ffff:192\.168\./['test'](b)||/^::ffff:169\.254\./['test'](b);}async function assertPublicUrl(a){let b;try{b=new URL(a);}catch{throw new Error('invalid\x20URL:\x20'+a);}if(b['protocol']!=='http:'&&b['protocol']!=='https:')throw new Error('blocked\x20scheme:\x20'+b['protocol']);const c=b['hostname']['replace'](/^\[|\]$/g,'')['toLowerCase'](),d=(process['env']['ROUTINECODE_DOCFETCH_ALLOW_HOSTS']||'')['split'](',')['map'](f=>f['trim']()['toLowerCase']())['filter'](Boolean);if(d['includes'](c))return;if(c==='localhost'||c['endsWith']('.localhost')||isPrivateIp(c))throw new Error('blocked\x20private/link-local\x20host:\x20'+c+'\x20(set\x20ROUTINECODE_DOCFETCH_ALLOW_HOSTS\x20to\x20allow)');const e=/^[0-9.]+$/['test'](c)||c['includes'](':');if(!e){const {lookup:f}=await import('node:dns/promises');let g=[];try{g=await f(c,{'all':!![]});}catch{return;}const h=g['find'](i=>isPrivateIp(i['address']));if(h)throw new Error('blocked:\x20'+c+'\x20resolves\x20to\x20private\x20IP\x20'+h['address']+'\x20(possible\x20DNS\x20rebinding)');}}const server=new Server({'name':'mcp-doc-fetcher','version':'1.0.0'},{'capabilities':{'tools':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>({'tools':[{'name':'crawl_sitemap','description':'Crawl\x20a\x20sitemap.xml\x20and\x20extract\x20all\x20page\x20URLs.\x20Tries\x20/sitemap.xml,\x20/sitemap-0.xml,\x20/docs/sitemap.xml.','inputSchema':{'type':'object','properties':{'base_url':{'type':'string','description':'Base\x20URL\x20of\x20the\x20documentation\x20site'}},'required':['base_url']}},{'name':'fetch_doc_page','description':'Fetch\x20a\x20documentation\x20page\x20and\x20extract\x20text\x20content\x20(strips\x20HTML\x20tags).','inputSchema':{'type':'object','properties':{'url':{'type':'string','description':'URL\x20to\x20fetch'},'max_length':{'type':'number','description':'Max\x20character\x20length\x20(default:\x2010000)'}},'required':['url']}},{'name':'clone_repo_shallow','description':'Shallow\x20clone\x20a\x20GitHub\x20repository\x20to\x20temp\x20directory.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'dest':{'type':'string','description':'Optional\x20destination\x20directory'}},'required':['repo']}},{'name':'search_github_issues','description':'Search\x20GitHub\x20issues\x20and\x20PRs\x20by\x20query.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'query':{'type':'string','description':'Search\x20query'},'state':{'type':'string','enum':['open','closed','all'],'description':'Issue\x20state\x20(default:\x20all)'},'limit':{'type':'number','description':'Max\x20results\x20(default:\x2010)'}},'required':['repo','query']}},{'name':'get_releases','description':'Get\x20recent\x20releases\x20from\x20a\x20GitHub\x20repository.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'count':{'type':'number','description':'Number\x20of\x20releases\x20(default:\x205)'}},'required':['repo']}},{'name':'build_permalink','description':'Build\x20a\x20GitHub\x20permalink\x20URL\x20from\x20repo,\x20SHA,\x20file\x20path,\x20and\x20optional\x20line\x20range.','inputSchema':{'type':'object','properties':{'repo':{'type':'string','description':'Repository\x20in\x20owner/name\x20format'},'sha':{'type':'string','description':'Commit\x20SHA'},'path':{'type':'string','description':'File\x20path\x20within\x20repository'},'start_line':{'type':'number','description':'Start\x20line\x20(optional)'},'end_line':{'type':'number','description':'End\x20line\x20(optional)'}},'required':['repo','sha','path']}}]})),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];try{switch(b){case'crawl_sitemap':{const d=c['base_url']['replace'](/\/$/,''),f=['/sitemap.xml','/sitemap-0.xml','/docs/sitemap.xml','/sitemap_index.xml'];let g=[];await assertPublicUrl(d);for(const h of f){try{const i=await fetch(d+h,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)});if(!i['ok'])continue;const j=await i['text'](),k=/<loc>([^<]+)<\/loc>/g;let l;while((l=k['exec'](j))!==null){g['push'](l[0x1]);}if(g['length']>0x0)break;}catch{continue;}}return ok(JSON['stringify']({'base_url':d,'urls_found':g['length'],'urls':g['slice'](0x0,0x64)},null,0x2));}case'fetch_doc_page':{const m=c['url'],n=c?.['max_length']||0x2710;await assertPublicUrl(m);const o=await fetch(m,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x3a98)});if(!o['ok'])return err('HTTP\x20'+o['status']+':\x20'+o['statusText']);let p=await o['text'](),q=p['replace'](/<script[^>]*>[\s\S]*?<\/script>/gi,'')['replace'](/<style[^>]*>[\s\S]*?<\/style>/gi,'')['replace'](/<nav[^>]*>[\s\S]*?<\/nav>/gi,'')['replace'](/<footer[^>]*>[\s\S]*?<\/footer>/gi,'')['replace'](/<header[^>]*>[\s\S]*?<\/header>/gi,'')['replace'](/<[^>]+>/g,'\x20')['replace'](/&nbsp;/g,'\x20')['replace'](/&amp;/g,'&')['replace'](/&lt;/g,'<')['replace'](/&gt;/g,'>')['replace'](/&quot;/g,'\x22')['replace'](/\s+/g,'\x20')['trim']();return q['length']>n&&(q=q['slice'](0x0,n)+'\x0a...(truncated)'),ok(q);}case'clone_repo_shallow':{const r=c['repo'];if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](r))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');const s=r['split']('/')['pop']()||r,t=c?.['dest']||join(tmpdir(),s);try{execFileSync('git',['clone','--depth','1','https://github.com/'+r+'.git',t],{'timeout':0xea60,'stdio':'pipe'});const u=execFileSync('git',['rev-parse','HEAD'],{'cwd':t,'encoding':'utf-8','timeout':0x1388})['trim']();return ok(JSON['stringify']({'path':t,'sha':u,'repo':r},null,0x2));}catch(v){return err('Clone\x20failed:\x20'+v['message']?.['split']('\x0a')[0x0]);}}case'search_github_issues':{const w=c['repo'],x=c['query'],y=c?.['state']||'all',z=c?.['limit']||0xa;if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](w))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');if(!['open','closed','all']['includes'](y))return err('Invalid\x20state.\x20Expected:\x20open,\x20closed,\x20or\x20all');try{const A=execFileSync('gh',['search','issues',x,'--repo',w,'--state',y,'--limit',String(z),'--json','number,title,state,url,createdAt'],{'encoding':'utf-8','timeout':0x3a98});return ok(A);}catch(B){try{const C='https://api.github.com/search/issues?q='+encodeURIComponent(x+'\x20repo:'+w)+'&per_page='+z,D=await fetch(C,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)}),E=await D['json'](),F=(E['items']||[])['map'](G=>({'number':G['number'],'title':G['title'],'state':G['state'],'url':G['html_url']}));return ok(JSON['stringify'](F,null,0x2));}catch{return err('GitHub\x20search\x20failed\x20(no\x20gh\x20CLI\x20and\x20API\x20fallback\x20failed)');}}}case'get_releases':{const G=c['repo'],H=c?.['count']||0x5;if(!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/['test'](G))return err('Invalid\x20repo\x20format.\x20Expected:\x20owner/name');try{const I=execFileSync('gh',['api','repos/'+G+'/releases','--jq','.[0:'+H+']\x20|\x20.[]\x20|\x20{tag_name,\x20name,\x20published_at,\x20html_url}'],{'encoding':'utf-8','timeout':0x2710});return ok(I);}catch{try{const J=await fetch('https://api.github.com/repos/'+G+'/releases?per_page='+H,{'headers':{'User-Agent':'mcp-doc-fetcher/1.0'},'signal':AbortSignal['timeout'](0x2710)}),K=await J['json'](),L=K['map'](M=>({'tag_name':M['tag_name'],'name':M['name'],'published_at':M['published_at'],'html_url':M['html_url']}));return ok(JSON['stringify'](L,null,0x2));}catch{return err('Failed\x20to\x20fetch\x20releases');}}}case'build_permalink':{const M=c['repo'],N=c['sha'],O=c['path'],P=c?.['start_line'],Q=c?.['end_line'];let R='https://github.com/'+M+'/blob/'+N+'/'+O;return P&&(R+='#L'+P,Q&&Q!==P&&(R+='-L'+Q)),ok(R);}default:return err('Unknown\x20tool:\x20'+b);}}catch(S){return err(S instanceof Error?S['message']:String(S));}});function ok(a){return{'content':[{'type':'text','text':a}]};}function err(a){return{'content':[{'type':'text','text':'Error:\x20'+a}],'isError':!![]};}async function main(){const a=new StdioServerTransport();await server['connect'](a),console['error']('[MCP]\x20Doc\x20Fetcher\x20server\x20started');}main()['catch'](a=>{console['error']('[MCP]\x20Fatal\x20error:',a),process['exit'](0x1);});
@@ -1 +1 @@
1
- import*as a0a from'fs';import*as a0b from'path';import{homedir}from'os';import*as a0c from'crypto';import{embed,cosine}from'./semantic-embedder.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a0b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a0b['join'](ROUTINECODE_DIR,'knowledge'),CONCEPTS_PATH=a0b['join'](KNOWLEDGE_DIR,'concepts.jsonl'),DENOTES_PATH=a0b['join'](KNOWLEDGE_DIR,'denotes.jsonl'),ASSERTIONS_PATH=a0b['join'](KNOWLEDGE_DIR,'assertions.jsonl'),RESOLVE_BIND_THRESHOLD=0.55,DEDUP_THRESHOLD=0.9,PROMOTE_MIN_CONTRIBUTORS=0x2,CANONICAL_BOOST=0.03;export const PREDICATES={'CAUSED_BY':{'domain':['Problem'],'range':['Cause']},'MITIGATED_BY':{'domain':['Problem'],'range':['Fix']},'MANIFESTS_AS':{'domain':['Problem'],'range':['Symptom']},'OCCURS_IN':{'domain':['Problem','Component'],'range':['Component','Library','Domain','Stack']},'PART_OF':{'domain':['Component'],'range':['Component','Capability']},'APPLIES_TO':{'domain':['Fix','Capability'],'range':['Capability','Component']},'AFFECTS':{'domain':['Symptom','Cause'],'range':['Library','Component']},'DEPENDS_ON':{'domain':['*'],'range':['*']},'SUPERSEDES':{'domain':['*'],'range':['*']},'PRECONDITION_OF':{'domain':['*'],'range':['*']},'GOVERNS':{'domain':['Domain'],'range':['Component']}};export function unbindSource(a,b){const d=readJsonl(DENOTES_PATH),e=d['filter'](j=>!(normSourceType(j['sourceType'])===normSourceType(a)&&String(j['sourceId'])===String(b))),f=d['length']-e['length'];if(f===0x0)return 0x0;ensureDir();const g=DENOTES_PATH+'.tmp';a0a['writeFileSync'](g,e['map'](j=>JSON['stringify'](j))['join']('\x0a')+(e['length']?'\x0a':'')),a0a['renameSync'](g,DENOTES_PATH);const h=loadConcepts(),i=new Set(d['filter'](j=>normSourceType(j['sourceType'])===normSourceType(a)&&String(j['sourceId'])===String(b))['map'](j=>j['conceptId']));for(const j of h){if(!i['has'](j['id']))continue;const k=e['filter'](l=>l['conceptId']===j['id']);j['bindingCount']=k['length'],j['distinctContributors']=new Set(k['map'](l=>l['contributorHash']??'local'))['size'];}return rewriteConcepts(h),f;}function trigramSim(c,d){const e=j=>{const k='\x20\x20'+j['toLowerCase']()+'\x20\x20',l=new Set();for(let m=0x0;m<k['length']-0x2;m++)l['add'](k['slice'](m,m+0x3));return l;},f=e(c),g=e(d);if(!f['size']||!g['size'])return 0x0;let h=0x0;for(const i of f)if(g['has'](i))h++;return h/Math['max'](f['size'],g['size']);}export function tokenSim(c,d){const e=i=>new Set(i['toLowerCase']()['replace'](/[^a-z0-9가-힣\s]/g,'\x20')['split'](/\s+/)['filter'](j=>j['length']>0x2)),f=e(c),g=e(d);if(!f['size']||!g['size'])return 0x0;let h=0x0;for(const i of f)if(g['has'](i))h++;return h/Math['max'](f['size'],g['size']);}function sim(c,d){return trigramSim(c,d)*0.4+tokenSim(c,d)*0.6;}function readJsonl(a){try{if(!a0a['existsSync'](a))return[];return a0a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}function ensureDir(){try{a0a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});}catch{}}function append(a,b){ensureDir(),a0a['appendFileSync'](a,JSON['stringify'](b)+'\x0a');}function rewriteConcepts(a){ensureDir();const b=CONCEPTS_PATH+'.tmp';a0a['writeFileSync'](b,a['map'](d=>JSON['stringify'](d))['join']('\x0a')+(a['length']?'\x0a':'')),a0a['renameSync'](b,CONCEPTS_PATH);}function normSourceType(a){return String(a??'')['replace'](/_/g,'-');}export function loadConcepts(){return readJsonl(CONCEPTS_PATH);}export function resolveConcept(a,b){const c=loadConcepts()['filter'](f=>f['status']!=='deprecated'),d=c['filter'](f=>!b?.['kind']||f['type']===b['kind'])['map'](f=>{const g=[f['canonicalName'],...f['aliases']],h=[...g['map'](j=>sim(a,j)),sim(a,f['definition'])*0.7],i=h['reduce']((j,k)=>k>j?k:j,0x0);return{'c':f,'score':i};})['filter'](f=>f['score']>=RESOLVE_BIND_THRESHOLD)['sort']((f,g)=>g['score']+(g['c']['status']==='canonical'?CANONICAL_BOOST:0x0)-(f['score']+(f['c']['status']==='canonical'?CANONICAL_BOOST:0x0)))['slice'](0x0,b?.['limit']??0x5)['map'](f=>({'conceptId':f['c']['id'],'canonicalName':f['c']['canonicalName'],'definition':f['c']['definition'],'type':f['c']['type'],'score':Number(f['score']['toFixed'](0x3)),'status':f['c']['status']})),e=d[0x0];return{'candidates':d,'suggestProposeNew':!e||e['score']<DEDUP_THRESHOLD};}const conceptEmbCache=new Map();function conceptText(a){return a['canonicalName']+'.\x20'+a['definition']+'.\x20'+a['aliases']['join']('.\x20');}function conceptKey(a){return a['id']+':'+a['aliases']['length'];}async function conceptEmbedding(a){const b=conceptKey(a),d=conceptEmbCache['get'](b);if(d)return d;const e=await embed(conceptText(a),'passage');if(e)conceptEmbCache['set'](b,e);return e;}const SEM_CANDIDATE_FLOOR=0.78,SEM_AUTO_MERGE=0.85,SEM_CONFIDENT=0.82;export async function resolveConceptHybrid(a,b){const d=resolveConcept(a,b),e=await embed(a,'query');if(!e)return{...d,'mode':'lexical'};const f=loadConcepts()['filter'](k=>k['status']!=='deprecated'&&(!b?.['kind']||k['type']===b['kind'])),g=new Map(d['candidates']['map'](k=>[k['conceptId'],k['score']])),h=[];for(const k of f){const l=await conceptEmbedding(k);if(!l)continue;const m=cosine(e,l);if(m<SEM_CANDIDATE_FLOOR)continue;const n=g['get'](k['id'])??0x0,o=m*0.7+n*0.3;h['push']({'conceptId':k['id'],'canonicalName':k['canonicalName'],'definition':k['definition'],'type':k['type'],'score':Number(o['toFixed'](0x3)),'status':k['status'],'semScore':Number(m['toFixed'](0x3))});}h['sort']((p,q)=>(q['semScore']??0x0)+(q['status']==='canonical'?CANONICAL_BOOST:0x0)-((p['semScore']??0x0)+(p['status']==='canonical'?CANONICAL_BOOST:0x0)));const i=h['slice'](0x0,b?.['limit']??0x5),j=i[0x0];return{'candidates':i,'suggestProposeNew':!j||(j['semScore']??0x0)<SEM_CONFIDENT,'mode':'semantic'};}function conceptId(a,b){return'C:'+b+':'+a0c['createHash']('sha1')['update'](a['toLowerCase']()['trim']())['digest']('hex')['slice'](0x0,0x8);}export async function proposeConcept(a){const b=await resolveConceptHybrid(a['name']+'.\x20'+a['definition'],{'kind':a['type'],'limit':0x1}),c=b['candidates'][0x0],d=b['mode']==='semantic'?c&&(c['semScore']??0x0)>=SEM_AUTO_MERGE:c&&c['score']>=DEDUP_THRESHOLD;if(d&&c){const i=loadConcepts()['find'](j=>j['id']===c['conceptId']);return a['mention']&&!i['aliases']['includes'](a['mention'])&&(i['aliases']['push'](a['mention']),rewriteConcepts(loadConcepts()['map'](j=>j['id']===i['id']?i:j))),{'concept':i,'created':![]};}const e=conceptId(a['name'],a['type']),f=loadConcepts(),g=f['find'](j=>j['id']===e);if(g)return{'concept':g,'created':![]};const h={'id':e,'canonicalName':a['name'],'definition':a['definition'],'type':a['type'],'layer':a['layer'],'aliases':a['mention']&&a['mention']!==a['name']?[a['mention']]:[],'status':'provisional','bindingCount':0x0,'distinctContributors':0x0,'createdAt':new Date()['toISOString']()};return append(CONCEPTS_PATH,h),{'concept':h,'created':!![]};}export function bindMention(a){const b=loadConcepts(),d=b['find'](f=>f['id']===a['conceptId']);if(!d)return{'bound':![]};append(DENOTES_PATH,{'mentionText':a['text'],'conceptId':a['conceptId'],'sourceType':normSourceType(a['sourceType']),'sourceId':a['sourceId'],'confidence':a['confidence']??0.9,'contributorHash':a['contributorHash']??'local','ts':new Date()['toISOString']()});if(a['text']&&a['text']!==d['canonicalName']&&!d['aliases']['includes'](a['text']))d['aliases']['push'](a['text']);d['bindingCount']+=0x1;const e=new Set(readJsonl(DENOTES_PATH)['filter'](f=>f['conceptId']===a['conceptId'])['map'](f=>f['contributorHash']??'local'));d['distinctContributors']=e['size'];if(d['status']==='provisional'&&d['distinctContributors']>=PROMOTE_MIN_CONTRIBUTORS)d['status']='canonical';return rewriteConcepts(b['map'](f=>f['id']===d['id']?d:f)),{'bound':!![]};}export function recordAssertion(a){const b=PREDICATES[a['p']];if(!b)return{'stored':![],'reason':'unknown\x20predicate\x20\x27'+a['p']+'\x27\x20(통제\x20술어\x20아님)'};const c=loadConcepts(),d=c['find'](k=>k['id']===a['s']),e=c['find'](k=>k['id']===a['o']);if(!d||!e)return{'stored':![],'reason':'concept\x20미존재\x20(I1:\x20근거\x20없는\x20관계\x20금지)'};const f=(k,l)=>k['includes']('*')||k['includes'](l);if(!f(b['domain'],d['type'])||!f(b['range'],e['type']))return{'stored':![],'reason':'타입\x20위반:\x20'+a['p']+'는\x20'+b['domain']+'→'+b['range']+',\x20받은\x20것은\x20'+d['type']+'→'+e['type']};const g=readJsonl(ASSERTIONS_PATH),h=a['s']+'|'+a['p']+'|'+a['o'],i=g['find'](k=>k['s']+'|'+k['p']+'|'+k['o']===h),j=a['contributorHash']??'local';if(i){const k=new Set(i['contributors']??[]);!k['has'](j)&&(k['add'](j),i['weight']=(i['weight']??0x1)+0x1,i['contributors']=[...k],i['distinctContributors']=k['size']);const l=ASSERTIONS_PATH+'.tmp';a0a['writeFileSync'](l,g['map'](m=>JSON['stringify'](m))['join']('\x0a')+'\x0a'),a0a['renameSync'](l,ASSERTIONS_PATH);}else append(ASSERTIONS_PATH,{'s':a['s'],'p':a['p'],'o':a['o'],'weight':0x1,'contributors':[j],'distinctContributors':0x1,'ts':new Date()['toISOString']()});return{'stored':!![]};}export function sourcesForConcept(a){return readJsonl(DENOTES_PATH)['filter'](b=>b['conceptId']===a)['map'](b=>({'sourceType':normSourceType(b['sourceType']),'sourceId':b['sourceId'],'mentionText':b['mentionText']}));}export function conceptsForSource(a,b){return[...new Set(readJsonl(DENOTES_PATH)['filter'](c=>normSourceType(c['sourceType'])===normSourceType(a)&&String(c['sourceId'])===String(b))['map'](c=>c['conceptId']))];}export function auditConcept(a){const b=loadConcepts()['find'](d=>d['id']===a),c=readJsonl(DENOTES_PATH)['filter'](e=>e['conceptId']===a);return{'concept':b,'mentions':c,'contributors':[...new Set(c['map'](d=>d['contributorHash']??'local'))]};}export function relatedConcepts(b,c){const d=c?.['maxHops']??0x1,f=c?.['preds']??['GOVERNS','MITIGATED_BY','CAUSED_BY','DEPENDS_ON','OCCURS_IN','PART_OF','APPLIES_TO','AFFECTS'],g=c?.['minWeight']??0x1,h=readJsonl(ASSERTIONS_PATH)['filter'](n=>f['includes'](n['p'])&&(n['weight']??0x1)>=g),i=new Map(),j=(n,o,q,r)=>{if(!i['has'](n))i['set'](n,[]);i['get'](n)['push']({'to':o,'p':q,'w':r});};for(const n of h){const o=n['distinctContributors']??n['weight']??0x1;j(n['s'],n['o'],n['p'],o),j(n['o'],n['s'],n['p'],o);}const k=new Set(b),l=[];let m=[...b];for(let p=0x1;p<=d;p++){const q=[];for(const r of m){for(const s of i['get'](r)??[]){if(k['has'](s['to']))continue;k['add'](s['to']),l['push']({'conceptId':s['to'],'distance':p,'viaPredicate':s['p'],'weight':s['w']}),q['push'](s['to']);}}m=q;if(!m['length'])break;}return l;}export async function retrieveByContext(a){const b=a['limit']??0x8,c=a['query']??a['file']??a['errorSignature']??a['library']??'',d=new Map(),e=(i,j)=>normSourceType(i)+':'+j,f=(i,j,l,m)=>{const n=e(i,j),o=d['get'](n);if(o){o['score']+=l;if(m==='flat')o['via']='flat';}else d['set'](n,{'sourceType':normSourceType(i),'sourceId':j,'score':l,'via':m});},g=0x2;for(const i of a['flatHits']??[])f(i['sourceType'],i['sourceId'],g,'flat');if(c){let j=[];try{const l=await resolveConceptHybrid(c,{'kind':a['kind'],'limit':0x5});j=l['candidates']['map'](m=>({'conceptId':m['conceptId'],'score':m['score']}));}catch{j=[];}for(const m of j){for(const n of sourcesForConcept(m['conceptId']))f(n['sourceType'],n['sourceId'],0x1*(m['score']||0.5),'concept');}const k=relatedConcepts(j['map'](o=>o['conceptId']),{'maxHops':0x1});for(const o of k){const p=0x1/(0x1+o['distance']),q=Math['min'](0x1,(o['weight']||0x1)/0x3);for(const t of sourcesForConcept(o['conceptId']))f(t['sourceType'],t['sourceId'],0.6*p*q,'assertion');}}return[...d['values']()]['sort']((u,v)=>v['score']-u['score'])['slice'](0x0,b);}
1
+ import*as a0a from'fs';import*as a0b from'path';import{homedir}from'os';import*as a0c from'crypto';import{embed,cosine}from'./semantic-embedder.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a0b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']??a0b['join'](ROUTINECODE_DIR,'knowledge'),CONCEPTS_PATH=a0b['join'](KNOWLEDGE_DIR,'concepts.jsonl'),DENOTES_PATH=a0b['join'](KNOWLEDGE_DIR,'denotes.jsonl'),ASSERTIONS_PATH=a0b['join'](KNOWLEDGE_DIR,'assertions.jsonl'),RESOLVE_BIND_THRESHOLD=0.55,DEDUP_THRESHOLD=0.9,PROMOTE_MIN_CONTRIBUTORS=0x2,CANONICAL_BOOST=0.03;export const PREDICATES={'CAUSED_BY':{'domain':['Problem'],'range':['Cause']},'MITIGATED_BY':{'domain':['Problem'],'range':['Fix']},'MANIFESTS_AS':{'domain':['Problem'],'range':['Symptom']},'OCCURS_IN':{'domain':['Problem','Component'],'range':['Component','Library','Domain','Stack']},'PART_OF':{'domain':['Component'],'range':['Component','Capability']},'APPLIES_TO':{'domain':['Fix','Capability'],'range':['Capability','Component']},'AFFECTS':{'domain':['Symptom','Cause'],'range':['Library','Component']},'DEPENDS_ON':{'domain':['*'],'range':['*']},'SUPERSEDES':{'domain':['*'],'range':['*']},'PRECONDITION_OF':{'domain':['*'],'range':['*']},'GOVERNS':{'domain':['Domain'],'range':['Component']}};export function unbindSource(a,b){const d=readJsonl(DENOTES_PATH),e=d['filter'](j=>!(normSourceType(j['sourceType'])===normSourceType(a)&&String(j['sourceId'])===String(b))),f=d['length']-e['length'];if(f===0x0)return 0x0;ensureDir();const g=DENOTES_PATH+'.tmp';a0a['writeFileSync'](g,e['map'](j=>JSON['stringify'](j))['join']('\x0a')+(e['length']?'\x0a':'')),a0a['renameSync'](g,DENOTES_PATH);const h=loadConcepts(),i=new Set(d['filter'](j=>normSourceType(j['sourceType'])===normSourceType(a)&&String(j['sourceId'])===String(b))['map'](j=>j['conceptId']));for(const j of h){if(!i['has'](j['id']))continue;const k=e['filter'](l=>l['conceptId']===j['id']);j['bindingCount']=k['length'],j['distinctContributors']=new Set(k['map'](l=>l['contributorHash']??'local'))['size'];}return rewriteConcepts(h),f;}function trigramSim(c,d){const e=j=>{const k='\x20\x20'+j['toLowerCase']()+'\x20\x20',l=new Set();for(let m=0x0;m<k['length']-0x2;m++)l['add'](k['slice'](m,m+0x3));return l;},f=e(c),g=e(d);if(!f['size']||!g['size'])return 0x0;let h=0x0;for(const i of f)if(g['has'](i))h++;return h/Math['max'](f['size'],g['size']);}export function tokenSim(c,d){const e=i=>new Set(i['toLowerCase']()['replace'](/[^a-z0-9가-힣\s]/g,'\x20')['split'](/\s+/)['filter'](j=>j['length']>0x2)),f=e(c),g=e(d);if(!f['size']||!g['size'])return 0x0;let h=0x0;for(const i of f)if(g['has'](i))h++;return h/Math['max'](f['size'],g['size']);}function sim(c,d){return trigramSim(c,d)*0.4+tokenSim(c,d)*0.6;}function readJsonl(a){try{if(!a0a['existsSync'](a))return[];return a0a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}function ensureDir(){try{a0a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});}catch{}}function append(a,b){ensureDir(),a0a['appendFileSync'](a,JSON['stringify'](b)+'\x0a');}function rewriteConcepts(a){ensureDir();const b=CONCEPTS_PATH+'.tmp';a0a['writeFileSync'](b,a['map'](d=>JSON['stringify'](d))['join']('\x0a')+(a['length']?'\x0a':'')),a0a['renameSync'](b,CONCEPTS_PATH);}function normSourceType(a){return String(a??'')['replace'](/_/g,'-');}export function loadConcepts(){return readJsonl(CONCEPTS_PATH);}export function resolveConcept(a,b){const c=loadConcepts()['filter'](f=>f['status']!=='deprecated'),d=c['filter'](f=>!b?.['kind']||f['type']===b['kind'])['map'](f=>{const g=[f['canonicalName'],...f['aliases']],h=[...g['map'](j=>sim(a,j)),sim(a,f['definition'])*0.7],i=h['reduce']((j,k)=>k>j?k:j,0x0);return{'c':f,'score':i};})['filter'](f=>f['score']>=RESOLVE_BIND_THRESHOLD)['sort']((f,g)=>g['score']+(g['c']['status']==='canonical'?CANONICAL_BOOST:0x0)-(f['score']+(f['c']['status']==='canonical'?CANONICAL_BOOST:0x0)))['slice'](0x0,b?.['limit']??0x5)['map'](f=>({'conceptId':f['c']['id'],'canonicalName':f['c']['canonicalName'],'definition':f['c']['definition'],'type':f['c']['type'],'score':Number(f['score']['toFixed'](0x3)),'status':f['c']['status']})),e=d[0x0];return{'candidates':d,'suggestProposeNew':!e||e['score']<DEDUP_THRESHOLD};}const conceptEmbCache=new Map();function conceptText(a){return a['canonicalName']+'.\x20'+a['definition']+'.\x20'+a['aliases']['join']('.\x20');}function conceptKey(a){return a['id']+':'+a['aliases']['length'];}async function conceptEmbedding(a){const b=conceptKey(a),d=conceptEmbCache['get'](b);if(d)return d;const e=await embed(conceptText(a),'passage');if(e)conceptEmbCache['set'](b,e);return e;}const SEM_CANDIDATE_FLOOR=0.78,SEM_AUTO_MERGE=0.85,SEM_CONFIDENT=0.82;export async function resolveConceptHybrid(a,b){const d=resolveConcept(a,b),e=await embed(a,'query');if(!e)return{...d,'mode':'lexical'};const f=loadConcepts()['filter'](k=>k['status']!=='deprecated'&&(!b?.['kind']||k['type']===b['kind'])),g=new Map(d['candidates']['map'](k=>[k['conceptId'],k['score']])),h=[];for(const k of f){const l=await conceptEmbedding(k);if(!l)continue;const m=cosine(e,l);if(m<SEM_CANDIDATE_FLOOR)continue;const n=g['get'](k['id'])??0x0,o=m*0.7+n*0.3;h['push']({'conceptId':k['id'],'canonicalName':k['canonicalName'],'definition':k['definition'],'type':k['type'],'score':Number(o['toFixed'](0x3)),'status':k['status'],'semScore':Number(m['toFixed'](0x3))});}h['sort']((p,q)=>(q['semScore']??0x0)+(q['status']==='canonical'?CANONICAL_BOOST:0x0)-((p['semScore']??0x0)+(p['status']==='canonical'?CANONICAL_BOOST:0x0)));const i=h['slice'](0x0,b?.['limit']??0x5),j=i[0x0];return{'candidates':i,'suggestProposeNew':!j||(j['semScore']??0x0)<SEM_CONFIDENT,'mode':'semantic'};}function conceptId(a,b){return'C:'+b+':'+a0c['createHash']('sha1')['update'](a['toLowerCase']()['trim']())['digest']('hex')['slice'](0x0,0x8);}export async function proposeConcept(a){const b=await resolveConceptHybrid(a['name']+'.\x20'+a['definition'],{'kind':a['type'],'limit':0x1}),c=b['candidates'][0x0],d=b['mode']==='semantic'?c&&(c['semScore']??0x0)>=SEM_AUTO_MERGE:c&&c['score']>=DEDUP_THRESHOLD;if(d&&c){const i=loadConcepts()['find'](j=>j['id']===c['conceptId']);return a['mention']&&!i['aliases']['includes'](a['mention'])&&(i['aliases']['push'](a['mention']),rewriteConcepts(loadConcepts()['map'](j=>j['id']===i['id']?i:j))),{'concept':i,'created':![]};}const e=conceptId(a['name'],a['type']),f=loadConcepts(),g=f['find'](j=>j['id']===e);if(g)return{'concept':g,'created':![]};const h={'id':e,'canonicalName':a['name'],'definition':a['definition'],'type':a['type'],'layer':a['layer'],'aliases':a['mention']&&a['mention']!==a['name']?[a['mention']]:[],'status':'provisional','bindingCount':0x0,'distinctContributors':0x0,'createdAt':new Date()['toISOString']()};return append(CONCEPTS_PATH,h),{'concept':h,'created':!![]};}export function bindMention(a){const b=loadConcepts(),d=b['find'](f=>f['id']===a['conceptId']);if(!d)return{'bound':![]};append(DENOTES_PATH,{'mentionText':a['text'],'conceptId':a['conceptId'],'sourceType':normSourceType(a['sourceType']),'sourceId':a['sourceId'],'confidence':a['confidence']??0.9,'contributorHash':a['contributorHash']??'local','ts':new Date()['toISOString']()});if(a['text']&&a['text']!==d['canonicalName']&&!d['aliases']['includes'](a['text']))d['aliases']['push'](a['text']);d['bindingCount']+=0x1;const e=new Set(readJsonl(DENOTES_PATH)['filter'](f=>f['conceptId']===a['conceptId'])['map'](f=>f['contributorHash']??'local'));d['distinctContributors']=e['size'];if(d['status']==='provisional'&&d['distinctContributors']>=PROMOTE_MIN_CONTRIBUTORS)d['status']='canonical';return rewriteConcepts(b['map'](f=>f['id']===d['id']?d:f)),{'bound':!![]};}export function recordAssertion(a){const b=PREDICATES[a['p']];if(!b)return{'stored':![],'reason':'unknown\x20predicate\x20\x27'+a['p']+'\x27\x20(통제\x20술어\x20아님)'};const c=loadConcepts(),d=c['find'](k=>k['id']===a['s']),e=c['find'](k=>k['id']===a['o']);if(!d||!e)return{'stored':![],'reason':'concept\x20미존재\x20(I1:\x20근거\x20없는\x20관계\x20금지)'};const f=(k,l)=>k['includes']('*')||k['includes'](l);if(!f(b['domain'],d['type'])||!f(b['range'],e['type']))return{'stored':![],'reason':'타입\x20위반:\x20'+a['p']+'는\x20'+b['domain']+'→'+b['range']+',\x20받은\x20것은\x20'+d['type']+'→'+e['type']};const g=readJsonl(ASSERTIONS_PATH),h=a['s']+'|'+a['p']+'|'+a['o'],i=g['find'](k=>k['s']+'|'+k['p']+'|'+k['o']===h),j=a['contributorHash']??'local';if(i){const k=new Set(i['contributors']??[]);!k['has'](j)&&(k['add'](j),i['weight']=(i['weight']??0x1)+0x1,i['contributors']=[...k],i['distinctContributors']=k['size']);const l=ASSERTIONS_PATH+'.tmp';a0a['writeFileSync'](l,g['map'](m=>JSON['stringify'](m))['join']('\x0a')+'\x0a'),a0a['renameSync'](l,ASSERTIONS_PATH);}else append(ASSERTIONS_PATH,{'s':a['s'],'p':a['p'],'o':a['o'],'weight':0x1,'contributors':[j],'distinctContributors':0x1,'ts':new Date()['toISOString']()});return{'stored':!![]};}export function sourcesForConcept(a){return readJsonl(DENOTES_PATH)['filter'](b=>b['conceptId']===a)['map'](b=>({'sourceType':normSourceType(b['sourceType']),'sourceId':b['sourceId'],'mentionText':b['mentionText']}));}export function conceptsForSource(a,b){return[...new Set(readJsonl(DENOTES_PATH)['filter'](c=>normSourceType(c['sourceType'])===normSourceType(a)&&String(c['sourceId'])===String(b))['map'](c=>c['conceptId']))];}export function auditConcept(a){const b=loadConcepts()['find'](d=>d['id']===a),c=readJsonl(DENOTES_PATH)['filter'](e=>e['conceptId']===a);return{'concept':b,'mentions':c,'contributors':[...new Set(c['map'](d=>d['contributorHash']??'local'))]};}export function relatedConcepts(b,c){const d=c?.['maxHops']??0x1,f=c?.['preds']??['GOVERNS','MITIGATED_BY','CAUSED_BY','DEPENDS_ON','OCCURS_IN','PART_OF','APPLIES_TO','AFFECTS'],g=c?.['minWeight']??0x1,h=readJsonl(ASSERTIONS_PATH)['filter'](n=>f['includes'](n['p'])&&(n['weight']??0x1)>=g),i=new Map(),j=(n,o,q,r)=>{if(!i['has'](n))i['set'](n,[]);i['get'](n)['push']({'to':o,'p':q,'w':r});};for(const n of h){const o=n['distinctContributors']??n['weight']??0x1;j(n['s'],n['o'],n['p'],o),j(n['o'],n['s'],n['p'],o);}const k=new Set(b),l=[];let m=[...b];for(let p=0x1;p<=d;p++){const q=[];for(const r of m){for(const s of i['get'](r)??[]){if(k['has'](s['to']))continue;k['add'](s['to']),l['push']({'conceptId':s['to'],'distance':p,'viaPredicate':s['p'],'weight':s['w']}),q['push'](s['to']);}}m=q;if(!m['length'])break;}return l;}export async function retrieveByContext(a){const b=a['limit']??0x8,c=a['query']??a['file']??a['errorSignature']??a['library']??'',d=new Map(),e=(i,j)=>normSourceType(i)+':'+j,f=(i,j,l,m)=>{const n=e(i,j),o=d['get'](n);if(o){o['score']+=l;if(m==='flat')o['via']='flat';}else d['set'](n,{'sourceType':normSourceType(i),'sourceId':j,'score':l,'via':m});},g=0x2;for(const i of a['flatHits']??[])f(i['sourceType'],i['sourceId'],g,'flat');if(c){let j=[];try{const l=await resolveConceptHybrid(c,{'kind':a['kind'],'limit':0x5});j=l['candidates']['map'](m=>({'conceptId':m['conceptId'],'score':m['score']}));}catch{j=[];}for(const m of j){for(const n of sourcesForConcept(m['conceptId']))f(n['sourceType'],n['sourceId'],0x1*(m['score']||0.5),'concept');}const k=relatedConcepts(j['map'](o=>o['conceptId']),{'maxHops':0x1});for(const o of k){const p=0x1/(0x1+o['distance']),q=Math['min'](0x1,(o['weight']||0x1)/0x3);for(const t of sourcesForConcept(o['conceptId']))f(t['sourceType'],t['sourceId'],0.6*p*q,'assertion');}}return[...d['values']()]['sort']((u,v)=>v['score']-u['score'])['slice'](0x0,b);}
@@ -1 +1 @@
1
- import*as a1a from'fs';import*as a1b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{PATH_PLACEHOLDER,logTransmission,queueAllowed,sanitizeDeep,sanitizeText}from'./sanitize.generated.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a1b['join'](homedir(),'.routinecode'),CONFIG_PATH=process.env.ROUTINECODE_CONFIG_PATH??a1b['join'](ROUTINECODE_DIR,'config.json'),TIMEOUT_MS=0x4b0;function loadConfig(){try{return JSON['parse'](a1a['readFileSync'](CONFIG_PATH,'utf-8'));}catch{return{};}}export function serverOntologyEnabled(){if(process.env.ROUTINECODE_KI_ONTOLOGY_SERVER==='off')return![];const a=loadConfig();return!!(a['serverUrl']&&a['apiKey']&&queueAllowed(a));}async function call(a,b){const d=loadConfig();if(!d['serverUrl']||!d['apiKey']||!queueAllowed(d))return null;try{const e=sanitizeDeep(b),f=d['serverUrl']['replace'](/\/$/,'')+'/api/v1/concept/'+a;logTransmission(f,e);const g=await fetch(f,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+d['apiKey']},'body':JSON['stringify'](e),'signal':AbortSignal['timeout'](TIMEOUT_MS)});if(!g['ok'])return noteAuthFailure(g['status']),null;const h=await g['json']();return h['data']??null;}catch{return null;}}export async function serverResolve(a,b){return call('resolve',{'mention':a,'kind':b});}const COMPONENT_PREFIX='component:';function isFileDerived(a){if(typeof a!=='string')return![];return a['startsWith'](COMPONENT_PREFIX)||sanitizeText(a)['trim']()===PATH_PLACEHOLDER;}export function groundPayloadForServer(a){const b=a['mentions']['filter'](d=>{const e=d;return!isFileDerived(e['text'])&&!isFileDerived(e['proposeNew']?.['name']);}),c=a['assertions']?.['filter'](d=>{const e=d;return!isFileDerived(e['s'])&&!isFileDerived(e['o']);});return{...a,'mentions':b,...c?{'assertions':c}:{}};}export async function serverGround(a){const b=groundPayloadForServer(a);if(b['mentions']['length']===0x0)return null;return call('ground',b);}
1
+ import*as a1a from'fs';import*as a1b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{PATH_PLACEHOLDER,logTransmission,queueAllowed,sanitizeDeep,sanitizeText}from'./sanitize.generated.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a1b['join'](homedir(),'.routinecode'),CONFIG_PATH=process['env']['ROUTINECODE_CONFIG_PATH']??a1b['join'](ROUTINECODE_DIR,'config.json'),TIMEOUT_MS=0x4b0;function loadConfig(){try{return JSON['parse'](a1a['readFileSync'](CONFIG_PATH,'utf-8'));}catch{return{};}}export function serverOntologyEnabled(){if(process['env']['ROUTINECODE_KI_ONTOLOGY_SERVER']==='off')return![];const a=loadConfig();return!!(a['serverUrl']&&a['apiKey']&&queueAllowed(a));}async function call(a,b){const d=loadConfig();if(!d['serverUrl']||!d['apiKey']||!queueAllowed(d))return null;try{const e=sanitizeDeep(b),f=d['serverUrl']['replace'](/\/$/,'')+'/api/v1/concept/'+a;logTransmission(f,e);const g=await fetch(f,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+d['apiKey']},'body':JSON['stringify'](e),'signal':AbortSignal['timeout'](TIMEOUT_MS)});if(!g['ok'])return noteAuthFailure(g['status']),null;const h=await g['json']();return h['data']??null;}catch{return null;}}export async function serverResolve(a,b){return call('resolve',{'mention':a,'kind':b});}const COMPONENT_PREFIX='component:';function isFileDerived(a){if(typeof a!=='string')return![];return a['startsWith'](COMPONENT_PREFIX)||sanitizeText(a)['trim']()===PATH_PLACEHOLDER;}export function groundPayloadForServer(a){const b=a['mentions']['filter'](d=>{const e=d;return!isFileDerived(e['text'])&&!isFileDerived(e['proposeNew']?.['name']);}),c=a['assertions']?.['filter'](d=>{const e=d;return!isFileDerived(e['s'])&&!isFileDerived(e['o']);});return{...a,'mentions':b,...c?{'assertions':c}:{}};}export async function serverGround(a){const b=groundPayloadForServer(a);if(b['mentions']['length']===0x0)return null;return call('ground',b);}
@@ -1 +1 @@
1
- import*as a2a from'fs';import*as a2b from'path';import{homedir}from'os';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a2b['join'](homedir(),'.routinecode'),CONFIG_PATH=process.env.ROUTINECODE_CONFIG_PATH??a2b['join'](ROUTINECODE_DIR,'config.json');export function noteAuthFailure(a){if(a!==0x191)return;try{const b=a2a['readFileSync'](CONFIG_PATH,'utf-8'),c=JSON['parse'](b);if(!c['apiKey'])return;delete c['apiKey'],c['apiKeyInvalidatedAt']=new Date()['toISOString'](),c['apiKeyInvalidReason']='401';const d=CONFIG_PATH+'.tmp.'+process['pid'];a2a['writeFileSync'](d,JSON['stringify'](c,null,0x2)),a2a['renameSync'](d,CONFIG_PATH),console['error']('[mcp-intelligence]\x20apiKey\x20invalidated\x20(401)\x20—\x20next\x20session-start\x20will\x20re-provision');}catch{}}
1
+ import*as a2a from'fs';import*as a2b from'path';import{homedir}from'os';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a2b['join'](homedir(),'.routinecode'),CONFIG_PATH=process['env']['ROUTINECODE_CONFIG_PATH']??a2b['join'](ROUTINECODE_DIR,'config.json');export function noteAuthFailure(a){if(a!==0x191)return;try{const b=a2a['readFileSync'](CONFIG_PATH,'utf-8'),c=JSON['parse'](b);if(!c['apiKey'])return;delete c['apiKey'],c['apiKeyInvalidatedAt']=new Date()['toISOString'](),c['apiKeyInvalidReason']='401';const d=CONFIG_PATH+'.tmp.'+process['pid'];a2a['writeFileSync'](d,JSON['stringify'](c,null,0x2)),a2a['renameSync'](d,CONFIG_PATH),console['error']('[mcp-intelligence]\x20apiKey\x20invalidated\x20(401)\x20—\x20next\x20session-start\x20will\x20re-provision');}catch{}}
@@ -1 +1 @@
1
- import*as a3a from'fs';import*as a3b from'path';import{homedir}from'os';export function knowledgeDir(){return process.env.ROUTINECODE_KNOWLEDGE_DIR||a3b['join'](process.env.ROUTINECODE_DIR||a3b['join'](homedir(),'.routinecode'),'knowledge');}export function knowledgePath(a){return a3b['join'](knowledgeDir(),a);}export const FILES={'EVENTS':'events.jsonl','PATTERNS':'patterns.jsonl','QUIRKS':'quirks.jsonl','DOMAIN_KNOWLEDGE':'domain-knowledge.jsonl','DECISIONS':'decisions.jsonl','CONCEPTS':'concepts.jsonl','DENOTES':'denotes.jsonl','ASSERTIONS':'assertions.jsonl'};export const SOURCE={'ERROR_FIX':'error-fix','PATTERN':'pattern','QUIRK':'quirk','DOMAIN_KNOWLEDGE':'domain-knowledge'};const s=a=>String(a??'');export function errorFixSourceId(a,b,c){return'ef:'+(s(a)||'unknown')+':'+(s(b)||s(c));}export function patternSourceId(a,b){return'pt:'+s(a)+':'+s(b);}export function quirkSourceId(a,b){return'qk:'+s(a)+':'+s(b);}export function domainKnowledgeSourceId(a,b){return'dk:'+s(a)+':'+s(b);}export function readJsonl(a){try{if(!a3a['existsSync'](a))return[];return a3a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}export function readDenotes(){return readJsonl(knowledgePath(FILES['DENOTES']));}export function readDomainKnowledge(){return readJsonl(knowledgePath(FILES['DOMAIN_KNOWLEDGE']));}export function relatedSourceIds(a,b,c,d){return new Set(a['filter'](e=>b['has'](e['conceptId'])&&e['sourceType']===c&&e['sourceId']&&!d['has'](e['sourceId']))['map'](e=>e['sourceId']));}
1
+ import*as a3a from'fs';import*as a3b from'path';import{homedir}from'os';export function knowledgeDir(){return process['env']['ROUTINECODE_KNOWLEDGE_DIR']||a3b['join'](process['env']['ROUTINECODE_DIR']||a3b['join'](homedir(),'.routinecode'),'knowledge');}export function knowledgePath(a){return a3b['join'](knowledgeDir(),a);}export const FILES={'EVENTS':'events.jsonl','PATTERNS':'patterns.jsonl','QUIRKS':'quirks.jsonl','DOMAIN_KNOWLEDGE':'domain-knowledge.jsonl','DECISIONS':'decisions.jsonl','CONCEPTS':'concepts.jsonl','DENOTES':'denotes.jsonl','ASSERTIONS':'assertions.jsonl'};export const SOURCE={'ERROR_FIX':'error-fix','PATTERN':'pattern','QUIRK':'quirk','DOMAIN_KNOWLEDGE':'domain-knowledge'};const s=a=>String(a??'');export function errorFixSourceId(a,b,c){return'ef:'+(s(a)||'unknown')+':'+(s(b)||s(c));}export function patternSourceId(a,b){return'pt:'+s(a)+':'+s(b);}export function quirkSourceId(a,b){return'qk:'+s(a)+':'+s(b);}export function domainKnowledgeSourceId(a,b){return'dk:'+s(a)+':'+s(b);}export function readJsonl(a){try{if(!a3a['existsSync'](a))return[];return a3a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}export function readDenotes(){return readJsonl(knowledgePath(FILES['DENOTES']));}export function readDomainKnowledge(){return readJsonl(knowledgePath(FILES['DOMAIN_KNOWLEDGE']));}export function relatedSourceIds(a,b,c,d){return new Set(a['filter'](e=>b['has'](e['conceptId'])&&e['sourceType']===c&&e['sourceId']&&!d['has'](e['sourceId']))['map'](e=>e['sourceId']));}
@@ -1 +1 @@
1
- import*as a5a from'fs';import*as a5b from'path';import{homedir}from'os';import{tokenSim}from'./concept-catalog.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a5b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a5b['join'](ROUTINECODE_DIR,'knowledge'),OBSERVED_DIR=a5b['join'](KNOWLEDGE_DIR,'observed');export function gateEnabled(){return process.env.ROUTINECODE_KI_GATE==='on';}export function loadResolvedDraftById(a){try{if(!a5a['existsSync'](OBSERVED_DIR))return null;for(const b of a5a['readdirSync'](OBSERVED_DIR)){if(!b['startsWith']('draft-')||!b['endsWith']('.json'))continue;try{const c=JSON['parse'](a5a['readFileSync'](a5b['join'](OBSERVED_DIR,b),'utf-8'));if(c['draftId']===a)return c;}catch{}}}catch{}return null;}export function verifyFilesExist(a,b){const c=[],d=[];for(const e of a??[]){const g=[e];if(b&&!a5b['isAbsolute'](e))g['push'](a5b['join'](b,e));if(g['some'](h=>{try{return a5a['existsSync'](h);}catch{return![];}}))c['push'](e);else d['push'](e);}return{'valid':c,'invalid':d};}export function detectProjectMeta(a){let b=a;for(let c=0x0;c<0x3&&b;c++){try{const e=JSON['parse'](a5a['readFileSync'](a5b['join'](b,'package.json'),'utf-8')),f=Object['keys']({...e['dependencies'],...e['devDependencies']}),g=f['filter'](h=>/express|next|react|sequelize|fastify|nestjs|vue|svelte|prisma|typeorm|celery/i['test'](h));return{'domain':e['name']?String(e['name'])['replace'](/^@[^/]+\//,''):a5b['basename'](a),'stack':g['slice'](0x0,0x4)['join'](',')||'unknown'};}catch{}const d=a5b['dirname'](b);if(d===b)break;b=d;}return{'domain':a5b['basename'](a)||'unknown','stack':'unknown'};}export function gateErrorFix(a){if(!gateEnabled()){if(!a['draftId'])return{'ok':!![]};const f=loadResolvedDraftById(a['draftId']);if(!f||!f['resolvedAt'])return{'ok':!![]};if(a['project']&&f['project']&&a['project']!==f['project'])return{'ok':!![]};const g=detectProjectMeta(f['directory']);return{'ok':!![],'observed':{'errorSignature':f['errorSignature'],'attempts':f['attempts'],'files':verifyFilesExist(f['editedFiles'],f['directory'])['valid'],'domain':g['domain'],'stack':g['stack'],'project':f['project'],'type':f['type']}};}if(!a['draftId'])return{'ok':![],'reason':'REJECTED:\x20draftId\x20required.\x20Error\x20fixes\x20can\x20only\x20be\x20recorded\x20for\x20errors\x20this\x20system\x20observed\x20(see\x20the\x20[KNOWLEDGE-RECORD]\x20directive\x20in\x20the\x20build_check\x20output).\x20If\x20no\x20directive\x20was\x20shown,\x20skip\x20the\x20record\x20and\x20continue.'};const b=loadResolvedDraftById(a['draftId']);if(!b)return{'ok':![],'reason':'REJECTED:\x20no\x20observed\x20draft\x20for\x20draftId\x20\x27'+a['draftId']+'\x27.\x20Do\x20not\x20fabricate\x20a\x20draftId\x20—\x20skip\x20the\x20record.'};if(!b['resolvedAt'])return{'ok':![],'reason':'REJECTED:\x20draft\x20\x27'+a['draftId']+'\x27\x20is\x20not\x20resolved\x20(error\x20not\x20yet\x20fixed).'};if(a['project']&&b['project']&&a['project']!==b['project'])return{'ok':![],'reason':'REJECTED:\x20draftId\x20\x27'+a['draftId']+'\x27\x20belongs\x20to\x20a\x20different\x20project.'};const c=detectProjectMeta(b['directory']),{valid:e}=verifyFilesExist(b['editedFiles'],b['directory']);return{'ok':!![],'observed':{'errorSignature':b['errorSignature'],'attempts':b['attempts'],'files':e,'domain':c['domain'],'stack':c['stack'],'project':b['project'],'type':b['type']}};}const NOVELTY_THRESHOLD=0.6,similarity=tokenSim;function loadClaudeMdChunks(a){const b=[],e=[];if(a){let f=a;for(let g=0x0;g<0x4&&f;g++){e['push'](a5b['join'](f,'CLAUDE.md'));const h=a5b['dirname'](f);if(h===f)break;f=h;}}for(const j of e){try{const k=a5a['readFileSync'](j,'utf-8');k['split'](/\n\s*\n/)['forEach'](l=>{if(l['trim']()['length']>0x28)b['push'](l['trim']());});}catch{}}return b;}export function gateNovelty(a,b){if(!gateEnabled())return{'ok':!![]};if(!a||a['trim']()['length']<0x14)return{'ok':!![]};const c=loadClaudeMdChunks(b);for(const d of c){if(similarity(a,d)>=NOVELTY_THRESHOLD)return{'ok':![],'reason':'REJECTED:\x20already\x20documented\x20in\x20CLAUDE.md\x20—\x20knowledge\x20store\x20is\x20for\x20non-derivable\x20facts\x20only.'};}return{'ok':!![]};}export function gatePattern(a){if(!gateEnabled())return{'ok':!![]};const b=a['files']??[];if(b['length']===0x0)return{'ok':![],'reason':'REJECTED:\x20pattern\x20requires\x20at\x20least\x20one\x20existing\x20file\x20anchor\x20(files[]).\x20Knowledge\x20store\x20is\x20for\x20grounded\x20facts.'};const {valid:c,invalid:d}=verifyFilesExist(b);if(c['length']===0x0)return{'ok':![],'reason':'REJECTED:\x20none\x20of\x20the\x20referenced\x20files\x20exist:\x20'+d['join'](',\x20')};return{'ok':!![],'validFiles':c,'warning':d['length']>0x0?'Dropped\x20non-existent\x20file\x20refs:\x20'+d['join'](',\x20'):undefined};}
1
+ import*as a5a from'fs';import*as a5b from'path';import{homedir}from'os';import{tokenSim}from'./concept-catalog.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a5b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']??a5b['join'](ROUTINECODE_DIR,'knowledge'),OBSERVED_DIR=a5b['join'](KNOWLEDGE_DIR,'observed');export function gateEnabled(){return process['env']['ROUTINECODE_KI_GATE']==='on';}export function loadResolvedDraftById(a){try{if(!a5a['existsSync'](OBSERVED_DIR))return null;for(const b of a5a['readdirSync'](OBSERVED_DIR)){if(!b['startsWith']('draft-')||!b['endsWith']('.json'))continue;try{const c=JSON['parse'](a5a['readFileSync'](a5b['join'](OBSERVED_DIR,b),'utf-8'));if(c['draftId']===a)return c;}catch{}}}catch{}return null;}export function verifyFilesExist(a,b){const c=[],d=[];for(const e of a??[]){const g=[e];if(b&&!a5b['isAbsolute'](e))g['push'](a5b['join'](b,e));if(g['some'](h=>{try{return a5a['existsSync'](h);}catch{return![];}}))c['push'](e);else d['push'](e);}return{'valid':c,'invalid':d};}export function detectProjectMeta(a){let b=a;for(let c=0x0;c<0x3&&b;c++){try{const e=JSON['parse'](a5a['readFileSync'](a5b['join'](b,'package.json'),'utf-8')),f=Object['keys']({...e['dependencies'],...e['devDependencies']}),g=f['filter'](h=>/express|next|react|sequelize|fastify|nestjs|vue|svelte|prisma|typeorm|celery/i['test'](h));return{'domain':e['name']?String(e['name'])['replace'](/^@[^/]+\//,''):a5b['basename'](a),'stack':g['slice'](0x0,0x4)['join'](',')||'unknown'};}catch{}const d=a5b['dirname'](b);if(d===b)break;b=d;}return{'domain':a5b['basename'](a)||'unknown','stack':'unknown'};}export function gateErrorFix(a){if(!gateEnabled()){if(!a['draftId'])return{'ok':!![]};const f=loadResolvedDraftById(a['draftId']);if(!f||!f['resolvedAt'])return{'ok':!![]};if(a['project']&&f['project']&&a['project']!==f['project'])return{'ok':!![]};const g=detectProjectMeta(f['directory']);return{'ok':!![],'observed':{'errorSignature':f['errorSignature'],'attempts':f['attempts'],'files':verifyFilesExist(f['editedFiles'],f['directory'])['valid'],'domain':g['domain'],'stack':g['stack'],'project':f['project'],'type':f['type']}};}if(!a['draftId'])return{'ok':![],'reason':'REJECTED:\x20draftId\x20required.\x20Error\x20fixes\x20can\x20only\x20be\x20recorded\x20for\x20errors\x20this\x20system\x20observed\x20(see\x20the\x20[KNOWLEDGE-RECORD]\x20directive\x20in\x20the\x20build_check\x20output).\x20If\x20no\x20directive\x20was\x20shown,\x20skip\x20the\x20record\x20and\x20continue.'};const b=loadResolvedDraftById(a['draftId']);if(!b)return{'ok':![],'reason':'REJECTED:\x20no\x20observed\x20draft\x20for\x20draftId\x20\x27'+a['draftId']+'\x27.\x20Do\x20not\x20fabricate\x20a\x20draftId\x20—\x20skip\x20the\x20record.'};if(!b['resolvedAt'])return{'ok':![],'reason':'REJECTED:\x20draft\x20\x27'+a['draftId']+'\x27\x20is\x20not\x20resolved\x20(error\x20not\x20yet\x20fixed).'};if(a['project']&&b['project']&&a['project']!==b['project'])return{'ok':![],'reason':'REJECTED:\x20draftId\x20\x27'+a['draftId']+'\x27\x20belongs\x20to\x20a\x20different\x20project.'};const c=detectProjectMeta(b['directory']),{valid:e}=verifyFilesExist(b['editedFiles'],b['directory']);return{'ok':!![],'observed':{'errorSignature':b['errorSignature'],'attempts':b['attempts'],'files':e,'domain':c['domain'],'stack':c['stack'],'project':b['project'],'type':b['type']}};}const NOVELTY_THRESHOLD=0.6,similarity=tokenSim;function loadClaudeMdChunks(a){const b=[],e=[];if(a){let f=a;for(let g=0x0;g<0x4&&f;g++){e['push'](a5b['join'](f,'CLAUDE.md'));const h=a5b['dirname'](f);if(h===f)break;f=h;}}for(const j of e){try{const k=a5a['readFileSync'](j,'utf-8');k['split'](/\n\s*\n/)['forEach'](l=>{if(l['trim']()['length']>0x28)b['push'](l['trim']());});}catch{}}return b;}export function gateNovelty(a,b){if(!gateEnabled())return{'ok':!![]};if(!a||a['trim']()['length']<0x14)return{'ok':!![]};const c=loadClaudeMdChunks(b);for(const d of c){if(similarity(a,d)>=NOVELTY_THRESHOLD)return{'ok':![],'reason':'REJECTED:\x20already\x20documented\x20in\x20CLAUDE.md\x20—\x20knowledge\x20store\x20is\x20for\x20non-derivable\x20facts\x20only.'};}return{'ok':!![]};}export function gatePattern(a){if(!gateEnabled())return{'ok':!![]};const b=a['files']??[];if(b['length']===0x0)return{'ok':![],'reason':'REJECTED:\x20pattern\x20requires\x20at\x20least\x20one\x20existing\x20file\x20anchor\x20(files[]).\x20Knowledge\x20store\x20is\x20for\x20grounded\x20facts.'};const {valid:c,invalid:d}=verifyFilesExist(b);if(c['length']===0x0)return{'ok':![],'reason':'REJECTED:\x20none\x20of\x20the\x20referenced\x20files\x20exist:\x20'+d['join'](',\x20')};return{'ok':!![],'validFiles':c,'warning':d['length']>0x0?'Dropped\x20non-existent\x20file\x20refs:\x20'+d['join'](',\x20'):undefined};}
@@ -1 +1 @@
1
- import*as a9a from'fs';import*as a9b from'path';import{homedir}from'os';import{verifyFilesExist}from'./grounding.js';import{unbindSource,tokenSim}from'./concept-catalog.js';import{SOURCE,errorFixSourceId,patternSourceId,quirkSourceId,domainKnowledgeSourceId}from'./contracts.generated.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a9b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a9b['join'](ROUTINECODE_DIR,'knowledge'),CRITIC_STATE_PATH=a9b['join'](KNOWLEDGE_DIR,'last-critic.json'),CRITIC_INTERVAL_MS=0x3c*0x3c*0x3e8,DUP_THRESHOLD=0.92,ANCHOR_FIELDS={'patterns.jsonl':'files','domain-knowledge.jsonl':'scope'},DEDUP_KEYS={'events.jsonl':['errorSignature','domain'],'patterns.jsonl':['title','domain'],'quirks.jsonl':['title','library'],'domain-knowledge.jsonl':['title','project'],'decisions.jsonl':['statement','project']};function sourceRefFor(a,b){const c=d=>d==null?undefined:String(d);switch(a){case'events.jsonl':return{'sourceType':SOURCE['ERROR_FIX'],'sourceId':errorFixSourceId(c(b['domain']),c(b['errorSignature']),c(b['rootCause']))};case'patterns.jsonl':return{'sourceType':SOURCE['PATTERN'],'sourceId':patternSourceId(c(b['domain']),c(b['title']))};case'quirks.jsonl':return{'sourceType':SOURCE['QUIRK'],'sourceId':quirkSourceId(c(b['library']),c(b['title']))};case'domain-knowledge.jsonl':return{'sourceType':SOURCE['DOMAIN_KNOWLEDGE'],'sourceId':domainKnowledgeSourceId(c(b['project']),c(b['title']))};default:return null;}}const sim=tokenSim;function readJsonl(a){try{if(!a9a['existsSync'](a))return[];return a9a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}function criticFile(a){const b=a9b['join'](KNOWLEDGE_DIR,a);if(!a9a['existsSync'](b))return null;const c=readJsonl(b);if(c['length']===0x0)return null;const d=ANCHOR_FIELDS[a],f=DEDUP_KEYS[a]??[],g=[],h=[],i={},j=l=>{i[l]=(i[l]??0x0)+0x1;},k=[];for(const l of c){if(d&&Array['isArray'](l[d])){const m=l[d]['filter'](n=>typeof n==='string');if(m['length']>0x0){const {valid:n}=verifyFilesExist(m);if(n['length']===0x0){h['push']({...l,'_quarantineReason':'no-anchor'}),j('no-anchor');continue;}}}if(typeof l['confidence']==='number'&&l['confidence']<0.2){h['push']({...l,'_quarantineReason':'low-confidence'}),j('low-confidence');continue;}if(f['length']>0x0){const o=k['some'](r=>f['every'](t=>{const u=String(l[t]??''),v=String(r[t]??'');return u&&v&&sim(u,v)>=DUP_THRESHOLD;}));if(o){h['push']({...l,'_quarantineReason':'duplicate'}),j('duplicate');continue;}}g['push'](l),k['push'](l);}if(h['length']>0x0)try{a9a['appendFileSync'](a9b['join'](KNOWLEDGE_DIR,a['replace']('.jsonl','.quarantine.jsonl')),h['map'](s=>JSON['stringify']({...s,'quarantinedAt':new Date()['toISOString']()}))['join']('\x0a')+'\x0a');const r=b+'.tmp';a9a['writeFileSync'](r,g['map'](s=>JSON['stringify'](s))['join']('\x0a')+(g['length']?'\x0a':'')),a9a['renameSync'](r,b);for(const s of h){const t=sourceRefFor(a,s);if(t)try{unbindSource(t['sourceType'],t['sourceId']);}catch{}}}catch{}return{'file':a,'kept':g['length'],'quarantined':h['length'],'reasons':i};}export function runKnowledgeCritic(a=![]){if(!a)try{const e=JSON['parse'](a9a['readFileSync'](CRITIC_STATE_PATH,'utf-8'))['ts']??0x0;if(Date['now']()-e<CRITIC_INTERVAL_MS)return{'ran':![],'results':[],'totalQuarantined':0x0,'skipped':'interval'};}catch{}const b=['events.jsonl','patterns.jsonl','quirks.jsonl','domain-knowledge.jsonl','decisions.jsonl'],c=[];for(const g of b){const h=criticFile(g);if(h)c['push'](h);}const d=c['reduce']((i,j)=>i+j['quarantined'],0x0);try{a9a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]}),a9a['writeFileSync'](CRITIC_STATE_PATH,JSON['stringify']({'ts':Date['now'](),'totalQuarantined':d}));}catch{}return{'ran':!![],'results':c,'totalQuarantined':d};}
1
+ import*as a9a from'fs';import*as a9b from'path';import{homedir}from'os';import{verifyFilesExist}from'./grounding.js';import{unbindSource,tokenSim}from'./concept-catalog.js';import{SOURCE,errorFixSourceId,patternSourceId,quirkSourceId,domainKnowledgeSourceId}from'./contracts.generated.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a9b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']??a9b['join'](ROUTINECODE_DIR,'knowledge'),CRITIC_STATE_PATH=a9b['join'](KNOWLEDGE_DIR,'last-critic.json'),CRITIC_INTERVAL_MS=0x3c*0x3c*0x3e8,DUP_THRESHOLD=0.92,ANCHOR_FIELDS={'patterns.jsonl':'files','domain-knowledge.jsonl':'scope'},DEDUP_KEYS={'events.jsonl':['errorSignature','domain'],'patterns.jsonl':['title','domain'],'quirks.jsonl':['title','library'],'domain-knowledge.jsonl':['title','project'],'decisions.jsonl':['statement','project']};function sourceRefFor(a,b){const c=d=>d==null?undefined:String(d);switch(a){case'events.jsonl':return{'sourceType':SOURCE['ERROR_FIX'],'sourceId':errorFixSourceId(c(b['domain']),c(b['errorSignature']),c(b['rootCause']))};case'patterns.jsonl':return{'sourceType':SOURCE['PATTERN'],'sourceId':patternSourceId(c(b['domain']),c(b['title']))};case'quirks.jsonl':return{'sourceType':SOURCE['QUIRK'],'sourceId':quirkSourceId(c(b['library']),c(b['title']))};case'domain-knowledge.jsonl':return{'sourceType':SOURCE['DOMAIN_KNOWLEDGE'],'sourceId':domainKnowledgeSourceId(c(b['project']),c(b['title']))};default:return null;}}const sim=tokenSim;function readJsonl(a){try{if(!a9a['existsSync'](a))return[];return a9a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}function criticFile(a){const b=a9b['join'](KNOWLEDGE_DIR,a);if(!a9a['existsSync'](b))return null;const c=readJsonl(b);if(c['length']===0x0)return null;const d=ANCHOR_FIELDS[a],f=DEDUP_KEYS[a]??[],g=[],h=[],i={},j=l=>{i[l]=(i[l]??0x0)+0x1;},k=[];for(const l of c){if(d&&Array['isArray'](l[d])){const m=l[d]['filter'](n=>typeof n==='string');if(m['length']>0x0){const {valid:n}=verifyFilesExist(m);if(n['length']===0x0){h['push']({...l,'_quarantineReason':'no-anchor'}),j('no-anchor');continue;}}}if(typeof l['confidence']==='number'&&l['confidence']<0.2){h['push']({...l,'_quarantineReason':'low-confidence'}),j('low-confidence');continue;}if(f['length']>0x0){const o=k['some'](r=>f['every'](t=>{const u=String(l[t]??''),v=String(r[t]??'');return u&&v&&sim(u,v)>=DUP_THRESHOLD;}));if(o){h['push']({...l,'_quarantineReason':'duplicate'}),j('duplicate');continue;}}g['push'](l),k['push'](l);}if(h['length']>0x0)try{a9a['appendFileSync'](a9b['join'](KNOWLEDGE_DIR,a['replace']('.jsonl','.quarantine.jsonl')),h['map'](s=>JSON['stringify']({...s,'quarantinedAt':new Date()['toISOString']()}))['join']('\x0a')+'\x0a');const r=b+'.tmp';a9a['writeFileSync'](r,g['map'](s=>JSON['stringify'](s))['join']('\x0a')+(g['length']?'\x0a':'')),a9a['renameSync'](r,b);for(const s of h){const t=sourceRefFor(a,s);if(t)try{unbindSource(t['sourceType'],t['sourceId']);}catch{}}}catch{}return{'file':a,'kept':g['length'],'quarantined':h['length'],'reasons':i};}export function runKnowledgeCritic(a=![]){if(!a)try{const e=JSON['parse'](a9a['readFileSync'](CRITIC_STATE_PATH,'utf-8'))['ts']??0x0;if(Date['now']()-e<CRITIC_INTERVAL_MS)return{'ran':![],'results':[],'totalQuarantined':0x0,'skipped':'interval'};}catch{}const b=['events.jsonl','patterns.jsonl','quirks.jsonl','domain-knowledge.jsonl','decisions.jsonl'],c=[];for(const g of b){const h=criticFile(g);if(h)c['push'](h);}const d=c['reduce']((i,j)=>i+j['quarantined'],0x0);try{a9a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]}),a9a['writeFileSync'](CRITIC_STATE_PATH,JSON['stringify']({'ts':Date['now'](),'totalQuarantined':d}));}catch{}return{'ran':!![],'results':c,'totalQuarantined':d};}
@@ -1 +1 @@
1
- import*as a10a from'fs';import*as a10b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{knowledgeSendAllowed,logTransmission}from'./sanitize.generated.js';const TIMEOUT_MS=0x1388,OFFLINE='온보딩\x20가이드를\x20지금\x20가져올\x20수\x20없다(지식\x20서버\x20미연결).\x20서버가\x20연결되면\x20다시\x20호출하라.';function configPath(){const a=process.env.ROUTINECODE_DIR??a10b['join'](homedir(),'.routinecode');return process.env.ROUTINECODE_CONFIG_PATH??a10b['join'](a,'config.json');}function loadGuideConfig(){try{return JSON['parse'](a10a['readFileSync'](configPath(),'utf-8'));}catch{return{};}}export async function handleGetOnboardingGuide(){const a=loadGuideConfig();if(!a['serverUrl']||!a['apiKey']||!knowledgeSendAllowed(a))return{'available':![],'markdown':OFFLINE};const b=a['serverUrl']['replace'](/\/$/,'')+'/api/v1/knowledge/guide';try{logTransmission(b,{});const d=await fetch(b,{'headers':{'Authorization':'Bearer\x20'+a['apiKey']},'signal':AbortSignal['timeout'](TIMEOUT_MS)});if(!d['ok']){noteAuthFailure(d['status']);if(d['status']===0x193)return{'available':![],'markdown':'이\x20키에는\x20계정\x20공간이\x20없어\x20가이드를\x20만들\x20수\x20없다(ACCOUNT_SPACE_REQUIRED).'};return{'available':![],'markdown':OFFLINE};}const e=await d['json']();if(typeof e['markdown']!=='string')return{'available':![],'markdown':OFFLINE};return{'available':e['teamOnly']!==!![],'markdown':e['markdown'],'teamOnly':e['teamOnly']===!![],'items':typeof e['items']==='number'?e['items']:undefined,'generatedAt':typeof e['generatedAt']==='string'?e['generatedAt']:undefined};}catch{return{'available':![],'markdown':OFFLINE};}}
1
+ import*as a10a from'fs';import*as a10b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{knowledgeSendAllowed,logTransmission}from'./sanitize.generated.js';const TIMEOUT_MS=0x1388,OFFLINE='온보딩\x20가이드를\x20지금\x20가져올\x20수\x20없다(지식\x20서버\x20미연결).\x20서버가\x20연결되면\x20다시\x20호출하라.';function configPath(){const a=process['env']['ROUTINECODE_DIR']??a10b['join'](homedir(),'.routinecode');return process['env']['ROUTINECODE_CONFIG_PATH']??a10b['join'](a,'config.json');}function loadGuideConfig(){try{return JSON['parse'](a10a['readFileSync'](configPath(),'utf-8'));}catch{return{};}}export async function handleGetOnboardingGuide(){const a=loadGuideConfig();if(!a['serverUrl']||!a['apiKey']||!knowledgeSendAllowed(a))return{'available':![],'markdown':OFFLINE};const b=a['serverUrl']['replace'](/\/$/,'')+'/api/v1/knowledge/guide';try{logTransmission(b,{});const d=await fetch(b,{'headers':{'Authorization':'Bearer\x20'+a['apiKey']},'signal':AbortSignal['timeout'](TIMEOUT_MS)});if(!d['ok']){noteAuthFailure(d['status']);if(d['status']===0x193)return{'available':![],'markdown':'이\x20키에는\x20계정\x20공간이\x20없어\x20가이드를\x20만들\x20수\x20없다(ACCOUNT_SPACE_REQUIRED).'};return{'available':![],'markdown':OFFLINE};}const e=await d['json']();if(typeof e['markdown']!=='string')return{'available':![],'markdown':OFFLINE};return{'available':e['teamOnly']!==!![],'markdown':e['markdown'],'teamOnly':e['teamOnly']===!![],'items':typeof e['items']==='number'?e['items']:undefined,'generatedAt':typeof e['generatedAt']==='string'?e['generatedAt']:undefined};}catch{return{'available':![],'markdown':OFFLINE};}}