@routinecrew/routinecode 2.31.86 → 2.31.87

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 (53) hide show
  1. package/bin/prompt-vault.dat +1 -1
  2. package/bin/rc-skills.js +1 -1
  3. package/hooks/lib/attest_reader.py +16 -1
  4. package/hooks/lib/design_pick_nudge.py +86 -0
  5. package/hooks/lib/i18n.py +48 -20
  6. package/hooks/pre-agent-spawn.mjs +1 -1
  7. package/hooks/pre-agent-spawn.sh +12 -0
  8. package/hooks/pre-credit-guard.sh +1 -1
  9. package/hooks/pre-mark-complete.sh +54 -12
  10. package/hooks/session-start.sh +9 -10
  11. package/hooks/user-prompt-submit.sh +9 -0
  12. package/mcp-plan-manager/dist/file-ops.js +1 -1
  13. package/mcp-routinecode/dist/criteria-card.js +1 -0
  14. package/mcp-routinecode/dist/design-judge.js +1 -0
  15. package/mcp-routinecode/dist/edit-tracker.js +1 -1
  16. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  17. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  18. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  19. package/mcp-routinecode/dist/index.js +1 -1
  20. package/mcp-routinecode/dist/known-solutions.js +1 -1
  21. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  22. package/mcp-routinecode/dist/normalize-sig.js +1 -1
  23. package/mcp-routinecode/dist/observed-draft.js +1 -1
  24. package/mcp-routinecode/dist/observed-escalation.js +1 -1
  25. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  26. package/mcp-routinecode/dist/route-match.js +1 -1
  27. package/mcp-routinecode/dist/routines.js +1 -1
  28. package/mcp-routinecode/dist/rule-engine.js +1 -1
  29. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  30. package/mcp-routinecode/dist/session-registry.js +1 -1
  31. package/mcp-routinecode/dist/skill-pack/sync.js +40 -14
  32. package/mcp-routinecode/dist/test-runner.js +1 -1
  33. package/mcp-routinecode/dist/thinking-judge.js +1 -0
  34. package/mcp-routinecode/dist/verification.js +1 -1
  35. package/package.json +1 -1
  36. package/plugin/agents/analyzer.md.sealed +1 -1
  37. package/plugin/agents/architect.md.sealed +1 -1
  38. package/plugin/agents/crawler.md.sealed +1 -1
  39. package/plugin/agents/explorer.md.sealed +1 -1
  40. package/plugin/agents/implementor.md.sealed +1 -1
  41. package/plugin/agents/looker.md.sealed +1 -1
  42. package/plugin/agents/planner.md.sealed +1 -1
  43. package/plugin/agents/recorder.md.sealed +1 -1
  44. package/plugin/agents/reviewer.md.sealed +1 -1
  45. package/plugin/agents/verifier.md.sealed +1 -1
  46. package/plugin/commands/analyze.md.sealed +1 -1
  47. package/plugin/commands/plan.md.sealed +1 -1
  48. package/plugin/commands/rc.md.sealed +1 -1
  49. package/plugin/commands/receipt.md.sealed +1 -1
  50. package/plugin/commands/recharge.md.sealed +1 -1
  51. package/plugin/commands/routines.md.sealed +1 -1
  52. package/plugin/commands/share.md.sealed +1 -1
  53. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -1 +1 @@
1
- import*as a46a from'fs';import*as a46b from'path';import{homedir}from'os';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a46b['join'](homedir(),'.routinecode','knowledge'),TELEMETRY_FILE=a46b['join'](KNOWLEDGE_DIR,'agent-telemetry.jsonl'),ADVISOR_MODEL=process.env.ROUTINECODE_ADVISOR_MODEL||'claude-opus-4-6',ADVISOR_TIMEOUT_MS=0x3a98,L1_CONFIDENCE_THRESHOLD=0.75,L2_CONFIDENCE_THRESHOLD=0.7,RULES=[{'id':'H1:file-path-given','test':a=>/(?:[\w./-]+\/)?[\w-]+\.(?:ts|tsx|js|jsx|mjs|json|md|sh|py|yml|yaml)\b/['test'](a)&&a['length']<0x78&&!/(?:흐름|flow|전파|사용처|호출|관계|연결|영향|전체|구조|usages?|callers?|impact|architecture)/i['test'](a),'result':{'recommendation':'direct','confidence':0.9,'reasoning':['특정\x20파일의\x201회성\x20확인\x20—\x20해당\x20파일을\x20직접\x20Read/Grep'],'suggestedApproach':'Main이\x20해당\x20파일\x20경로에\x20Read\x20또는\x20Grep\x201~2회\x20실행'}},{'id':'H2:single-symbol-where','test':a=>(/(?:^|\s|[.,?!:;])(?:where|어디|위치)(?:$|\s|[.,?!:;])/i['test'](a)||/어디\s*(?:있|에|인|\?)/['test'](a))&&a['length']<0x64&&!/(?:패턴|pattern|flow|전체|\ball\b|everything|whole)/i['test'](a),'result':{'recommendation':'direct','confidence':0.85,'reasoning':['단일\x20심볼\x20위치\x20질문\x20—\x20Main이\x20Grep\x201~2회로\x20충분'],'suggestedApproach':'Grep으로\x20해당\x20심볼의\x20정의\x20위치\x20탐색'}},{'id':'H3:simple-enumeration','test':a=>/(?:모든|all\b|나열|list|enumerate)/i['test'](a)&&/(?:파일|file|디렉토리|directory|folder|폴더)/i['test'](a)&&a['length']<0x96,'result':{'recommendation':'direct','confidence':0.8,'reasoning':['단순\x20열거\x20요청\x20—\x20Glob/ls\x201회로\x20충분'],'suggestedApproach':'Glob\x20패턴\x20또는\x20Bash\x20ls로\x20즉시\x20열거'}},{'id':'H4:pattern-discovery','test':a=>/(?:패턴|pattern|flow|어떻게\s*(?:동작|작동|작동하|상호작용)|how\s+(?:does|do)\s+.+\s+work|상호작용|interact)/i['test'](a)&&a['length']>0x1e,'result':{'recommendation':'single-explorer','confidence':0.75,'reasoning':['광범위\x20패턴/flow\x20이해\x20필요\x20—\x20가설-검증\x20사이클\x20적합'],'suggestedApproach':'단일\x20explorer를\x20Sequential\x20모드로\x20호출,\x20Decomposition\x20Test\x20Step\x202에서\x20단일\x20판정'}},{'id':'H5:multi-subject-parallel-candidate','test':a=>{const b=/(?:각각|별도|respective|separately|each\s+of)/i['test'](a),c=(a['match'](/,/g)||[])['length'],d=(a['match'](/\b(?:and|와|과|그리고)\b/gi)||[])['length'];return b||c+d>=0x2||/\b\w+\s*,\s*\w+\s*,\s*\w+/['test'](a);},'result':{'recommendation':'parallel-decomposable','confidence':0.65,'reasoning':['3+\x20독립\x20subject로\x20보이는\x20프롬프트\x20—\x20Decomposition\x20Test\x20필수','cross-reference\x20존재\x20가능성\x20먼저\x20확인\x20(많으면\x20단일로\x20통합)'],'suggestedApproach':'Decomposition\x20Test\x203단계\x20실행.\x20Step\x203(cross-reference)에서\x20FALSE일\x20때만\x20병렬,\x20그\x20외\x20단일\x20explorer로\x20통합'}},{'id':'H6:vague-scope','test':a=>/(?:전체|entire|whole|모든\s*것|everything|해줘|부탁)/i['test'](a)&&!/(?:\/|디렉토리|directory|folder|src|apps|packages|hooks)/i['test'](a)&&a['length']<0x50,'result':{'recommendation':'uncertain','confidence':0.55,'reasoning':['SCOPE가\x20명확하지\x20않음.\x20광범위한\x20\x22전체/everything\x22는\x20explorer\x20낭비\x20위험'],'suggestedApproach':'사용자에게\x20구체적\x20범위\x20확인\x20후\x20결정\x20(어떤\x20디렉토리/파일군인지)'}}];function heuristicClassify(a){const b=[];let c=null,d=0x0;for(const e of RULES){e['test'](a)&&(b['push'](e['id']),e['result']['confidence']>d&&(c=e,d=e['result']['confidence']));}if(!c)return null;return{...c['result'],'layer':0x1,'heuristicsTriggered':b};}function tokenizePrompt(a){return new Set(a['toLowerCase']()['replace'](/[^\w가-힣\s]/g,'\x20')['split'](/\s+/)['filter'](b=>b['length']>=0x3));}function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const g of c)if(d['has'](g))e++;const f=c['size']+d['size']-e;return f>0x0?e/f:0x0;}export function loadTelemetry(){if(!a46a['existsSync'](TELEMETRY_FILE))return[];try{const a=a46a['readFileSync'](TELEMETRY_FILE,'utf-8'),b=[];for(const c of a['split']('\x0a')){if(!c['trim']())continue;try{b['push'](JSON['parse'](c));}catch{}}return b;}catch{return[];}}function telemetryLookup(a){const b=loadTelemetry();if(b['length']===0x0)return null;const c=tokenizePrompt(a),d=b['filter'](m=>m['promptSnippet']&&m['agentType']==='explorer')['map'](m=>({'entry':m,'similarity':jaccard(c,tokenizePrompt(m['promptSnippet']))}))['filter'](m=>m['similarity']>=0.4)['sort']((m,n)=>n['similarity']-m['similarity'])['slice'](0x0,0xa);if(d['length']<0x2)return null;const e=d['filter'](m=>m['entry']['result']==='success'&&typeof m['entry']['toolCallCount']==='number');if(e['length']<0x2)return null;const f=e['reduce']((m,n)=>m+(n['entry']['toolCallCount']??0x0),0x0)/e['length'],g=e['reduce']((m,n)=>m+((n['entry']['tokensIn']??0x0)+(n['entry']['tokensOut']??0x0)),0x0)/e['length'];let h,i,j,k,l;if(f<=0x2)h='direct',i='direct',l=0.75,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회.\x20direct\x20처리가\x20적절'],k='Grep\x201~2회로\x20해결\x20가능할\x20것으로\x20예상';else f>=0x6?(h='single-explorer',i='explorer-heavy',l=0.7,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회.\x20광범위\x20탐색\x20필요'],k='단일\x20explorer\x20Sequential\x20호출'):(h='uncertain',i='explorer-light',l=0.55,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회\x20(애매).\x20프롬프트\x20복잡도\x20추가\x20판단\x20필요'],k='1차로\x20Main이\x20직접\x20Grep\x20시도\x20후\x20부족하면\x20explorer\x20고려');return{'recommendation':h,'confidence':l,'reasoning':j,'suggestedApproach':k,'layer':0x2,'heuristicsTriggered':['L2:telemetry-similarity'],'similarPast':{'count':e['length'],'avgToolCalls':f,'avgTokens':g,'mostCommonOutcome':i}};}const L3_SYSTEM_PROMPT='You\x20are\x20a\x20classifier\x20deciding\x20how\x20a\x20software\x20engineer\x27s\x20codebase\x20search\x20query\x20should\x20be\x20routed.\x0a\x0aGiven\x20the\x20query,\x20return\x20ONLY\x20a\x20JSON\x20object\x20with\x20this\x20exact\x20shape:\x0a{\x0a\x20\x20\x22recommendation\x22:\x20\x22direct\x22\x20|\x20\x22single-explorer\x22\x20|\x20\x22parallel-decomposable\x22\x20|\x20\x22uncertain\x22,\x0a\x20\x20\x22confidence\x22:\x20<number\x200.0\x20to\x201.0>,\x0a\x20\x20\x22reasoning\x22:\x20\x22<under\x20200\x20chars,\x20Korean\x20OK>\x22,\x0a\x20\x20\x22suggestedApproach\x22:\x20\x22<under\x20150\x20chars,\x20Korean\x20OK>\x22\x0a}\x0a\x0aRouting\x20criteria:\x0a-\x20direct:\x20Main\x20agent\x20can\x20handle\x20with\x201-3\x20Grep/Read/Glob\x20calls.\x20Applies\x20to:\x20specific\x20file\x20paths,\x20single\x20symbol\x20lookups,\x20simple\x20enumeration,\x20narrow\x20questions\x20on\x20known\x20code.\x0a-\x20single-explorer:\x20Broad\x20pattern\x20discovery\x20requiring\x20hypothesis-verify\x20cycles\x20across\x20multiple\x20files.\x20Main\x20lacks\x20context\x20to\x20Grep\x20efficiently.\x0a-\x20parallel-decomposable:\x203+\x20TRULY\x20INDEPENDENT\x20scopes\x20(no\x20cross-imports,\x20no\x20shared\x20files).\x20RARE\x20—\x20most\x20multi-subject\x20questions\x20are\x20actually\x20single-explorer\x20because\x20subjects\x20cross-reference.\x0a-\x20uncertain:\x20Query\x20is\x20too\x20vague\x20to\x20route.\x20Recommend\x20clarification.\x0a\x0aBe\x20conservative\x20—\x20prefer\x20\x22direct\x22\x20over\x20\x22single-explorer\x22\x20when\x20in\x20doubt.\x20Prefer\x20\x22single-explorer\x22\x20over\x20\x22parallel-decomposable\x22\x20unless\x20independence\x20is\x20structurally\x20obvious.\x0a\x0aReturn\x20ONLY\x20the\x20JSON.\x20No\x20preamble,\x20no\x20code\x20fences.';async function llmClassify(a){const b=process.env.ANTHROPIC_API_KEY;if(!b)return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x201/2\x20unresolved,\x20ANTHROPIC_API_KEY\x20미설정으로\x20Layer\x203\x20생략','기본\x20보수\x20추천:\x20단일\x20explorer\x20Sequential\x20(over-delegation\x20방지)'],'suggestedApproach':'Grep\x201~2회\x20시도\x20후\x20필요하면\x20단일\x20explorer\x20호출','layer':0x0,'heuristicsTriggered':['L3:no-api-key']};const c=new AbortController(),d=setTimeout(()=>c['abort'](),ADVISOR_TIMEOUT_MS);try{const f=await fetch('https://api.anthropic.com/v1/messages',{'method':'POST','headers':{'x-api-key':b,'anthropic-version':'2023-06-01','content-type':'application/json'},'body':JSON['stringify']({'model':ADVISOR_MODEL,'max_tokens':0x190,'system':L3_SYSTEM_PROMPT,'messages':[{'role':'user','content':a}]}),'signal':c['signal']});if(!f['ok']){const n=await f['text']();return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x203\x20API\x20오류\x20(status\x20'+f['status']+'):\x20'+n['slice'](0x0,0x78)],'suggestedApproach':'Layer\x201/2\x20결과\x20기반으로\x20보수적\x20판단\x20(direct\x20우선)','layer':0x3,'heuristicsTriggered':['L3:api-error']};}const g=await f['json'](),h=g['content']?.[0x0]?.['text']??'',i=h['match'](/\{[\s\S]*\}/);if(!i)return{'recommendation':'uncertain','confidence':0.4,'reasoning':['Layer\x203\x20응답\x20파싱\x20실패\x20—\x20JSON\x20블록\x20없음'],'suggestedApproach':'Layer\x201/2\x20결과\x20기반\x20판단','layer':0x3,'heuristicsTriggered':['L3:parse-fail']};const j=JSON['parse'](i[0x0]),k=g['usage']?.['input_tokens']??0x0,l=g['usage']?.['output_tokens']??0x0,m=k*0xf/0xf4240+l*0x4b/0xf4240;return{'recommendation':j['recommendation'],'confidence':j['confidence'],'reasoning':[j['reasoning']],'suggestedApproach':j['suggestedApproach'],'layer':0x3,'heuristicsTriggered':['L3:opus-classifier'],'modelUsed':g['model']??ADVISOR_MODEL,'cost_usd':Number(m['toFixed'](0x5))};}catch(o){const p=o instanceof Error?o['message']:String(o);return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x203\x20예외:\x20'+p['slice'](0x0,0x78)],'suggestedApproach':'Layer\x201/2\x20결과\x20기반\x20판단','layer':0x3,'heuristicsTriggered':['L3:exception']};}finally{clearTimeout(d);}}export async function advise(a){const b=a['prompt']??'';if(!b||b['length']<0x5)return{'recommendation':'uncertain','confidence':0.2,'reasoning':['프롬프트가\x20너무\x20짧거나\x20비어있음'],'suggestedApproach':'프롬프트를\x20구체화\x20후\x20재요청','layer':0x0,'heuristicsTriggered':[]};const c=heuristicClassify(b);if(c&&c['confidence']>=L1_CONFIDENCE_THRESHOLD)return c;const d=telemetryLookup(b);if(d&&d['confidence']>=L2_CONFIDENCE_THRESHOLD)return d;const e=await llmClassify(b);if(c)e['heuristicsTriggered']=[...c['heuristicsTriggered'],...e['heuristicsTriggered']];if(d?.['similarPast'])e['similarPast']=d['similarPast'];return e;}
1
+ import*as a48a from'fs';import*as a48b from'path';import{homedir}from'os';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a48b['join'](homedir(),'.routinecode','knowledge'),TELEMETRY_FILE=a48b['join'](KNOWLEDGE_DIR,'agent-telemetry.jsonl'),ADVISOR_MODEL=process.env.ROUTINECODE_ADVISOR_MODEL||'claude-opus-4-6',ADVISOR_TIMEOUT_MS=0x3a98,L1_CONFIDENCE_THRESHOLD=0.75,L2_CONFIDENCE_THRESHOLD=0.7,RULES=[{'id':'H1:file-path-given','test':a=>/(?:[\w./-]+\/)?[\w-]+\.(?:ts|tsx|js|jsx|mjs|json|md|sh|py|yml|yaml)\b/['test'](a)&&a['length']<0x78&&!/(?:흐름|flow|전파|사용처|호출|관계|연결|영향|전체|구조|usages?|callers?|impact|architecture)/i['test'](a),'result':{'recommendation':'direct','confidence':0.9,'reasoning':['특정\x20파일의\x201회성\x20확인\x20—\x20해당\x20파일을\x20직접\x20Read/Grep'],'suggestedApproach':'Main이\x20해당\x20파일\x20경로에\x20Read\x20또는\x20Grep\x201~2회\x20실행'}},{'id':'H2:single-symbol-where','test':a=>(/(?:^|\s|[.,?!:;])(?:where|어디|위치)(?:$|\s|[.,?!:;])/i['test'](a)||/어디\s*(?:있|에|인|\?)/['test'](a))&&a['length']<0x64&&!/(?:패턴|pattern|flow|전체|\ball\b|everything|whole)/i['test'](a),'result':{'recommendation':'direct','confidence':0.85,'reasoning':['단일\x20심볼\x20위치\x20질문\x20—\x20Main이\x20Grep\x201~2회로\x20충분'],'suggestedApproach':'Grep으로\x20해당\x20심볼의\x20정의\x20위치\x20탐색'}},{'id':'H3:simple-enumeration','test':a=>/(?:모든|all\b|나열|list|enumerate)/i['test'](a)&&/(?:파일|file|디렉토리|directory|folder|폴더)/i['test'](a)&&a['length']<0x96,'result':{'recommendation':'direct','confidence':0.8,'reasoning':['단순\x20열거\x20요청\x20—\x20Glob/ls\x201회로\x20충분'],'suggestedApproach':'Glob\x20패턴\x20또는\x20Bash\x20ls로\x20즉시\x20열거'}},{'id':'H4:pattern-discovery','test':a=>/(?:패턴|pattern|flow|어떻게\s*(?:동작|작동|작동하|상호작용)|how\s+(?:does|do)\s+.+\s+work|상호작용|interact)/i['test'](a)&&a['length']>0x1e,'result':{'recommendation':'single-explorer','confidence':0.75,'reasoning':['광범위\x20패턴/flow\x20이해\x20필요\x20—\x20가설-검증\x20사이클\x20적합'],'suggestedApproach':'단일\x20explorer를\x20Sequential\x20모드로\x20호출,\x20Decomposition\x20Test\x20Step\x202에서\x20단일\x20판정'}},{'id':'H5:multi-subject-parallel-candidate','test':a=>{const b=/(?:각각|별도|respective|separately|each\s+of)/i['test'](a),c=(a['match'](/,/g)||[])['length'],d=(a['match'](/\b(?:and|와|과|그리고)\b/gi)||[])['length'];return b||c+d>=0x2||/\b\w+\s*,\s*\w+\s*,\s*\w+/['test'](a);},'result':{'recommendation':'parallel-decomposable','confidence':0.65,'reasoning':['3+\x20독립\x20subject로\x20보이는\x20프롬프트\x20—\x20Decomposition\x20Test\x20필수','cross-reference\x20존재\x20가능성\x20먼저\x20확인\x20(많으면\x20단일로\x20통합)'],'suggestedApproach':'Decomposition\x20Test\x203단계\x20실행.\x20Step\x203(cross-reference)에서\x20FALSE일\x20때만\x20병렬,\x20그\x20외\x20단일\x20explorer로\x20통합'}},{'id':'H6:vague-scope','test':a=>/(?:전체|entire|whole|모든\s*것|everything|해줘|부탁)/i['test'](a)&&!/(?:\/|디렉토리|directory|folder|src|apps|packages|hooks)/i['test'](a)&&a['length']<0x50,'result':{'recommendation':'uncertain','confidence':0.55,'reasoning':['SCOPE가\x20명확하지\x20않음.\x20광범위한\x20\x22전체/everything\x22는\x20explorer\x20낭비\x20위험'],'suggestedApproach':'사용자에게\x20구체적\x20범위\x20확인\x20후\x20결정\x20(어떤\x20디렉토리/파일군인지)'}}];function heuristicClassify(a){const b=[];let c=null,d=0x0;for(const e of RULES){e['test'](a)&&(b['push'](e['id']),e['result']['confidence']>d&&(c=e,d=e['result']['confidence']));}if(!c)return null;return{...c['result'],'layer':0x1,'heuristicsTriggered':b};}function tokenizePrompt(a){return new Set(a['toLowerCase']()['replace'](/[^\w가-힣\s]/g,'\x20')['split'](/\s+/)['filter'](b=>b['length']>=0x3));}function jaccard(c,d){if(c['size']===0x0||d['size']===0x0)return 0x0;let e=0x0;for(const g of c)if(d['has'](g))e++;const f=c['size']+d['size']-e;return f>0x0?e/f:0x0;}export function loadTelemetry(){if(!a48a['existsSync'](TELEMETRY_FILE))return[];try{const a=a48a['readFileSync'](TELEMETRY_FILE,'utf-8'),b=[];for(const c of a['split']('\x0a')){if(!c['trim']())continue;try{b['push'](JSON['parse'](c));}catch{}}return b;}catch{return[];}}function telemetryLookup(a){const b=loadTelemetry();if(b['length']===0x0)return null;const c=tokenizePrompt(a),d=b['filter'](m=>m['promptSnippet']&&m['agentType']==='explorer')['map'](m=>({'entry':m,'similarity':jaccard(c,tokenizePrompt(m['promptSnippet']))}))['filter'](m=>m['similarity']>=0.4)['sort']((m,n)=>n['similarity']-m['similarity'])['slice'](0x0,0xa);if(d['length']<0x2)return null;const e=d['filter'](m=>m['entry']['result']==='success'&&typeof m['entry']['toolCallCount']==='number');if(e['length']<0x2)return null;const f=e['reduce']((m,n)=>m+(n['entry']['toolCallCount']??0x0),0x0)/e['length'],g=e['reduce']((m,n)=>m+((n['entry']['tokensIn']??0x0)+(n['entry']['tokensOut']??0x0)),0x0)/e['length'];let h,i,j,k,l;if(f<=0x2)h='direct',i='direct',l=0.75,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회.\x20direct\x20처리가\x20적절'],k='Grep\x201~2회로\x20해결\x20가능할\x20것으로\x20예상';else f>=0x6?(h='single-explorer',i='explorer-heavy',l=0.7,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회.\x20광범위\x20탐색\x20필요'],k='단일\x20explorer\x20Sequential\x20호출'):(h='uncertain',i='explorer-light',l=0.55,j=['유사\x20과거\x20프롬프트\x20'+e['length']+'건\x20—\x20평균\x20tool\x20call\x20'+f['toFixed'](0x1)+'회\x20(애매).\x20프롬프트\x20복잡도\x20추가\x20판단\x20필요'],k='1차로\x20Main이\x20직접\x20Grep\x20시도\x20후\x20부족하면\x20explorer\x20고려');return{'recommendation':h,'confidence':l,'reasoning':j,'suggestedApproach':k,'layer':0x2,'heuristicsTriggered':['L2:telemetry-similarity'],'similarPast':{'count':e['length'],'avgToolCalls':f,'avgTokens':g,'mostCommonOutcome':i}};}const L3_SYSTEM_PROMPT='You\x20are\x20a\x20classifier\x20deciding\x20how\x20a\x20software\x20engineer\x27s\x20codebase\x20search\x20query\x20should\x20be\x20routed.\x0a\x0aGiven\x20the\x20query,\x20return\x20ONLY\x20a\x20JSON\x20object\x20with\x20this\x20exact\x20shape:\x0a{\x0a\x20\x20\x22recommendation\x22:\x20\x22direct\x22\x20|\x20\x22single-explorer\x22\x20|\x20\x22parallel-decomposable\x22\x20|\x20\x22uncertain\x22,\x0a\x20\x20\x22confidence\x22:\x20<number\x200.0\x20to\x201.0>,\x0a\x20\x20\x22reasoning\x22:\x20\x22<under\x20200\x20chars,\x20Korean\x20OK>\x22,\x0a\x20\x20\x22suggestedApproach\x22:\x20\x22<under\x20150\x20chars,\x20Korean\x20OK>\x22\x0a}\x0a\x0aRouting\x20criteria:\x0a-\x20direct:\x20Main\x20agent\x20can\x20handle\x20with\x201-3\x20Grep/Read/Glob\x20calls.\x20Applies\x20to:\x20specific\x20file\x20paths,\x20single\x20symbol\x20lookups,\x20simple\x20enumeration,\x20narrow\x20questions\x20on\x20known\x20code.\x0a-\x20single-explorer:\x20Broad\x20pattern\x20discovery\x20requiring\x20hypothesis-verify\x20cycles\x20across\x20multiple\x20files.\x20Main\x20lacks\x20context\x20to\x20Grep\x20efficiently.\x0a-\x20parallel-decomposable:\x203+\x20TRULY\x20INDEPENDENT\x20scopes\x20(no\x20cross-imports,\x20no\x20shared\x20files).\x20RARE\x20—\x20most\x20multi-subject\x20questions\x20are\x20actually\x20single-explorer\x20because\x20subjects\x20cross-reference.\x0a-\x20uncertain:\x20Query\x20is\x20too\x20vague\x20to\x20route.\x20Recommend\x20clarification.\x0a\x0aBe\x20conservative\x20—\x20prefer\x20\x22direct\x22\x20over\x20\x22single-explorer\x22\x20when\x20in\x20doubt.\x20Prefer\x20\x22single-explorer\x22\x20over\x20\x22parallel-decomposable\x22\x20unless\x20independence\x20is\x20structurally\x20obvious.\x0a\x0aReturn\x20ONLY\x20the\x20JSON.\x20No\x20preamble,\x20no\x20code\x20fences.';async function llmClassify(a){const b=process.env.ANTHROPIC_API_KEY;if(!b)return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x201/2\x20unresolved,\x20ANTHROPIC_API_KEY\x20미설정으로\x20Layer\x203\x20생략','기본\x20보수\x20추천:\x20단일\x20explorer\x20Sequential\x20(over-delegation\x20방지)'],'suggestedApproach':'Grep\x201~2회\x20시도\x20후\x20필요하면\x20단일\x20explorer\x20호출','layer':0x0,'heuristicsTriggered':['L3:no-api-key']};const c=new AbortController(),d=setTimeout(()=>c['abort'](),ADVISOR_TIMEOUT_MS);try{const f=await fetch('https://api.anthropic.com/v1/messages',{'method':'POST','headers':{'x-api-key':b,'anthropic-version':'2023-06-01','content-type':'application/json'},'body':JSON['stringify']({'model':ADVISOR_MODEL,'max_tokens':0x190,'system':L3_SYSTEM_PROMPT,'messages':[{'role':'user','content':a}]}),'signal':c['signal']});if(!f['ok']){const n=await f['text']();return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x203\x20API\x20오류\x20(status\x20'+f['status']+'):\x20'+n['slice'](0x0,0x78)],'suggestedApproach':'Layer\x201/2\x20결과\x20기반으로\x20보수적\x20판단\x20(direct\x20우선)','layer':0x3,'heuristicsTriggered':['L3:api-error']};}const g=await f['json'](),h=g['content']?.[0x0]?.['text']??'',i=h['match'](/\{[\s\S]*\}/);if(!i)return{'recommendation':'uncertain','confidence':0.4,'reasoning':['Layer\x203\x20응답\x20파싱\x20실패\x20—\x20JSON\x20블록\x20없음'],'suggestedApproach':'Layer\x201/2\x20결과\x20기반\x20판단','layer':0x3,'heuristicsTriggered':['L3:parse-fail']};const j=JSON['parse'](i[0x0]),k=g['usage']?.['input_tokens']??0x0,l=g['usage']?.['output_tokens']??0x0,m=k*0xf/0xf4240+l*0x4b/0xf4240;return{'recommendation':j['recommendation'],'confidence':j['confidence'],'reasoning':[j['reasoning']],'suggestedApproach':j['suggestedApproach'],'layer':0x3,'heuristicsTriggered':['L3:opus-classifier'],'modelUsed':g['model']??ADVISOR_MODEL,'cost_usd':Number(m['toFixed'](0x5))};}catch(o){const p=o instanceof Error?o['message']:String(o);return{'recommendation':'uncertain','confidence':0.3,'reasoning':['Layer\x203\x20예외:\x20'+p['slice'](0x0,0x78)],'suggestedApproach':'Layer\x201/2\x20결과\x20기반\x20판단','layer':0x3,'heuristicsTriggered':['L3:exception']};}finally{clearTimeout(d);}}export async function advise(a){const b=a['prompt']??'';if(!b||b['length']<0x5)return{'recommendation':'uncertain','confidence':0.2,'reasoning':['프롬프트가\x20너무\x20짧거나\x20비어있음'],'suggestedApproach':'프롬프트를\x20구체화\x20후\x20재요청','layer':0x0,'heuristicsTriggered':[]};const c=heuristicClassify(b);if(c&&c['confidence']>=L1_CONFIDENCE_THRESHOLD)return c;const d=telemetryLookup(b);if(d&&d['confidence']>=L2_CONFIDENCE_THRESHOLD)return d;const e=await llmClassify(b);if(c)e['heuristicsTriggered']=[...c['heuristicsTriggered'],...e['heuristicsTriggered']];if(d?.['similarPast'])e['similarPast']=d['similarPast'];return e;}
@@ -1 +1 @@
1
- import*as a47a from'fs';import*as a47b from'path';import{homedir}from'os';import{createHash}from'crypto';import{normalizeSigText,problemKeyOf}from'./normalize-sig.js';const attempts=new Map(),ESCALATION_THRESHOLD=0x3,ATTEMPTS_TTL_MS=0x7*0x18*0x3c*0x3c*0x3e8,KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a47b['join'](homedir(),'.routinecode','knowledge'),ATTEMPTS_FILE=a47b['join'](KNOWLEDGE_DIR,'attempts.json'),RC_RUNDIR=((()=>{const a=process.env.XDG_RUNTIME_DIR||a47b['join'](homedir(),'.routinecode','run');try{return a47a['mkdirSync'](a,{'recursive':!![],'mode':0x1c0}),a;}catch{return'/tmp';}})()),ESCALATION_STATE_FILE=a47b['join'](RC_RUNDIR,'routinecode-escalation.json');function escalatedKey(){const a=currentProject();for(const [b,c]of attempts){if(!sameProject(b,a))continue;if(c['filter'](d=>d['result']==='fail')['length']>=ESCALATION_THRESHOLD)return b;}return null;}function syncEscalationFile(){const a=escalatedKey();updateEscalationFile(a!==null,a??undefined);}function updateEscalationFile(a,b){try{a47a['writeFileSync'](ESCALATION_STATE_FILE,JSON['stringify']({'escalated':a,'issueId':b??null,'updatedAt':new Date()['toISOString']()}));}catch{}}function loadAttempts(){try{if(!a47a['existsSync'](ATTEMPTS_FILE))return;const a=a47a['readFileSync'](ATTEMPTS_FILE,'utf-8'),b=JSON['parse'](a),c=Date['now']()-ATTEMPTS_TTL_MS;for(const [d,e]of Object['entries'](b)){const f=e['filter'](g=>{const h=Date['parse'](g['ts']);return Number['isFinite'](h)&&h>=c;});f['length']>0x0&&attempts['set'](d,f);}}catch{}}function persistAttempts(){try{!a47a['existsSync'](KNOWLEDGE_DIR)&&a47a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});const a={};attempts['forEach']((b,c)=>{a[c]=b;}),a47a['writeFileSync'](ATTEMPTS_FILE,JSON['stringify'](a,null,0x2));}catch{}}const STOP=new Set(['npm','pnpm','yarn','npx','run','build','test','tests','next','error','errors','failed','fail','failure','the','and','for','with','from','not','cannot','could','was','were','this','that','exit','code','warning']),MERGE_MIN_SHARED=0x4,MERGE_MIN_CONTAIN=0.6,currentProject=()=>a47b['resolve'](process.env.CLAUDE_PROJECT_DIR||process['cwd']()),projectTag=a=>createHash('sha1')['update'](a)['digest']('hex')['slice'](0x0,0x8),sameProject=(a,b)=>(attempts['get'](a)??[])['every'](c=>!c['project']||c['project']===b);export function sigTokens(a){return new Set(normalizeSigText(String(a??''))['toLowerCase']()['split'](/[\s"'`(),:;\[\]{}<>=]+/)['filter'](b=>b['length']>=0x3&&!STOP['has'](b)&&!/^[\d.*n]+$/['test'](b)));}export function quotedLiterals(a){const b=new Set(),c=/(?<![A-Za-z0-9])['"`]([^'"`\n]{1,200}?)['"`](?![A-Za-z0-9])/g;let d;while((d=c['exec'](String(a??'')))!==null){const e=d[0x1]['trim']()['toLowerCase']();if(e)b['add'](e);}return b;}function literalsOfKey(b){const c=new Set();for(const d of attempts['get'](b)??[])for(const e of quotedLiterals(d['issueId']??b))c['add'](e);return c;}function literalsConflict(c,d){if(!c['size']||!d['size'])return![];for(const e of c)if(d['has'](e))return![];return!![];}function overlaps(c,d){if(!c['size']||!d['size'])return![];let e=0x0;for(const f of c)if(d['has'](f))e++;return e>=MERGE_MIN_SHARED&&e/Math['min'](c['size'],d['size'])>=MERGE_MIN_CONTAIN;}function tokensOfKey(b){const c=new Set();for(const d of attempts['get'](b)??[])for(const e of sigTokens(d['issueId']??b))c['add'](e);return c;}export function resolveKey(a){const b=currentProject();if(attempts['has'](a)&&sameProject(a,b))return{'key':a,'mergedFrom':[]};const c=problemKeyOf(a)+'@'+projectTag(b),d=i=>[...new Set((attempts['get'](i)??[])['map'](j=>j['issueId']??i))]['filter'](j=>j!==a);if(attempts['has'](c))return{'key':c,'mergedFrom':d(c)};const e=problemKeyOf(a);if(attempts['has'](e)&&sameProject(e,b))return{'key':e,'mergedFrom':d(e)};const f=sigTokens(a),g=quotedLiterals(a);let h=null;for(const i of attempts['keys']()){if(!sameProject(i,b))continue;const j=tokensOfKey(i);if(!overlaps(f,j))continue;if(literalsConflict(g,literalsOfKey(i)))continue;let l=0x0;for(const m of f)if(j['has'](m))l++;if(!h||l>h['n'])h={'k':i,'n':l};}if(h)return{'key':h['k'],'mergedFrom':d(h['k'])};return{'key':c,'mergedFrom':[]};}loadAttempts();export function recordAttempt(a){const {issueId:b,approach:c,result:d,reason:e}=a,{key:f,mergedFrom:g}=resolveKey(b),h=attempts['get'](f)??[],i={'issueId':b,'project':currentProject(),'approach':c,'result':d,'reason':e,'ts':new Date()['toISOString']()};h['push'](i),attempts['set'](f,h);if(d==='success')return attempts['delete'](f),syncEscalationFile(),persistAttempts(),{'attemptNumber':h['length'],'shouldEscalate':![],'history':[],'mergedFrom':g};const j=h['filter'](l=>l['result']==='fail'),k=j['length']>=ESCALATION_THRESHOLD;if(k)updateEscalationFile(!![],f);else syncEscalationFile();return persistAttempts(),{'attemptNumber':h['length'],'shouldEscalate':k,'history':h,'mergedFrom':g};}export function checkEscalation(a){const b=attempts['get'](resolveKey(a)['key'])??[],c=b['filter'](d=>d['result']==='fail');return{'totalAttempts':b['length'],'failedAttempts':c['length'],'shouldEscalate':c['length']>=ESCALATION_THRESHOLD,'approaches':b['map'](d=>'['+d['result']+']\x20'+d['approach']+(d['reason']?'\x20('+d['reason']+')':''))};}export function clearAttempts(a){const b=attempts['has'](a)?a:resolveKey(a)['key'],c=attempts['has'](b);return attempts['delete'](b),syncEscalationFile(),persistAttempts(),{'cleared':c};}
1
+ import*as a49a from'fs';import*as a49b from'path';import{homedir}from'os';import{createHash}from'crypto';import{normalizeSigText,problemKeyOf}from'./normalize-sig.js';const attempts=new Map(),ESCALATION_THRESHOLD=0x3,ATTEMPTS_TTL_MS=0x7*0x18*0x3c*0x3c*0x3e8,KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a49b['join'](homedir(),'.routinecode','knowledge'),ATTEMPTS_FILE=a49b['join'](KNOWLEDGE_DIR,'attempts.json'),RC_RUNDIR=((()=>{const a=process.env.XDG_RUNTIME_DIR||a49b['join'](homedir(),'.routinecode','run');try{return a49a['mkdirSync'](a,{'recursive':!![],'mode':0x1c0}),a;}catch{return'/tmp';}})()),ESCALATION_STATE_FILE=a49b['join'](RC_RUNDIR,'routinecode-escalation.json');function escalatedKey(){const a=currentProject();for(const [b,c]of attempts){if(!sameProject(b,a))continue;if(c['filter'](d=>d['result']==='fail')['length']>=ESCALATION_THRESHOLD)return b;}return null;}function syncEscalationFile(){const a=escalatedKey();updateEscalationFile(a!==null,a??undefined);}function updateEscalationFile(a,b){try{a49a['writeFileSync'](ESCALATION_STATE_FILE,JSON['stringify']({'escalated':a,'issueId':b??null,'updatedAt':new Date()['toISOString']()}));}catch{}}function loadAttempts(){try{if(!a49a['existsSync'](ATTEMPTS_FILE))return;const a=a49a['readFileSync'](ATTEMPTS_FILE,'utf-8'),b=JSON['parse'](a),c=Date['now']()-ATTEMPTS_TTL_MS;for(const [d,e]of Object['entries'](b)){const f=e['filter'](g=>{const h=Date['parse'](g['ts']);return Number['isFinite'](h)&&h>=c;});f['length']>0x0&&attempts['set'](d,f);}}catch{}}function persistAttempts(){try{!a49a['existsSync'](KNOWLEDGE_DIR)&&a49a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});const a={};attempts['forEach']((b,c)=>{a[c]=b;}),a49a['writeFileSync'](ATTEMPTS_FILE,JSON['stringify'](a,null,0x2));}catch{}}const STOP=new Set(['npm','pnpm','yarn','npx','run','build','test','tests','next','error','errors','failed','fail','failure','the','and','for','with','from','not','cannot','could','was','were','this','that','exit','code','warning']),MERGE_MIN_SHARED=0x4,MERGE_MIN_CONTAIN=0.6,currentProject=()=>a49b['resolve'](process.env.CLAUDE_PROJECT_DIR||process['cwd']()),projectTag=a=>createHash('sha1')['update'](a)['digest']('hex')['slice'](0x0,0x8),sameProject=(a,b)=>(attempts['get'](a)??[])['every'](c=>!c['project']||c['project']===b);export function sigTokens(a){return new Set(normalizeSigText(String(a??''))['toLowerCase']()['split'](/[\s"'`(),:;\[\]{}<>=]+/)['filter'](b=>b['length']>=0x3&&!STOP['has'](b)&&!/^[\d.*n]+$/['test'](b)));}export function quotedLiterals(a){const b=new Set(),c=/(?<![A-Za-z0-9])['"`]([^'"`\n]{1,200}?)['"`](?![A-Za-z0-9])/g;let d;while((d=c['exec'](String(a??'')))!==null){const e=d[0x1]['trim']()['toLowerCase']();if(e)b['add'](e);}return b;}function literalsOfKey(b){const c=new Set();for(const d of attempts['get'](b)??[])for(const e of quotedLiterals(d['issueId']??b))c['add'](e);return c;}function literalsConflict(c,d){if(!c['size']||!d['size'])return![];for(const e of c)if(d['has'](e))return![];return!![];}function overlaps(c,d){if(!c['size']||!d['size'])return![];let e=0x0;for(const f of c)if(d['has'](f))e++;return e>=MERGE_MIN_SHARED&&e/Math['min'](c['size'],d['size'])>=MERGE_MIN_CONTAIN;}function tokensOfKey(b){const c=new Set();for(const d of attempts['get'](b)??[])for(const e of sigTokens(d['issueId']??b))c['add'](e);return c;}export function resolveKey(a){const b=currentProject();if(attempts['has'](a)&&sameProject(a,b))return{'key':a,'mergedFrom':[]};const c=problemKeyOf(a)+'@'+projectTag(b),d=i=>[...new Set((attempts['get'](i)??[])['map'](j=>j['issueId']??i))]['filter'](j=>j!==a);if(attempts['has'](c))return{'key':c,'mergedFrom':d(c)};const e=problemKeyOf(a);if(attempts['has'](e)&&sameProject(e,b))return{'key':e,'mergedFrom':d(e)};const f=sigTokens(a),g=quotedLiterals(a);let h=null;for(const i of attempts['keys']()){if(!sameProject(i,b))continue;const j=tokensOfKey(i);if(!overlaps(f,j))continue;if(literalsConflict(g,literalsOfKey(i)))continue;let l=0x0;for(const m of f)if(j['has'](m))l++;if(!h||l>h['n'])h={'k':i,'n':l};}if(h)return{'key':h['k'],'mergedFrom':d(h['k'])};return{'key':c,'mergedFrom':[]};}loadAttempts();export function recordAttempt(a){const {issueId:b,approach:c,result:d,reason:e}=a,{key:f,mergedFrom:g}=resolveKey(b),h=attempts['get'](f)??[],i={'issueId':b,'project':currentProject(),'approach':c,'result':d,'reason':e,'ts':new Date()['toISOString']()};h['push'](i),attempts['set'](f,h);if(d==='success')return attempts['delete'](f),syncEscalationFile(),persistAttempts(),{'attemptNumber':h['length'],'shouldEscalate':![],'history':[],'mergedFrom':g};const j=h['filter'](l=>l['result']==='fail'),k=j['length']>=ESCALATION_THRESHOLD;if(k)updateEscalationFile(!![],f);else syncEscalationFile();return persistAttempts(),{'attemptNumber':h['length'],'shouldEscalate':k,'history':h,'mergedFrom':g};}export function checkEscalation(a){const b=attempts['get'](resolveKey(a)['key'])??[],c=b['filter'](d=>d['result']==='fail');return{'totalAttempts':b['length'],'failedAttempts':c['length'],'shouldEscalate':c['length']>=ESCALATION_THRESHOLD,'approaches':b['map'](d=>'['+d['result']+']\x20'+d['approach']+(d['reason']?'\x20('+d['reason']+')':''))};}export function clearAttempts(a){const b=attempts['has'](a)?a:resolveKey(a)['key'],c=attempts['has'](b);return attempts['delete'](b),syncEscalationFile(),persistAttempts(),{'cleared':c};}
@@ -1 +1 @@
1
- import*as a49a from'fs';import*as a49b from'path';import{homedir}from'os';import{getVerificationRules}from'./rule-engine.js';import{readJsonl}from'./contracts.generated.js';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a49b['join'](homedir(),'.routinecode','knowledge'),CAUSAL_LINKS_PATH=a49b['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),EVENTS_PATH=a49b['join'](KNOWLEDGE_DIR,'events.jsonl'),QUIRKS_PATH=a49b['join'](KNOWLEDGE_DIR,'quirks.jsonl'),RISK_CACHE_PATH=a49b['join'](KNOWLEDGE_DIR,'file-risk-cache.json'),CACHE_TTL_MS=0xa*0x3c*0x3e8;export function mergeCausalDupes(a){const b=new Map();for(const c of a){if(!c['trigger']?.['file']||!c['effect']?.['file'])continue;const d=c['trigger']['file']+'::'+c['effect']['file'],f=b['get'](d);f?(f['observedCount']=(f['observedCount']??0x1)+(c['observedCount']??0x1),f['confidence']=Math['min'](0x1,Math['max'](f['confidence']??0.5,c['confidence']??0.5)+0.05)):b['set'](d,{...c});}return b;}function normalizeFile(a){return a49b['basename'](a);}function matchFile(a,b){if(!a||!b)return![];if(a===b)return!![];return normalizeFile(a)===normalizeFile(b);}const IMPORT_PATTERNS={'.ts,.tsx,.js,.jsx,.mjs,.cjs':[/(?:from\s+['"]|require\s*\(\s*['"])([^'"./][^'"]*)['"]/g],'.py':[/^(?:from|import)\s+([a-zA-Z_]\w*)(?:\.|$)/gm],'.go':[/import\s+(?:\w+\s+)?"([^"]+)"/g,/^\s+"([^"]+)"/gm],'.java,.kt,.kts':[/^import\s+(?:static\s+)?([a-z][\w.]*)\.[A-Z]/gm],'.rs':[/^use\s+([a-z_]\w*)::/gm]};function extractLibraries(a){try{const b=a49b['extname'](a)['toLowerCase'](),c=a49a['readFileSync'](a,'utf-8'),d=new Set();for(const [e,f]of Object['entries'](IMPORT_PATTERNS)){if(!e['split'](',')['includes'](b))continue;for(const g of f){g['lastIndex']=0x0;let h;while((h=g['exec'](c))!==null){if(h[0x1]){const i=h[0x1]['match'](/^(@[^/]+\/[^/]+)/);d['add'](i?i[0x1]:h[0x1]['split']('/')[0x0]['split']('.')[0x0]);}}}break;}return[...d];}catch{return[];}}let riskCache=null;function loadCache(){if(riskCache)return riskCache;try{if(a49a['existsSync'](RISK_CACHE_PATH))return riskCache=JSON['parse'](a49a['readFileSync'](RISK_CACHE_PATH,'utf-8')),riskCache;}catch{}return riskCache={'scores':{}},riskCache;}function saveCache(){try{!a49a['existsSync'](KNOWLEDGE_DIR)&&a49a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]}),a49a['writeFileSync'](RISK_CACHE_PATH,JSON['stringify'](riskCache,null,0x2),'utf-8');}catch{}}function getCachedScore(a){const b=loadCache(),c=b['scores'][normalizeFile(a)];if(c&&Date['now']()-c['ts']<CACHE_TTL_MS)return c['score'];return null;}function setCachedScore(a,b){const c=loadCache();c['scores'][normalizeFile(a)]={'score':b,'ts':Date['now']()};const d=Object['keys'](c['scores']);if(d['length']>0x1f4){const e=d['map'](f=>({'k':f,'ts':c['scores'][f]['ts']}))['sort']((f,g)=>f['ts']-g['ts']);for(let f=0x0;f<d['length']-0x1f4;f++){delete c['scores'][e[f]['k']];}}saveCache();}function applyRules(a){try{const b=getVerificationRules(a);if(b['length']===0x0)return null;const c=[];for(const d of b){c['push'](...d['verify_files']??[]);}return{'scoreDelta':Math['min'](0x1e,b['length']*0xf),'factors':[{'source':'learned_rule','weight':Math['min'](0x1e,b['length']*0xf),'detail':b['length']+'\x20active\x20verification\x20rule(s)\x20→\x20auto-verify:\x20'+c['map'](e=>normalizeFile(e))['join'](',\x20')}],'affectedFiles':c};}catch{return null;}}export function calculateFileRisk(a){const b=getCachedScore(a);if(b)return b;let c=0x0;const d=[],e=[],f=applyRules(a);f&&(c+=f['scoreDelta'],d['push'](...f['factors']),e['push'](...f['affectedFiles']));const g=readJsonl(CAUSAL_LINKS_PATH),h=mergeCausalDupes(g),i=[...h['values']()]['filter'](s=>(s['confidence']??0.5)>=0.3&&(s['observedCount']??0x1)>=0x2),j=i['filter'](s=>matchFile(s['trigger']?.['file']??'',a));if(j['length']>0x0){const s=j['reduce']((u,v)=>u+(v['confidence']??0.5),0x0),t=Math['min'](0x28,Math['round'](s*0xf));c+=t,d['push']({'source':'causal_link','weight':t,'detail':j['length']+'\x20known\x20side-effect(s):\x20'+j['map'](u=>normalizeFile(u['effect']?.['file']??''))['join'](',\x20')});for(const u of j){if(u['effect']?.['file'])e['push'](u['effect']['file']);}}const k=i['filter'](v=>matchFile(v['effect']?.['file']??'',a));if(k['length']>0x0){const v=Math['min'](0xf,k['length']*0x5);c+=v,d['push']({'source':'causal_effect','weight':v,'detail':'affected\x20by\x20'+k['length']+'\x20other\x20file(s):\x20'+k['map'](w=>normalizeFile(w['trigger']?.['file']??''))['join'](',\x20')});}const l=readJsonl(EVENTS_PATH),m=normalizeFile(a),n=l['filter'](w=>{const x=(w['errorSignature']??'')+(w['rootCause']??'')+(w['fixApproach']??'');return x['includes'](m);});if(n['length']>0x0){const w=Math['min'](0x1e,n['length']*0xa);c+=w,d['push']({'source':'error_history','weight':w,'detail':n['length']+'\x20past\x20error(s)\x20involving\x20this\x20file'});}const o=extractLibraries(a);if(o['length']>0x0){const x=readJsonl(QUIRKS_PATH),y=x['filter'](z=>o['some'](A=>{const B=(z['library']??'')['split']('@')[0x0]['toLowerCase']();return B===A['toLowerCase']();}));if(y['length']>0x0){const z=Math['min'](0xf,y['length']*0x5);c+=z,d['push']({'source':'library_quirk','weight':z,'detail':y['length']+'\x20known\x20quirk(s):\x20'+y['map'](A=>A['library'])['join'](',\x20')});}}const p=Math['min'](0x64,c),q=p>=0x46?'high':p>=0x1e?'medium':'low',r={'file':a,'score':p,'level':q,'factors':d,'affectedFiles':e};return setCachedScore(a,r),r;}export function calculateBatchRisk(a){const b=a['map'](e=>calculateFileRisk(e)),c=b['length']>0x0?b['reduce']((e,f)=>f['score']>e['score']?f:e,b[0x0]):null,d=c&&c['score']>=0x46?'high':c&&c['score']>=0x1e?'medium':'low';return{'files':b,'maxRisk':c,'aggregateLevel':d};}
1
+ import*as a51a from'fs';import*as a51b from'path';import{homedir}from'os';import{getVerificationRules}from'./rule-engine.js';import{readJsonl}from'./contracts.generated.js';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a51b['join'](homedir(),'.routinecode','knowledge'),CAUSAL_LINKS_PATH=a51b['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),EVENTS_PATH=a51b['join'](KNOWLEDGE_DIR,'events.jsonl'),QUIRKS_PATH=a51b['join'](KNOWLEDGE_DIR,'quirks.jsonl'),RISK_CACHE_PATH=a51b['join'](KNOWLEDGE_DIR,'file-risk-cache.json'),CACHE_TTL_MS=0xa*0x3c*0x3e8;export function mergeCausalDupes(a){const b=new Map();for(const c of a){if(!c['trigger']?.['file']||!c['effect']?.['file'])continue;const d=c['trigger']['file']+'::'+c['effect']['file'],f=b['get'](d);f?(f['observedCount']=(f['observedCount']??0x1)+(c['observedCount']??0x1),f['confidence']=Math['min'](0x1,Math['max'](f['confidence']??0.5,c['confidence']??0.5)+0.05)):b['set'](d,{...c});}return b;}function normalizeFile(a){return a51b['basename'](a);}function matchFile(a,b){if(!a||!b)return![];if(a===b)return!![];return normalizeFile(a)===normalizeFile(b);}const IMPORT_PATTERNS={'.ts,.tsx,.js,.jsx,.mjs,.cjs':[/(?:from\s+['"]|require\s*\(\s*['"])([^'"./][^'"]*)['"]/g],'.py':[/^(?:from|import)\s+([a-zA-Z_]\w*)(?:\.|$)/gm],'.go':[/import\s+(?:\w+\s+)?"([^"]+)"/g,/^\s+"([^"]+)"/gm],'.java,.kt,.kts':[/^import\s+(?:static\s+)?([a-z][\w.]*)\.[A-Z]/gm],'.rs':[/^use\s+([a-z_]\w*)::/gm]};function extractLibraries(a){try{const b=a51b['extname'](a)['toLowerCase'](),c=a51a['readFileSync'](a,'utf-8'),d=new Set();for(const [e,f]of Object['entries'](IMPORT_PATTERNS)){if(!e['split'](',')['includes'](b))continue;for(const g of f){g['lastIndex']=0x0;let h;while((h=g['exec'](c))!==null){if(h[0x1]){const i=h[0x1]['match'](/^(@[^/]+\/[^/]+)/);d['add'](i?i[0x1]:h[0x1]['split']('/')[0x0]['split']('.')[0x0]);}}}break;}return[...d];}catch{return[];}}let riskCache=null;function loadCache(){if(riskCache)return riskCache;try{if(a51a['existsSync'](RISK_CACHE_PATH))return riskCache=JSON['parse'](a51a['readFileSync'](RISK_CACHE_PATH,'utf-8')),riskCache;}catch{}return riskCache={'scores':{}},riskCache;}function saveCache(){try{!a51a['existsSync'](KNOWLEDGE_DIR)&&a51a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]}),a51a['writeFileSync'](RISK_CACHE_PATH,JSON['stringify'](riskCache,null,0x2),'utf-8');}catch{}}function getCachedScore(a){const b=loadCache(),c=b['scores'][normalizeFile(a)];if(c&&Date['now']()-c['ts']<CACHE_TTL_MS)return c['score'];return null;}function setCachedScore(a,b){const c=loadCache();c['scores'][normalizeFile(a)]={'score':b,'ts':Date['now']()};const d=Object['keys'](c['scores']);if(d['length']>0x1f4){const e=d['map'](f=>({'k':f,'ts':c['scores'][f]['ts']}))['sort']((f,g)=>f['ts']-g['ts']);for(let f=0x0;f<d['length']-0x1f4;f++){delete c['scores'][e[f]['k']];}}saveCache();}function applyRules(a){try{const b=getVerificationRules(a);if(b['length']===0x0)return null;const c=[];for(const d of b){c['push'](...d['verify_files']??[]);}return{'scoreDelta':Math['min'](0x1e,b['length']*0xf),'factors':[{'source':'learned_rule','weight':Math['min'](0x1e,b['length']*0xf),'detail':b['length']+'\x20active\x20verification\x20rule(s)\x20→\x20auto-verify:\x20'+c['map'](e=>normalizeFile(e))['join'](',\x20')}],'affectedFiles':c};}catch{return null;}}export function calculateFileRisk(a){const b=getCachedScore(a);if(b)return b;let c=0x0;const d=[],e=[],f=applyRules(a);f&&(c+=f['scoreDelta'],d['push'](...f['factors']),e['push'](...f['affectedFiles']));const g=readJsonl(CAUSAL_LINKS_PATH),h=mergeCausalDupes(g),i=[...h['values']()]['filter'](s=>(s['confidence']??0.5)>=0.3&&(s['observedCount']??0x1)>=0x2),j=i['filter'](s=>matchFile(s['trigger']?.['file']??'',a));if(j['length']>0x0){const s=j['reduce']((u,v)=>u+(v['confidence']??0.5),0x0),t=Math['min'](0x28,Math['round'](s*0xf));c+=t,d['push']({'source':'causal_link','weight':t,'detail':j['length']+'\x20known\x20side-effect(s):\x20'+j['map'](u=>normalizeFile(u['effect']?.['file']??''))['join'](',\x20')});for(const u of j){if(u['effect']?.['file'])e['push'](u['effect']['file']);}}const k=i['filter'](v=>matchFile(v['effect']?.['file']??'',a));if(k['length']>0x0){const v=Math['min'](0xf,k['length']*0x5);c+=v,d['push']({'source':'causal_effect','weight':v,'detail':'affected\x20by\x20'+k['length']+'\x20other\x20file(s):\x20'+k['map'](w=>normalizeFile(w['trigger']?.['file']??''))['join'](',\x20')});}const l=readJsonl(EVENTS_PATH),m=normalizeFile(a),n=l['filter'](w=>{const x=(w['errorSignature']??'')+(w['rootCause']??'')+(w['fixApproach']??'');return x['includes'](m);});if(n['length']>0x0){const w=Math['min'](0x1e,n['length']*0xa);c+=w,d['push']({'source':'error_history','weight':w,'detail':n['length']+'\x20past\x20error(s)\x20involving\x20this\x20file'});}const o=extractLibraries(a);if(o['length']>0x0){const x=readJsonl(QUIRKS_PATH),y=x['filter'](z=>o['some'](A=>{const B=(z['library']??'')['split']('@')[0x0]['toLowerCase']();return B===A['toLowerCase']();}));if(y['length']>0x0){const z=Math['min'](0xf,y['length']*0x5);c+=z,d['push']({'source':'library_quirk','weight':z,'detail':y['length']+'\x20known\x20quirk(s):\x20'+y['map'](A=>A['library'])['join'](',\x20')});}}const p=Math['min'](0x64,c),q=p>=0x46?'high':p>=0x1e?'medium':'low',r={'file':a,'score':p,'level':q,'factors':d,'affectedFiles':e};return setCachedScore(a,r),r;}export function calculateBatchRisk(a){const b=a['map'](e=>calculateFileRisk(e)),c=b['length']>0x0?b['reduce']((e,f)=>f['score']>e['score']?f:e,b[0x0]):null,d=c&&c['score']>=0x46?'high':c&&c['score']>=0x1e?'medium':'low';return{'files':b,'maxRisk':c,'aggregateLevel':d};}