@routinecrew/routinecode 2.31.90 → 2.31.92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/prompt-vault.dat +1 -1
- package/bin/rc-credit-turn.js +1 -1
- package/bin/rc-grant.js +1 -1
- package/bin/rc-team.js +1 -1
- package/hooks/lib/codemode_guard.py +103 -1
- package/hooks/lib/copy_guard.py +330 -0
- package/hooks/lib/knowledge_items.py +158 -2
- package/hooks/lib/knowledge_scope.py +184 -4
- package/hooks/lib/repo_pollution.py +173 -0
- package/hooks/lib/skill_drafts.py +1 -1
- package/hooks/lib/work_kind.py +48 -5
- package/hooks/lib/work_kind_events.py +20 -17
- package/hooks/pre-agent-spawn.mjs +1 -1
- package/hooks/pre-bash-guard.sh +11 -0
- package/hooks/session-start.sh +8 -0
- package/mcp-dev-tester/dist/attestation.js +1 -1
- package/mcp-doc-fetcher/dist/index.js +1 -1
- package/mcp-intelligence/dist/concept-catalog.js +1 -1
- package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
- package/mcp-intelligence/dist/config-auth.js +1 -1
- package/mcp-intelligence/dist/contracts.generated.js +1 -1
- package/mcp-intelligence/dist/grounding.js +1 -1
- package/mcp-intelligence/dist/knowledge-critic.js +1 -1
- package/mcp-intelligence/dist/knowledge-guide.js +1 -1
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-migrate.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-intelligence/dist/knowledge-scope.js +1 -1
- package/mcp-intelligence/dist/provenance.js +1 -1
- package/mcp-intelligence/dist/semantic-embedder.js +1 -1
- package/mcp-log-watcher/dist/config-auth.js +1 -1
- package/mcp-log-watcher/dist/index.js +1 -1
- package/mcp-log-watcher/dist/known-solutions.js +1 -1
- package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-plan-manager/dist/index.js +1 -1
- package/mcp-project-context/dist/index.js +1 -1
- package/mcp-routinecode/dist/agent-tracker.js +1 -1
- package/mcp-routinecode/dist/attestation.js +1 -1
- package/mcp-routinecode/dist/blast-radius.js +1 -1
- package/mcp-routinecode/dist/board.js +1 -1
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/audit.js +1 -1
- package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/store.js +1 -1
- package/mcp-routinecode/dist/contracts.generated.js +1 -1
- package/mcp-routinecode/dist/design-judge.js +1 -1
- package/mcp-routinecode/dist/edit-tracker.js +1 -1
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
- package/mcp-routinecode/dist/index.js +1 -1
- package/mcp-routinecode/dist/known-solutions.js +1 -1
- package/mcp-routinecode/dist/ledger-miner.js +1 -1
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -1
- package/mcp-routinecode/dist/routines.js +1 -1
- package/mcp-routinecode/dist/rule-engine.js +1 -1
- package/mcp-routinecode/dist/rule-promoter.js +1 -1
- package/mcp-routinecode/dist/session-registry.js +1 -1
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/thinking-judge.js +1 -1
- package/mcp-routinecode/dist/verification.js +1 -1
- package/mcp-routinecode/dist/viral-loop.js +1 -1
- package/package.json +1 -1
- package/plugin/agents/analyzer.md.sealed +1 -1
- package/plugin/agents/architect.md.sealed +1 -1
- package/plugin/agents/crawler.md.sealed +1 -1
- package/plugin/agents/explorer.md.sealed +1 -1
- package/plugin/agents/implementor-lite.md.sealed +1 -1
- package/plugin/agents/implementor.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- package/plugin/agents/ops-lite.md.sealed +1 -1
- package/plugin/agents/planner.md.sealed +1 -1
- package/plugin/agents/recorder.md.sealed +1 -1
- package/plugin/agents/reviewer.md.sealed +1 -1
- package/plugin/agents/runner-lite.md.sealed +1 -1
- package/plugin/agents/verifier.md.sealed +1 -1
- package/plugin/commands/analyze.md.sealed +1 -1
- package/plugin/commands/plan.md.sealed +1 -1
- package/plugin/commands/rc.md.sealed +1 -1
- package/plugin/commands/receipt.md.sealed +1 -1
- package/plugin/commands/recharge.md.sealed +1 -1
- package/plugin/commands/routines.md.sealed +1 -1
- package/plugin/commands/share.md.sealed +1 -1
- package/plugin/routinecode-prompt.md.sealed +1 -1
|
@@ -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,ListResourcesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import{LogStore}from'./log-store.js';import{FileWatcher}from'./file-watcher.js';import{BrowserLogServer}from'./websocket-server.js';import{findKnownSolutions,formatBlock}from'./known-solutions.js';const logStore=new LogStore({'maxEntries':0x3e8,'retentionMinutes':0x3c}),fileWatcher=new FileWatcher(logStore),browserServer=new BrowserLogServer(logStore,0x270f);browserServer['start']();const watchPaths=process
|
|
2
|
+
import{Server}from'@modelcontextprotocol/sdk/server/index.js';import{StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import{CallToolRequestSchema,ListToolsRequestSchema,ListResourcesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import{LogStore}from'./log-store.js';import{FileWatcher}from'./file-watcher.js';import{BrowserLogServer}from'./websocket-server.js';import{findKnownSolutions,formatBlock}from'./known-solutions.js';const logStore=new LogStore({'maxEntries':0x3e8,'retentionMinutes':0x3c}),fileWatcher=new FileWatcher(logStore),browserServer=new BrowserLogServer(logStore,0x270f);browserServer['start']();const watchPaths=process['env']['LOG_WATCH_PATHS']?.['split'](',')||[];for(const watchPath of watchPaths){watchPath['trim']()&&fileWatcher['watch'](watchPath['trim']());}const server=new Server({'name':'mcp-log-watcher','version':'1.0.0'},{'capabilities':{'tools':{},'resources':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>{return{'tools':[{'name':'get_errors','description':'Get\x20recent\x20errors\x20from\x20browser\x20console\x20and\x20server\x20logs.\x20Use\x20this\x20to\x20see\x20what\x20errors\x20occurred\x20recently.','inputSchema':{'type':'object','properties':{'minutes':{'type':'number','description':'Get\x20errors\x20from\x20the\x20last\x20N\x20minutes\x20(default:\x2010)'},'source':{'type':'string','enum':['browser','server','file','all'],'description':'Filter\x20by\x20log\x20source\x20(default:\x20all)'}}}},{'name':'get_all_logs','description':'Get\x20all\x20collected\x20logs\x20including\x20errors,\x20warnings,\x20and\x20info\x20messages.','inputSchema':{'type':'object','properties':{'level':{'type':'string','enum':['error','warn','info','log','all'],'description':'Filter\x20by\x20log\x20level\x20(default:\x20all)'},'minutes':{'type':'number','description':'Get\x20logs\x20from\x20the\x20last\x20N\x20minutes\x20(default:\x2010)'},'limit':{'type':'number','description':'Maximum\x20number\x20of\x20logs\x20to\x20return\x20(default:\x2050)'}}}},{'name':'search_logs','description':'Search\x20logs\x20by\x20keyword\x20or\x20pattern.','inputSchema':{'type':'object','properties':{'query':{'type':'string','description':'Search\x20query\x20string'}},'required':['query']}},{'name':'get_log_summary','description':'Get\x20a\x20summary\x20of\x20collected\x20logs\x20including\x20counts\x20by\x20source\x20and\x20level.','inputSchema':{'type':'object','properties':{}}},{'name':'clear_logs','description':'Clear\x20all\x20collected\x20logs\x20or\x20logs\x20from\x20a\x20specific\x20source.','inputSchema':{'type':'object','properties':{'source':{'type':'string','enum':['browser','server','file','all'],'description':'Source\x20to\x20clear\x20(default:\x20all)'}}}},{'name':'watch_file','description':'Start\x20watching\x20a\x20new\x20log\x20file\x20for\x20errors.','inputSchema':{'type':'object','properties':{'path':{'type':'string','description':'Path\x20to\x20the\x20log\x20file\x20to\x20watch'}},'required':['path']}},{'name':'get_status','description':'Get\x20the\x20status\x20of\x20the\x20log\x20watcher\x20including\x20WebSocket\x20connections\x20and\x20watched\x20files.','inputSchema':{'type':'object','properties':{}}}]};}),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];switch(b){case'get_errors':{const d=c?.['minutes']||0xa,e=c?.['source'];let f=logStore['getRecentErrors'](d);e&&e!=='all'&&(f=f['filter'](k=>k['source']===e));if(f['length']===0x0)return{'content':[{'type':'text','text':'No\x20errors\x20found\x20in\x20the\x20last\x20'+d+'\x20minutes.'}]};const g=f['length'];f=f['slice'](-0x32);const h=logStore['formatForDisplay'](f),i=h['length']>0x3a98?h['slice'](0x0,0x3a98)+('\x0a\x0a---\x20truncated\x20('+h['length']+'\x20chars\x20total,\x20showing\x20first\x2015000)\x20---'):h;let j='';if(process['env']['ROUTINECODE_KI_INJECT']!=='off')try{const k=await findKnownSolutions(h,0x3);j=formatBlock(k);}catch{}return{'content':[{'type':'text','text':'Found\x20'+g+'\x20error(s)\x20in\x20the\x20last\x20'+d+'\x20minutes'+(g>0x32?'\x20(showing\x20last\x2050)':'')+':\x0a\x0a'+i+j}]};}case'get_all_logs':{const l=c?.['minutes']||0xa,m=c?.['level'],n=c?.['limit']||0x32;let o=logStore['getRecent'](l);m&&m!=='all'&&(o=o['filter'](p=>p['level']===m));o=o['slice'](-n);if(o['length']===0x0)return{'content':[{'type':'text','text':'No\x20logs\x20found\x20in\x20the\x20last\x20'+l+'\x20minutes.'}]};return{'content':[{'type':'text','text':'Found\x20'+o['length']+'\x20log(s):\x0a\x0a'+logStore['formatForDisplay'](o)}]};}case'search_logs':{const p=c?.['query'];if(!p)return{'content':[{'type':'text','text':'Error:\x20query\x20is\x20required'}],'isError':!![]};let q=logStore['search'](p);if(q['length']===0x0)return{'content':[{'type':'text','text':'No\x20logs\x20found\x20matching\x20\x22'+p+'\x22.'}]};const r=q['length'];q=q['slice'](-0x32);const s=logStore['formatForDisplay'](q),t=s['length']>0x3a98?s['slice'](0x0,0x3a98)+('\x0a\x0a---\x20truncated\x20('+s['length']+'\x20chars\x20total,\x20showing\x20first\x2015000)\x20---'):s;return{'content':[{'type':'text','text':'Found\x20'+r+'\x20log(s)\x20matching\x20\x22'+p+'\x22'+(r>0x32?'\x20(showing\x20last\x2050)':'')+':\x0a\x0a'+t}]};}case'get_log_summary':{const u=logStore['getSummary']();let v='Log\x20Summary\x0a\x0a';v+='Total\x20logs:\x20'+u['total']+'\x0a',v+='Recent\x20errors\x20(5min):\x20'+u['recentErrors']+'\x0a\x0a',v+='By\x20Source:\x0a';for(const [w,x]of Object['entries'](u['bySource'])){v+='\x20\x20-\x20'+w+':\x20'+x+'\x0a';}v+='\x0aBy\x20Level:\x0a';for(const [y,z]of Object['entries'](u['byLevel'])){const A=y==='error'?'[ERROR]':y==='warn'?'[WARN]':y==='info'?'[INFO]':'[LOG]';v+='\x20\x20-\x20'+A+'\x20'+y+':\x20'+z+'\x0a';}return v+='\x0aWebSocket\x20clients:\x20'+browserServer['getClientCount'](),{'content':[{'type':'text','text':v}]};}case'clear_logs':{const B=c?.['source'];if(B&&B!=='all')return logStore['clearBySource'](B),{'content':[{'type':'text','text':'Cleared\x20all\x20'+B+'\x20logs.'}]};return logStore['clear'](),{'content':[{'type':'text','text':'Cleared\x20all\x20logs.'}]};}case'watch_file':{const C=c?.['path'];if(!C)return{'content':[{'type':'text','text':'Error:\x20path\x20is\x20required'}],'isError':!![]};return fileWatcher['watch'](C),{'content':[{'type':'text','text':'Started\x20watching:\x20'+C}]};}case'get_status':{const D=logStore['getSummary']();let E='MCP\x20Log\x20Watcher\x20Status\x0a\x0a';return E+='WebSocket\x20server:\x20Running\x20on\x20port\x209999\x0a',E+='Connected\x20browsers:\x20'+browserServer['getClientCount']()+'\x0a',E+='Total\x20logs\x20collected:\x20'+D['total']+'\x0a',E+='Recent\x20errors\x20(5min):\x20'+D['recentErrors']+'\x0a',{'content':[{'type':'text','text':E}]};}default:return{'content':[{'type':'text','text':'Unknown\x20tool:\x20'+b}],'isError':!![]};}}),server['setRequestHandler'](ListResourcesRequestSchema,async()=>{return{'resources':[{'uri':'logs://recent-errors','mimeType':'text/plain','name':'Recent\x20Errors','description':'Recent\x20error\x20logs\x20from\x20browser\x20and\x20server'},{'uri':'logs://all','mimeType':'text/plain','name':'All\x20Logs','description':'All\x20collected\x20logs'}]};}),server['setRequestHandler'](ReadResourceRequestSchema,async a=>{const {uri:b}=a['params'];switch(b){case'logs://recent-errors':{const c=logStore['getRecentErrors'](0xa);return{'contents':[{'uri':b,'mimeType':'text/plain','text':c['length']>0x0?logStore['formatForDisplay'](c):'No\x20recent\x20errors.'}]};}case'logs://all':{const d=logStore['getAll']();return{'contents':[{'uri':b,'mimeType':'text/plain','text':d['length']>0x0?logStore['formatForDisplay'](d):'No\x20logs\x20collected.'}]};}default:throw new Error('Unknown\x20resource:\x20'+b);}}),process['on']('SIGINT',async()=>{console['error']('\x0a[MCP]\x20Shutting\x20down...'),browserServer['stop'](),await fileWatcher['close'](),process['exit'](0x0);}),process['on']('SIGTERM',async()=>{console['error']('\x0a[MCP]\x20Shutting\x20down...'),browserServer['stop'](),await fileWatcher['close'](),process['exit'](0x0);});async function main(){const a=new StdioServerTransport();await server['connect'](a),console['error']('[MCP]\x20Log\x20Watcher\x20server\x20started'),console['error']('[MCP]\x20WebSocket\x20server\x20running\x20on\x20ws://localhost:9999');}main()['catch'](a=>{console['error']('[MCP]\x20Fatal\x20error:',a),process['exit'](0x1);});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as a3a from'fs';import*as a3b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{knowledgeSendAllowed,logTransmission,sanitizeDeep}from'./sanitize.generated.js';const ROUTINECODE_DIR=process
|
|
1
|
+
import*as a3a from'fs';import*as a3b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{knowledgeSendAllowed,logTransmission,sanitizeDeep}from'./sanitize.generated.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']??a3b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']??a3b['join'](ROUTINECODE_DIR,'knowledge'),EVENTS_PATH=a3b['join'](KNOWLEDGE_DIR,'events.jsonl'),CONFIG_PATH=process['env']['ROUTINECODE_CONFIG_PATH']??a3b['join'](ROUTINECODE_DIR,'config.json'),USAGE_EVENTS_PATH=a3b['join'](ROUTINECODE_DIR,'usage','events.jsonl');export function emitExposure(a,b,c,d){try{const f={'kid':a,'kind':b,'path':c};if(d){if(d['k_author']!=null)f['k_author']=d['k_author'];if(d['k_problem']!=null)f['k_problem']=d['k_problem'];if(d['k_scope']!=null)f['k_scope']=d['k_scope'];}const g={'at':new Date()['toISOString'](),'date':new Date()['toISOString']()['slice'](0x0,0xa),'session':'unknown','type':'exposure','value':0x1,'metadata':f};a3a['mkdirSync'](a3b['dirname'](USAGE_EVENTS_PATH),{'recursive':!![]}),a3a['appendFileSync'](USAGE_EVENTS_PATH,JSON['stringify'](g)+'\x0a');}catch{}}const SIMILARITY_THRESHOLD=0.35,SENTINEL_OPEN='[KNOWN-SOLUTIONS-CTX]',SENTINEL_CLOSE='[/KNOWN-SOLUTIONS-CTX]',SERVER_TIMEOUT_MS=0x320;function trigramSimilarity(c,d){const f=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;},g=f(c),h=f(d);if(g['size']===0x0||h['size']===0x0)return 0x0;let i=0x0;for(const j of g)if(h['has'](j))i++;return i/Math['max'](g['size'],h['size']);}function tokenOverlap(c,d){const f=j=>j['toLowerCase']()['replace'](/[^a-z0-9가-힣\s]/g,'\x20'),g=new Set(f(c)['split'](/\s+/)['filter'](j=>j['length']>0x2)),h=new Set(f(d)['split'](/\s+/)['filter'](j=>j['length']>0x2));if(g['size']===0x0||h['size']===0x0)return 0x0;let i=0x0;for(const j of g)if(h['has'](j))i++;return i/Math['max'](g['size'],h['size']);}function localSimilarity(a,b){if(!a||!b)return 0x0;return trigramSimilarity(a,b)*0.4+tokenOverlap(a,b)*0.6;}const ERROR_LINE_RE=/(error|Error|ERROR|에러|오류|실패|failed|FAILED|cannot|Cannot|CANNOT|not found|ENOENT|TS\d{3,5}|Exception|exception|panic|Traceback|undefined|null|Unexpected|Invalid)/;export function extractErrorSignal(a){if(!a)return'';const b=a['split']('\x0a')['map'](f=>f['trim']())['filter'](Boolean),c=b['filter'](f=>ERROR_LINE_RE['test'](f)),d=(c['length']>0x0?c:b['slice'](-0x3))['slice'](0x0,0x5);return d['join']('\x20')['slice'](0x0,0x190);}let cachedEntries=null,cachedMtime=0x0;function loadEvents(){try{if(!a3a['existsSync'](EVENTS_PATH))return[];const a=a3a['statSync'](EVENTS_PATH)['mtimeMs'];if(cachedEntries&&cachedMtime===a)return cachedEntries;const b=a3a['readFileSync'](EVENTS_PATH,'utf-8')['trim']();if(!b)return cachedEntries=[],cachedMtime=a,[];return cachedEntries=b['split']('\x0a')['filter'](Boolean)['map'](c=>{try{return JSON['parse'](c);}catch{return null;}})['filter'](c=>c!==null),cachedMtime=a,cachedEntries;}catch{return[];}}function searchLocal(a,b){const c=loadEvents(),d=c['map'](f=>{const g=f['errorSignature']??'',h=f['rootCause']??'',i=Math['max'](localSimilarity(a,g)*0x1,localSimilarity(a,h)*0.8);return{'e':f,'score':i};})['filter'](f=>f['score']>=SIMILARITY_THRESHOLD)['sort']((f,g)=>g['score']-f['score'])['slice'](0x0,b);return d['map'](({e:f,score:g})=>({'source':'local','id':f['serverId']??null,'confidence':f['confidence']??Number(g['toFixed'](0x2)),'maturity':f['maturity']??'observation','errorSignature':f['errorSignature']??'','rootCause':f['rootCause']??'','fixApproach':f['fixApproach']??''}));}function loadConfig(){try{return JSON['parse'](a3a['readFileSync'](CONFIG_PATH,'utf-8'));}catch{return{};}}async function searchServer(a,b){const c=loadConfig();if(!knowledgeSendAllowed(c)||!c['serverUrl']||!c['apiKey'])return[];try{const d=sanitizeDeep({'query':a,'limit':b}),f=c['serverUrl']['replace'](/\/$/,'')+'/api/v1/search/semantic';logTransmission(f,d);const g=await fetch(f,{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+c['apiKey']},'body':JSON['stringify'](d),'signal':AbortSignal['timeout'](SERVER_TIMEOUT_MS)});if(!g['ok'])return noteAuthFailure(g['status']),[];const h=await g['json'](),i=Array['isArray'](h['results'])?h['results']:[];return i['slice'](0x0,b)['map'](j=>({'source':'community','id':typeof j['id']==='number'?j['id']:null,'confidence':typeof j['confidence']==='number'?j['confidence']:0x0,'maturity':typeof j['maturity']==='string'?j['maturity']:'observation','errorSignature':String(j['errorSignature']??''),'rootCause':String(j['rootCause']??''),'fixApproach':String(j['fixApproach']??''),'authorUserId':typeof j['authorUserId']==='number'?j['authorUserId']:undefined,'problemKey':typeof j['problemKey']==='string'?j['problemKey']:undefined,'scope':typeof j['scope']==='string'?j['scope']:undefined}));}catch{return[];}}function sanitizeForOutput(a){return a['replace'](/"/g,'\x27')['replace'](/[A-Za-z0-9_\-]{32,}/g,'[REDACTED]')['replace'](/\b(sk|pk|ghp|xox[baprs])[-_][A-Za-z0-9]{10,}/gi,'[REDACTED]');}export function formatBlock(a){if(a['length']===0x0)return'';for(const c of a){c['id']!=null&&emitExposure('ef:'+c['id'],'error-fix','inject:T1',{'k_author':c['authorUserId'],'k_problem':c['problemKey'],'k_scope':c['scope']});}const b=a['map']((d,f)=>{const g=d['id']!=null?d['source']+'\x20id:'+d['id']:d['source'];return[f+0x1+'.\x20('+g+',\x20confidence:'+d['confidence']+',\x20maturity:'+d['maturity']+')','\x20\x20\x20error:\x20'+sanitizeForOutput(d['errorSignature']['slice'](0x0,0x78)),'\x20\x20\x20cause:\x20'+sanitizeForOutput(d['rootCause']['slice'](0x0,0xc8)),'\x20\x20\x20fix:\x20\x20\x20'+sanitizeForOutput(d['fixApproach']['slice'](0x0,0xc8))]['join']('\x0a');});return['\x0a\x0a'+SENTINEL_OPEN,'[KNOWN\x20SOLUTIONS]\x20'+a['length']+'\x20similar\x20past\x20error(s)\x20found\x20for\x20this\x20failure:',...b,'Reference\x20only\x20—\x20verify\x20against\x20current\x20code\x20before\x20applying.',''+SENTINEL_CLOSE]['join']('\x0a');}export async function findKnownSolutions(a,b=0x3){if(!a||a['trim']()['length']===0x0)return[];const c=extractErrorSignal(a),d=c||a,f=searchLocal(d,b),g=await searchServer(d,b),h=[...f];for(const j of g){const k=h['some'](l=>localSimilarity(l['errorSignature'],j['errorSignature'])>0.85);if(!k)h['push'](j);}const i=h['sort']((l,m)=>m['confidence']-l['confidence'])['slice'](0x0,b);for(const l of i){l['id']!=null&&emitExposure('ef:'+l['id'],'error-fix','search',{'k_author':l['authorUserId'],'k_problem':l['problemKey'],'k_scope':l['scope']});}return i;}export function communityRefs(a){return a['filter'](b=>b['source']==='community'&&b['id']!=null)['map'](b=>b['id']);}const OBSERVED_DIR=a3b['join'](KNOWLEDGE_DIR,'observed'),PENDING_PATH=a3b['join'](KNOWLEDGE_DIR,'pending-sync.jsonl');function projectHash(a){let b=0x0;for(let c=0x0;c<a['length'];c++){b=b*0x1f+a['charCodeAt'](c)|0x0;}return(b>>>0x0)['toString'](0x10);}function draftPath(a){return a3b['join'](OBSERVED_DIR,'draft-'+projectHash(a)+'.json');}const LOCK_STALE_MS=0x1388;function acquireLock(a){const b=a+'.lock';for(let c=0x0;c<0x32;c++){try{const d=a3a['openSync'](b,'wx');return a3a['closeSync'](d),b;}catch{try{const g=a3a['statSync'](b);if(Date['now']()-g['mtimeMs']>LOCK_STALE_MS){a3a['unlinkSync'](b);continue;}}catch{}const f=Date['now']()+0x14;while(Date['now']()<f){}}}return null;}function releaseLock(a){try{a3a['unlinkSync'](a);}catch{}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeAll,afterAll}from'vitest';import{mkdtempSync,writeFileSync,existsSync,readFileSync,rmSync,realpathSync}from'fs';import{tmpdir}from'os';import{join}from'path';import{updateWaveState}from'../file-ops.js';describe('updateWaveState\x20—\x20KNOWLEDGE_DIR',()=>{const a=realpathSync(mkdtempSync(join(tmpdir(),'rc-pm-kd-'))),b=join(a,'kd'),c=join(a,'home'),d={'kd':process
|
|
1
|
+
import{describe,it,expect,beforeAll,afterAll}from'vitest';import{mkdtempSync,writeFileSync,existsSync,readFileSync,rmSync,realpathSync}from'fs';import{tmpdir}from'os';import{join}from'path';import{updateWaveState}from'../file-ops.js';describe('updateWaveState\x20—\x20KNOWLEDGE_DIR',()=>{const a=realpathSync(mkdtempSync(join(tmpdir(),'rc-pm-kd-'))),b=join(a,'kd'),c=join(a,'home'),d={'kd':process['env']['ROUTINECODE_KNOWLEDGE_DIR'],'home':process['env']['HOME']};beforeAll(()=>{process['env']['ROUTINECODE_KNOWLEDGE_DIR']=b,process['env']['HOME']=c;}),afterAll(()=>{if(d['kd']===undefined)delete process['env']['ROUTINECODE_KNOWLEDGE_DIR'];else process['env']['ROUTINECODE_KNOWLEDGE_DIR']=d['kd'];if(d['home']===undefined)delete process['env']['HOME'];else process['env']['HOME']=d['home'];rmSync(a,{'recursive':!![],'force':!![]});}),it('wave-state.json\x20을\x20ROUTINECODE_KNOWLEDGE_DIR\x20에\x20쓰고\x20HOME\x20기본\x20경로는\x20건드리지\x20않는다',async()=>{const e=join(a,'p.md');writeFileSync(e,'#\x20Plan\x0a\x0a-\x20[x]\x201.\x20First\x0a-\x20[\x20]\x202.\x20Second\x0a');const f=await updateWaveState(a,e,'1');expect(f)['not']['toBeNull']();const g=join(b,'wave-state.json');expect(existsSync(g))['toBe'](!![]),expect(JSON['parse'](readFileSync(g,'utf-8'))['planName'])['toBe']('p'),expect(existsSync(join(c,'.routinecode','knowledge','wave-state.json')))['toBe'](![]);});});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile,mkdir,rm,readdir}from'fs/promises';import{join,basename}from'path';import{homedir}from'os';import{parsePlanProgress,generateWaveStructure}from'./plan-parser.js';const PLAN_SKELETON='#\x20{TITLE}\x0a\x0a##\x20TL;DR\x0a\x0a>\x20**Quick\x20Summary**:\x20{SUMMARY}\x0a>\x0a>\x20**Deliverables**:\x0a>\x20-\x20(to\x20be\x20defined)\x0a>\x0a>\x20**Estimated\x20Effort**:\x20Medium\x0a>\x20**Parallel\x20Execution**:\x20YES\x0a>\x20**Critical\x20Path**:\x20(to\x20be\x20determined)\x0a\x0a---\x0a\x0a##\x20Context\x0a\x0a###\x20Original\x20Request\x0a{OBJECTIVES}\x0a\x0a###\x20Interview\x20Summary\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a###\x20Analyzer\x20Review\x0a(to\x20be\x20filled\x20after\x20Analyzer\x20consultation)\x0a\x0a---\x0a\x0a##\x20요청\x20원문\x0a(사용자\x20요청을\x20그대로\x20붙인다.\x20요약·축약\x20금지\x20—\x20사고\x20심판의\x20기준이\x20된다)\x0a\x0a##\x20기준\x20카드\x0a(태스크보다\x20먼저\x20쓴다.\x20외부\x20기준은\x20출처가\x20있어야\x20한다:\x20원문\x20\x22인용\x22\x20/\x20문서\x20URL\x20/\x20데이터·정답예시\x20경로\x20/\x20미확인(필수\x20불가).\x20관점마다\x20기준\x201개\x20이상)\x0a목적:\x20{OBJECTIVES}\x0a관점:\x20{이해관계자,\x20쉼표\x20구분}\x0a|\x20id\x20|\x20관점\x20|\x20외부\x20기준\x20|\x20출처\x20|\x20필수\x20|\x20projectDir\x20|\x20verify\x20|\x0a|----|------|-----------|------|------|------------|--------|\x0a|\x20C1\x20|\x20{관점}\x20|\x20{기준}\x20|\x20원문:\x20\x22{요청\x20원문\x20속\x20인용}\x22\x20|\x20Y\x20|\x20`.`\x20|\x20`{run_tests\x20허용\x20명령\x20또는\x20manual:\x20<명령>}`\x20|\x0a하지\x20않을\x20것:\x20(to\x20be\x20defined)\x0a\x0a##\x20깊이\x0a(전문가가\x20안\x20시킨\x20일\x20/\x20원자료\x20file:line\x20/\x20방법·도구\x20/\x20맞다는\x20증거,\x20그리고\x20위험)\x0a\x0a##\x20범위\x0a(동사로\x20다시\x20쓴\x20일\x20+\x20분야\x20≤3,\x20분야마다\x20결과물)\x0a\x0a##\x20검토했으나\x20제외\x0a(고려했지만\x20하지\x20않기로\x20한\x20것과\x20이유,\x20한\x20줄씩)\x0a\x0a---\x0a\x0a##\x20Verification\x20Strategy\x0a\x0a>\x20**ZERO\x20HUMAN\x20INTERVENTION**\x20—\x20ALL\x20verification\x20is\x20agent-executed.\x0a\x0a###\x20Test\x20Decision\x0a-\x20**Infrastructure\x20exists**:\x20(to\x20be\x20checked)\x0a-\x20**Automated\x20tests**:\x20(to\x20be\x20decided)\x0a\x0a---\x0a\x0a##\x20Execution\x20Strategy\x0a\x0a###\x20Parallel\x20Execution\x20Waves\x0a(to\x20be\x20generated\x20after\x20tasks\x20are\x20defined)\x0a\x0a---\x0a\x0a##\x20TODOs\x0a\x0a---\x0a\x0a##\x20Final\x20Verification\x20Wave\x0a\x0a-\x20[\x20]\x20F1.\x20**Plan\x20Compliance\x20Audit**\x0a-\x20[\x20]\x20F2.\x20**Code\x20Quality\x20Review**\x0a-\x20[\x20]\x20F3.\x20**Real\x20QA**\x0a-\x20[\x20]\x20F4.\x20**Scope\x20Fidelity\x20Check**\x0a\x0a---\x0a\x0a##\x20Commit\x20Strategy\x0a(to\x20be\x20defined)\x0a\x0a---\x0a\x0a##\x20Success\x20Criteria\x0a-\x20[\x20]\x20All\x20\x22Must\x20Have\x22\x20present\x0a-\x20[\x20]\x20All\x20\x22Must\x20NOT\x20Have\x22\x20absent\x0a-\x20[\x20]\x20All\x20tests\x20pass\x0a';export async function appendTasksToPlan(a,b){let c=await readFile(a,'utf-8');const d='##\x20Final\x20Verification\x20Wave',e=c['indexOf'](d);if(e===-0x1)throw new Error('Plan\x20file\x20missing\x20\x22##\x20Final\x20Verification\x20Wave\x22\x20section');let f='';for(const g of b){f+='-\x20[\x20]\x20'+g['id']+'.\x20'+g['title']+'\x0a\x0a',f+='\x20\x20**What\x20to\x20do**:\x0a\x20\x20'+g['whatToDo']+'\x0a\x0a';g['mustNot']&&(f+='\x20\x20**Must\x20NOT\x20do**:\x0a\x20\x20'+g['mustNot']+'\x0a\x0a');if(g['category']||g['skills']){f+='\x20\x20**Recommended\x20Agent\x20Profile**:\x0a';if(g['category'])f+='\x20\x20-\x20**Category**:\x20`'+g['category']+'`\x0a';if(g['skills']?.['length'])f+='\x20\x20-\x20**Skills**:\x20['+g['skills']['map'](h=>'`'+h+'`')['join'](',\x20')+']\x0a';f+='\x0a';}(g['dependsOn']?.['length']||g['blocks']?.['length'])&&(f+='\x20\x20**Parallelization**:\x0a',f+='\x20\x20-\x20**Blocked\x20By**:\x20'+(g['dependsOn']?.['length']?g['dependsOn']['join'](',\x20'):'None')+'\x0a',f+='\x20\x20-\x20**Blocks**:\x20'+(g['blocks']?.['length']?g['blocks']['join'](',\x20'):'None')+'\x0a',f+='\x0a'),g['references']&&(f+='\x20\x20**References**:\x0a\x20\x20'+g['references']+'\x0a\x0a'),g['qaScenarios']&&(f+='\x20\x20**QA\x20Scenarios**:\x0a\x20\x20'+g['qaScenarios']+'\x0a\x0a');}c=c['slice'](0x0,e)+f+'\x0a'+c['slice'](e),await writeFile(a,c,'utf-8');}const DRAFT_TEMPLATE='#\x20Draft:\x20{NAME}\x0a\x0a##\x20Requirements\x20(confirmed)\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Technical\x20Decisions\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Research\x20Findings\x0a(to\x20be\x20filled\x20from\x20explorer/crawler\x20results)\x0a\x0a##\x20Open\x20Questions\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Scope\x20Boundaries\x0a-\x20INCLUDE:\x20(to\x20be\x20defined)\x0a-\x20EXCLUDE:\x20(to\x20be\x20defined)\x0a';export async function updateDraft(a,b,c,d){const e=join(a,'.routinecode','drafts',b+'.md');let f=await readFile(e,'utf-8');const g='##\x20'+c,h=f['indexOf'](g);if(h===-0x1)f+='\x0a'+g+'\x0a'+d+'\x0a';else{const i=h+g['length'],j=f['indexOf']('\x0a##\x20',i),k=j===-0x1?f['length']:j;f=f['slice'](0x0,i)+'\x0a'+d+'\x0a'+f['slice'](k);}await writeFile(e,f,'utf-8');}export async function deleteDraft(a,b){const c=join(a,'.routinecode','drafts',b+'.md');try{await rm(c);}catch{}}const NOTEPAD_FILES=['learnings.md','decisions.md','issues.md','problems.md'];export async function appendToNotepad(a,b,c,d,e){const f=join(a,'.routinecode','notepads',b,c+'.md');let g='';try{g=await readFile(f,'utf-8');}catch{g='#\x20'+(c['charAt'](0x0)['toUpperCase']()+c['slice'](0x1))+'\x0a\x0a';}const h=new Date()['toISOString']()['slice'](0x0,0x13)['replace']('T','\x20'),i=e?'##\x20['+h+']\x20Task:\x20'+e+'\x0a'+d+'\x0a\x0a':'##\x20['+h+']\x0a'+d+'\x0a\x0a';await writeFile(f,g+i,'utf-8');}const MAX_WISDOM_ENTRIES=0x1e,MAX_WISDOM_CHARS=0x3a98;export async function getInheritedWisdom(a,b){const c=join(a,'.routinecode','notepads',b),d=[];for(const f of NOTEPAD_FILES){try{const g=await readFile(join(c,f),'utf-8');if(g['trim']()['split']('\x0a')['length']>0x2){const h=g['split'](/^(?=## \[)/m)['filter'](Boolean),i=h[0x0]?.['startsWith']('#')&&!h[0x0]?.['startsWith']('##\x20[')?h['shift']():'',j=h['slice'](-MAX_WISDOM_ENTRIES);d['push'](((i??'')+j['join'](''))['trim']());}}catch{}}if(d['length']===0x0)return'(no\x20accumulated\x20wisdom\x20yet)';let e=d['join']('\x0a\x0a---\x0a\x0a');return e['length']>MAX_WISDOM_CHARS&&(e=e['slice'](0x0,MAX_WISDOM_CHARS)+('\x0a\x0a---\x20truncated\x20('+e['length']+'\x20chars\x20total)\x20---')),e;}const sessionStore=new Map();export async function verifyEvidence(a,b,c){const d=process
|
|
1
|
+
import{readFile,writeFile,mkdir,rm,readdir}from'fs/promises';import{join,basename}from'path';import{homedir}from'os';import{parsePlanProgress,generateWaveStructure}from'./plan-parser.js';const PLAN_SKELETON='#\x20{TITLE}\x0a\x0a##\x20TL;DR\x0a\x0a>\x20**Quick\x20Summary**:\x20{SUMMARY}\x0a>\x0a>\x20**Deliverables**:\x0a>\x20-\x20(to\x20be\x20defined)\x0a>\x0a>\x20**Estimated\x20Effort**:\x20Medium\x0a>\x20**Parallel\x20Execution**:\x20YES\x0a>\x20**Critical\x20Path**:\x20(to\x20be\x20determined)\x0a\x0a---\x0a\x0a##\x20Context\x0a\x0a###\x20Original\x20Request\x0a{OBJECTIVES}\x0a\x0a###\x20Interview\x20Summary\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a###\x20Analyzer\x20Review\x0a(to\x20be\x20filled\x20after\x20Analyzer\x20consultation)\x0a\x0a---\x0a\x0a##\x20요청\x20원문\x0a(사용자\x20요청을\x20그대로\x20붙인다.\x20요약·축약\x20금지\x20—\x20사고\x20심판의\x20기준이\x20된다)\x0a\x0a##\x20기준\x20카드\x0a(태스크보다\x20먼저\x20쓴다.\x20외부\x20기준은\x20출처가\x20있어야\x20한다:\x20원문\x20\x22인용\x22\x20/\x20문서\x20URL\x20/\x20데이터·정답예시\x20경로\x20/\x20미확인(필수\x20불가).\x20관점마다\x20기준\x201개\x20이상)\x0a목적:\x20{OBJECTIVES}\x0a관점:\x20{이해관계자,\x20쉼표\x20구분}\x0a|\x20id\x20|\x20관점\x20|\x20외부\x20기준\x20|\x20출처\x20|\x20필수\x20|\x20projectDir\x20|\x20verify\x20|\x0a|----|------|-----------|------|------|------------|--------|\x0a|\x20C1\x20|\x20{관점}\x20|\x20{기준}\x20|\x20원문:\x20\x22{요청\x20원문\x20속\x20인용}\x22\x20|\x20Y\x20|\x20`.`\x20|\x20`{run_tests\x20허용\x20명령\x20또는\x20manual:\x20<명령>}`\x20|\x0a하지\x20않을\x20것:\x20(to\x20be\x20defined)\x0a\x0a##\x20깊이\x0a(전문가가\x20안\x20시킨\x20일\x20/\x20원자료\x20file:line\x20/\x20방법·도구\x20/\x20맞다는\x20증거,\x20그리고\x20위험)\x0a\x0a##\x20범위\x0a(동사로\x20다시\x20쓴\x20일\x20+\x20분야\x20≤3,\x20분야마다\x20결과물)\x0a\x0a##\x20검토했으나\x20제외\x0a(고려했지만\x20하지\x20않기로\x20한\x20것과\x20이유,\x20한\x20줄씩)\x0a\x0a---\x0a\x0a##\x20Verification\x20Strategy\x0a\x0a>\x20**ZERO\x20HUMAN\x20INTERVENTION**\x20—\x20ALL\x20verification\x20is\x20agent-executed.\x0a\x0a###\x20Test\x20Decision\x0a-\x20**Infrastructure\x20exists**:\x20(to\x20be\x20checked)\x0a-\x20**Automated\x20tests**:\x20(to\x20be\x20decided)\x0a\x0a---\x0a\x0a##\x20Execution\x20Strategy\x0a\x0a###\x20Parallel\x20Execution\x20Waves\x0a(to\x20be\x20generated\x20after\x20tasks\x20are\x20defined)\x0a\x0a---\x0a\x0a##\x20TODOs\x0a\x0a---\x0a\x0a##\x20Final\x20Verification\x20Wave\x0a\x0a-\x20[\x20]\x20F1.\x20**Plan\x20Compliance\x20Audit**\x0a-\x20[\x20]\x20F2.\x20**Code\x20Quality\x20Review**\x0a-\x20[\x20]\x20F3.\x20**Real\x20QA**\x0a-\x20[\x20]\x20F4.\x20**Scope\x20Fidelity\x20Check**\x0a\x0a---\x0a\x0a##\x20Commit\x20Strategy\x0a(to\x20be\x20defined)\x0a\x0a---\x0a\x0a##\x20Success\x20Criteria\x0a-\x20[\x20]\x20All\x20\x22Must\x20Have\x22\x20present\x0a-\x20[\x20]\x20All\x20\x22Must\x20NOT\x20Have\x22\x20absent\x0a-\x20[\x20]\x20All\x20tests\x20pass\x0a';export async function appendTasksToPlan(a,b){let c=await readFile(a,'utf-8');const d='##\x20Final\x20Verification\x20Wave',e=c['indexOf'](d);if(e===-0x1)throw new Error('Plan\x20file\x20missing\x20\x22##\x20Final\x20Verification\x20Wave\x22\x20section');let f='';for(const g of b){f+='-\x20[\x20]\x20'+g['id']+'.\x20'+g['title']+'\x0a\x0a',f+='\x20\x20**What\x20to\x20do**:\x0a\x20\x20'+g['whatToDo']+'\x0a\x0a';g['mustNot']&&(f+='\x20\x20**Must\x20NOT\x20do**:\x0a\x20\x20'+g['mustNot']+'\x0a\x0a');if(g['category']||g['skills']){f+='\x20\x20**Recommended\x20Agent\x20Profile**:\x0a';if(g['category'])f+='\x20\x20-\x20**Category**:\x20`'+g['category']+'`\x0a';if(g['skills']?.['length'])f+='\x20\x20-\x20**Skills**:\x20['+g['skills']['map'](h=>'`'+h+'`')['join'](',\x20')+']\x0a';f+='\x0a';}(g['dependsOn']?.['length']||g['blocks']?.['length'])&&(f+='\x20\x20**Parallelization**:\x0a',f+='\x20\x20-\x20**Blocked\x20By**:\x20'+(g['dependsOn']?.['length']?g['dependsOn']['join'](',\x20'):'None')+'\x0a',f+='\x20\x20-\x20**Blocks**:\x20'+(g['blocks']?.['length']?g['blocks']['join'](',\x20'):'None')+'\x0a',f+='\x0a'),g['references']&&(f+='\x20\x20**References**:\x0a\x20\x20'+g['references']+'\x0a\x0a'),g['qaScenarios']&&(f+='\x20\x20**QA\x20Scenarios**:\x0a\x20\x20'+g['qaScenarios']+'\x0a\x0a');}c=c['slice'](0x0,e)+f+'\x0a'+c['slice'](e),await writeFile(a,c,'utf-8');}const DRAFT_TEMPLATE='#\x20Draft:\x20{NAME}\x0a\x0a##\x20Requirements\x20(confirmed)\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Technical\x20Decisions\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Research\x20Findings\x0a(to\x20be\x20filled\x20from\x20explorer/crawler\x20results)\x0a\x0a##\x20Open\x20Questions\x0a(to\x20be\x20filled\x20during\x20interview)\x0a\x0a##\x20Scope\x20Boundaries\x0a-\x20INCLUDE:\x20(to\x20be\x20defined)\x0a-\x20EXCLUDE:\x20(to\x20be\x20defined)\x0a';export async function updateDraft(a,b,c,d){const e=join(a,'.routinecode','drafts',b+'.md');let f=await readFile(e,'utf-8');const g='##\x20'+c,h=f['indexOf'](g);if(h===-0x1)f+='\x0a'+g+'\x0a'+d+'\x0a';else{const i=h+g['length'],j=f['indexOf']('\x0a##\x20',i),k=j===-0x1?f['length']:j;f=f['slice'](0x0,i)+'\x0a'+d+'\x0a'+f['slice'](k);}await writeFile(e,f,'utf-8');}export async function deleteDraft(a,b){const c=join(a,'.routinecode','drafts',b+'.md');try{await rm(c);}catch{}}const NOTEPAD_FILES=['learnings.md','decisions.md','issues.md','problems.md'];export async function appendToNotepad(a,b,c,d,e){const f=join(a,'.routinecode','notepads',b,c+'.md');let g='';try{g=await readFile(f,'utf-8');}catch{g='#\x20'+(c['charAt'](0x0)['toUpperCase']()+c['slice'](0x1))+'\x0a\x0a';}const h=new Date()['toISOString']()['slice'](0x0,0x13)['replace']('T','\x20'),i=e?'##\x20['+h+']\x20Task:\x20'+e+'\x0a'+d+'\x0a\x0a':'##\x20['+h+']\x0a'+d+'\x0a\x0a';await writeFile(f,g+i,'utf-8');}const MAX_WISDOM_ENTRIES=0x1e,MAX_WISDOM_CHARS=0x3a98;export async function getInheritedWisdom(a,b){const c=join(a,'.routinecode','notepads',b),d=[];for(const f of NOTEPAD_FILES){try{const g=await readFile(join(c,f),'utf-8');if(g['trim']()['split']('\x0a')['length']>0x2){const h=g['split'](/^(?=## \[)/m)['filter'](Boolean),i=h[0x0]?.['startsWith']('#')&&!h[0x0]?.['startsWith']('##\x20[')?h['shift']():'',j=h['slice'](-MAX_WISDOM_ENTRIES);d['push'](((i??'')+j['join'](''))['trim']());}}catch{}}if(d['length']===0x0)return'(no\x20accumulated\x20wisdom\x20yet)';let e=d['join']('\x0a\x0a---\x0a\x0a');return e['length']>MAX_WISDOM_CHARS&&(e=e['slice'](0x0,MAX_WISDOM_CHARS)+('\x0a\x0a---\x20truncated\x20('+e['length']+'\x20chars\x20total)\x20---')),e;}const sessionStore=new Map();export async function verifyEvidence(a,b,c){const d=process['env']['ROUTINECODE_EVIDENCE_DIR']||join(homedir(),'.routinecode','evidence'),e=join(d,b,'task-'+c),f=[];try{const g=await readdir(e);f['push'](...g);}catch{}return{'found':f,'missing':f['length']===0x0};}export async function updateWaveState(a,b,c){const d=await readFile(b,'utf-8'),e=parsePlanProgress(d),f=generateWaveStructure(e['tasks']);if(f['waves']['length']===0x0)return null;const g=new Set(e['tasks']['filter'](r=>r['status']==='completed')['map'](r=>r['id']));let h=0x0;for(const r of f['waves']){if(r['tasks']['some'](s=>s['id']===c)){h=r['number'];break;}}const i=e['tasks']['map'](s=>s['id']),j=e['tasks']['filter'](s=>s['status']==='completed')['map'](s=>s['id']),k=[],l=generateWaveStructure(e['tasks']['map'](s=>({...s,'status':'pending'})));for(const s of l['waves']){const t=s['tasks']['every'](u=>g['has'](u['id']));if(t)k['push'](s['number']);}const m=k['length']<l['waves']['length']?k['length']+0x1:l['waves']['length'],n=h>0x0&&k['includes'](h),o=basename(b,'.md'),p=process['env']['ROUTINECODE_KNOWLEDGE_DIR']||join(homedir(),'.routinecode','knowledge');await mkdir(p,{'recursive':!![]});const q={'planName':o,'planPath':b,'currentWave':m,'totalWaves':l['waves']['length'],'completedWaves':k,'tasks':i,'completedTasks':j,'status':j['length']>=i['length']?'completed':'in_progress','updatedAt':new Date()['toISOString']()};return await writeFile(join(p,'wave-state.json'),JSON['stringify'](q,null,0x2),'utf-8'),{'currentWave':m,'totalWaves':l['waves']['length'],'waveComplete':n};}
|
|
@@ -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{readFile,writeFile}from'fs/promises';import{parsePlanProgress,markTaskComplete,unmarkTaskComplete,getExecutableTasks,generateWaveStructure,extractFileReferences,extractTaskFileReferences,checkQaCompleteness}from'./plan-parser.js';import{appendTasksToPlan,updateDraft,deleteDraft,appendToNotepad,getInheritedWisdom,verifyEvidence,updateWaveState}from'./file-ops.js';const BASE_PATH=process.env.PROJECT_PATH||process['cwd'](),server=new Server({'name':'mcp-plan-manager','version':'1.0.0'},{'capabilities':{'tools':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>({'tools':[{'name':'append_tasks_to_plan','description':'Append\x20tasks\x20to\x20an\x20existing\x20plan\x20file\x20before\x20the\x20Final\x20Verification\x20Wave\x20section.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Absolute\x20path\x20to\x20plan\x20file'},'tasks':{'type':'array','items':{'type':'object','properties':{'id':{'type':'string'},'title':{'type':'string'},'whatToDo':{'type':'string'},'mustNot':{'type':'string'},'category':{'type':'string'},'skills':{'type':'array','items':{'type':'string'}},'dependsOn':{'type':'array','items':{'type':'string'}},'blocks':{'type':'array','items':{'type':'string'}},'references':{'type':'string'},'qaScenarios':{'type':'string'}},'required':['id','title','whatToDo']},'description':'Array\x20of\x20tasks\x20to\x20append'}},'required':['plan_path','tasks']}},{'name':'parse_plan_progress','description':'Parse\x20a\x20plan\x20file\x20and\x20return\x20progress:\x20total,\x20completed,\x20remaining\x20tasks\x20with\x20metadata.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'mark_task_complete','description':'Mark\x20a\x20task\x20as\x20completed\x20by\x20changing\x20[\x20]\x20to\x20[x]\x20in\x20the\x20plan\x20file.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20number\x20to\x20mark\x20complete'}},'required':['plan_path','task_id']}},{'name':'unmark_task_complete','description':'Revert\x20a\x20completed\x20task\x20back\x20to\x20pending\x20by\x20changing\x20[x]\x20to\x20[\x20]\x20in\x20the\x20plan\x20file.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20number\x20to\x20unmark'}},'required':['plan_path','task_id']}},{'name':'get_executable_tasks','description':'Get\x20tasks\x20whose\x20dependencies\x20are\x20all\x20satisfied\x20and\x20can\x20be\x20executed\x20now.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'generate_wave_structure','description':'Generate\x20Wave-based\x20parallel\x20execution\x20structure\x20from\x20task\x20dependencies.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'extract_file_references','description':'Extract\x20all\x20file\x20path\x20references\x20from\x20a\x20plan\x20file\x20for\x20validation.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'extract_task_file_references','description':'Extract\x20file\x20path\x20references\x20scoped\x20to\x20a\x20specific\x20task\x20section\x20only.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20ID\x20to\x20scope\x20extraction\x20to'}},'required':['plan_path','task_id']}},{'name':'check_qa_completeness','description':'Check\x20which\x20tasks\x20have\x20QA\x20scenarios\x20defined\x20and\x20which\x20are\x20missing.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'update_draft','description':'Update\x20a\x20specific\x20section\x20in\x20a\x20draft\x20file.','inputSchema':{'type':'object','properties':{'name':{'type':'string','description':'Draft\x20name'},'section':{'type':'string','description':'Section\x20header\x20(e.g.\x20\x22Requirements\x20(confirmed)\x22)'},'content':{'type':'string','description':'New\x20content\x20for\x20this\x20section'}},'required':['name','section','content']}},{'name':'delete_draft','description':'Delete\x20a\x20draft\x20file\x20after\x20plan\x20generation.','inputSchema':{'type':'object','properties':{'name':{'type':'string','description':'Draft\x20name'}},'required':['name']}},{'name':'append_to_notepad','description':'Append\x20an\x20entry\x20to\x20a\x20notepad\x20category\x20file.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'},'category':{'type':'string','enum':['learnings','decisions','issues','problems'],'description':'Notepad\x20category'},'content':{'type':'string','description':'Content\x20to\x20append'},'task_id':{'type':'string','description':'Optional\x20related\x20task\x20ID'}},'required':['plan_name','category','content']}},{'name':'get_inherited_wisdom','description':'Read\x20all\x20notepad\x20files\x20and\x20return\x20accumulated\x20wisdom\x20for\x20delegation\x20prompts.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'}},'required':['plan_name']}},{'name':'verify_evidence','description':'Check\x20if\x20evidence\x20files\x20exist\x20for\x20a\x20completed\x20task.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'},'task_id':{'type':'string','description':'Task\x20ID\x20to\x20check'}},'required':['plan_name','task_id']}}]})),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];try{switch(b){case'append_tasks_to_plan':{return await appendTasksToPlan(c['plan_path'],c['tasks']),ok('Appended\x20'+c['tasks']['length']+'\x20tasks\x20to\x20plan');}case'parse_plan_progress':{const d=await readFile(c['plan_path'],'utf-8'),e=parsePlanProgress(d);return ok(JSON['stringify'](e,null,0x2));}case'mark_task_complete':{const f=c['plan_path'],g=c['task_id'],h=await readFile(f,'utf-8'),i=markTaskComplete(h,g);await writeFile(f,i,'utf-8');const j=await updateWaveState(BASE_PATH,f,g);if(j){const k=j['waveComplete']?'\x20|\x20Wave\x20'+j['currentWave']+'/'+j['totalWaves']+'\x20COMPLETE':'\x20|\x20Wave\x20'+j['currentWave']+'/'+j['totalWaves']+'\x20in\x20progress';return ok('Task\x20'+g+'\x20marked\x20complete'+k);}return ok('Task\x20'+g+'\x20marked\x20complete');}case'unmark_task_complete':{const l=await readFile(c['plan_path'],'utf-8'),m=unmarkTaskComplete(l,c['task_id']);return await writeFile(c['plan_path'],m,'utf-8'),ok('Task\x20'+c['task_id']+'\x20unmarked\x20(reverted\x20to\x20pending)');}case'get_executable_tasks':{const n=await readFile(c['plan_path'],'utf-8'),o=parsePlanProgress(n),p=o['tasks']['filter'](r=>r['status']==='completed')['map'](r=>r['id']),q=getExecutableTasks(o['tasks'],p);return ok(JSON['stringify']({'executable_count':q['length'],'tasks':q['map'](r=>({'id':r['id'],'title':r['title'],'category':r['category'],'skills':r['skills']}))},null,0x2));}case'generate_wave_structure':{const r=await readFile(c['plan_path'],'utf-8'),s=parsePlanProgress(r),t=generateWaveStructure(s['tasks']);let u='';for(const v of t['waves']){u+='\x0aWave\x20'+v['number']+'\x20('+v['tasks']['length']+'\x20tasks):\x0a';for(const w of v['tasks']){u+='\x20\x20-\x20Task\x20'+w['id']+':\x20'+w['title'];if(w['dependsOn']['length'])u+='\x20(depends:\x20'+w['dependsOn']['join'](',\x20')+')';if(w['category'])u+='\x20['+w['category']+']';u+='\x0a';}}return u+='\x0aCritical\x20Path:\x20'+t['criticalPath']['join']('\x20->\x20')+'\x0a',u+='Total\x20Waves:\x20'+t['waves']['length']+'\x0a',ok(u);}case'extract_file_references':{const x=await readFile(c['plan_path'],'utf-8'),y=extractFileReferences(x);return ok(JSON['stringify']({'count':y['length'],'references':y},null,0x2));}case'extract_task_file_references':{const z=await readFile(c['plan_path'],'utf-8'),A=extractTaskFileReferences(z,c['task_id']);return ok(JSON['stringify']({'taskId':c['task_id'],'count':A['length'],'references':A},null,0x2));}case'check_qa_completeness':{const B=await readFile(c['plan_path'],'utf-8'),C=checkQaCompleteness(B),D=C['filter'](E=>!E['hasQa']);return ok(JSON['stringify']({'total':C['length'],'with_qa':C['length']-D['length'],'missing_qa':D['length'],'details':C},null,0x2));}case'update_draft':{return await updateDraft(BASE_PATH,c['name'],c['section'],c['content']),ok('Draft\x20updated:\x20section\x20\x22'+c['section']+'\x22');}case'delete_draft':{return await deleteDraft(BASE_PATH,c['name']),ok('Draft\x20deleted:\x20'+c['name']);}case'append_to_notepad':{return await appendToNotepad(BASE_PATH,c['plan_name'],c['category'],c['content'],c?.['task_id']),ok('Appended\x20to\x20'+c['category']);}case'get_inherited_wisdom':{const E=await getInheritedWisdom(BASE_PATH,c['plan_name']);return ok(E);}case'verify_evidence':{const F=await verifyEvidence(BASE_PATH,c['plan_name'],c['task_id']);return ok(JSON['stringify'](F,null,0x2));}default:return err('Unknown\x20tool:\x20'+b);}}catch(G){return err(G instanceof Error?G['message']:String(G));}});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]\x20Plan\x20Manager\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{readFile,writeFile}from'fs/promises';import{parsePlanProgress,markTaskComplete,unmarkTaskComplete,getExecutableTasks,generateWaveStructure,extractFileReferences,extractTaskFileReferences,checkQaCompleteness}from'./plan-parser.js';import{appendTasksToPlan,updateDraft,deleteDraft,appendToNotepad,getInheritedWisdom,verifyEvidence,updateWaveState}from'./file-ops.js';const BASE_PATH=process['env']['PROJECT_PATH']||process['cwd'](),server=new Server({'name':'mcp-plan-manager','version':'1.0.0'},{'capabilities':{'tools':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>({'tools':[{'name':'append_tasks_to_plan','description':'Append\x20tasks\x20to\x20an\x20existing\x20plan\x20file\x20before\x20the\x20Final\x20Verification\x20Wave\x20section.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Absolute\x20path\x20to\x20plan\x20file'},'tasks':{'type':'array','items':{'type':'object','properties':{'id':{'type':'string'},'title':{'type':'string'},'whatToDo':{'type':'string'},'mustNot':{'type':'string'},'category':{'type':'string'},'skills':{'type':'array','items':{'type':'string'}},'dependsOn':{'type':'array','items':{'type':'string'}},'blocks':{'type':'array','items':{'type':'string'}},'references':{'type':'string'},'qaScenarios':{'type':'string'}},'required':['id','title','whatToDo']},'description':'Array\x20of\x20tasks\x20to\x20append'}},'required':['plan_path','tasks']}},{'name':'parse_plan_progress','description':'Parse\x20a\x20plan\x20file\x20and\x20return\x20progress:\x20total,\x20completed,\x20remaining\x20tasks\x20with\x20metadata.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'mark_task_complete','description':'Mark\x20a\x20task\x20as\x20completed\x20by\x20changing\x20[\x20]\x20to\x20[x]\x20in\x20the\x20plan\x20file.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20number\x20to\x20mark\x20complete'}},'required':['plan_path','task_id']}},{'name':'unmark_task_complete','description':'Revert\x20a\x20completed\x20task\x20back\x20to\x20pending\x20by\x20changing\x20[x]\x20to\x20[\x20]\x20in\x20the\x20plan\x20file.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20number\x20to\x20unmark'}},'required':['plan_path','task_id']}},{'name':'get_executable_tasks','description':'Get\x20tasks\x20whose\x20dependencies\x20are\x20all\x20satisfied\x20and\x20can\x20be\x20executed\x20now.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'generate_wave_structure','description':'Generate\x20Wave-based\x20parallel\x20execution\x20structure\x20from\x20task\x20dependencies.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'extract_file_references','description':'Extract\x20all\x20file\x20path\x20references\x20from\x20a\x20plan\x20file\x20for\x20validation.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'extract_task_file_references','description':'Extract\x20file\x20path\x20references\x20scoped\x20to\x20a\x20specific\x20task\x20section\x20only.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'},'task_id':{'type':'string','description':'Task\x20ID\x20to\x20scope\x20extraction\x20to'}},'required':['plan_path','task_id']}},{'name':'check_qa_completeness','description':'Check\x20which\x20tasks\x20have\x20QA\x20scenarios\x20defined\x20and\x20which\x20are\x20missing.','inputSchema':{'type':'object','properties':{'plan_path':{'type':'string','description':'Path\x20to\x20plan\x20file'}},'required':['plan_path']}},{'name':'update_draft','description':'Update\x20a\x20specific\x20section\x20in\x20a\x20draft\x20file.','inputSchema':{'type':'object','properties':{'name':{'type':'string','description':'Draft\x20name'},'section':{'type':'string','description':'Section\x20header\x20(e.g.\x20\x22Requirements\x20(confirmed)\x22)'},'content':{'type':'string','description':'New\x20content\x20for\x20this\x20section'}},'required':['name','section','content']}},{'name':'delete_draft','description':'Delete\x20a\x20draft\x20file\x20after\x20plan\x20generation.','inputSchema':{'type':'object','properties':{'name':{'type':'string','description':'Draft\x20name'}},'required':['name']}},{'name':'append_to_notepad','description':'Append\x20an\x20entry\x20to\x20a\x20notepad\x20category\x20file.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'},'category':{'type':'string','enum':['learnings','decisions','issues','problems'],'description':'Notepad\x20category'},'content':{'type':'string','description':'Content\x20to\x20append'},'task_id':{'type':'string','description':'Optional\x20related\x20task\x20ID'}},'required':['plan_name','category','content']}},{'name':'get_inherited_wisdom','description':'Read\x20all\x20notepad\x20files\x20and\x20return\x20accumulated\x20wisdom\x20for\x20delegation\x20prompts.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'}},'required':['plan_name']}},{'name':'verify_evidence','description':'Check\x20if\x20evidence\x20files\x20exist\x20for\x20a\x20completed\x20task.','inputSchema':{'type':'object','properties':{'plan_name':{'type':'string','description':'Plan\x20name'},'task_id':{'type':'string','description':'Task\x20ID\x20to\x20check'}},'required':['plan_name','task_id']}}]})),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];try{switch(b){case'append_tasks_to_plan':{return await appendTasksToPlan(c['plan_path'],c['tasks']),ok('Appended\x20'+c['tasks']['length']+'\x20tasks\x20to\x20plan');}case'parse_plan_progress':{const d=await readFile(c['plan_path'],'utf-8'),e=parsePlanProgress(d);return ok(JSON['stringify'](e,null,0x2));}case'mark_task_complete':{const f=c['plan_path'],g=c['task_id'],h=await readFile(f,'utf-8'),i=markTaskComplete(h,g);await writeFile(f,i,'utf-8');const j=await updateWaveState(BASE_PATH,f,g);if(j){const k=j['waveComplete']?'\x20|\x20Wave\x20'+j['currentWave']+'/'+j['totalWaves']+'\x20COMPLETE':'\x20|\x20Wave\x20'+j['currentWave']+'/'+j['totalWaves']+'\x20in\x20progress';return ok('Task\x20'+g+'\x20marked\x20complete'+k);}return ok('Task\x20'+g+'\x20marked\x20complete');}case'unmark_task_complete':{const l=await readFile(c['plan_path'],'utf-8'),m=unmarkTaskComplete(l,c['task_id']);return await writeFile(c['plan_path'],m,'utf-8'),ok('Task\x20'+c['task_id']+'\x20unmarked\x20(reverted\x20to\x20pending)');}case'get_executable_tasks':{const n=await readFile(c['plan_path'],'utf-8'),o=parsePlanProgress(n),p=o['tasks']['filter'](r=>r['status']==='completed')['map'](r=>r['id']),q=getExecutableTasks(o['tasks'],p);return ok(JSON['stringify']({'executable_count':q['length'],'tasks':q['map'](r=>({'id':r['id'],'title':r['title'],'category':r['category'],'skills':r['skills']}))},null,0x2));}case'generate_wave_structure':{const r=await readFile(c['plan_path'],'utf-8'),s=parsePlanProgress(r),t=generateWaveStructure(s['tasks']);let u='';for(const v of t['waves']){u+='\x0aWave\x20'+v['number']+'\x20('+v['tasks']['length']+'\x20tasks):\x0a';for(const w of v['tasks']){u+='\x20\x20-\x20Task\x20'+w['id']+':\x20'+w['title'];if(w['dependsOn']['length'])u+='\x20(depends:\x20'+w['dependsOn']['join'](',\x20')+')';if(w['category'])u+='\x20['+w['category']+']';u+='\x0a';}}return u+='\x0aCritical\x20Path:\x20'+t['criticalPath']['join']('\x20->\x20')+'\x0a',u+='Total\x20Waves:\x20'+t['waves']['length']+'\x0a',ok(u);}case'extract_file_references':{const x=await readFile(c['plan_path'],'utf-8'),y=extractFileReferences(x);return ok(JSON['stringify']({'count':y['length'],'references':y},null,0x2));}case'extract_task_file_references':{const z=await readFile(c['plan_path'],'utf-8'),A=extractTaskFileReferences(z,c['task_id']);return ok(JSON['stringify']({'taskId':c['task_id'],'count':A['length'],'references':A},null,0x2));}case'check_qa_completeness':{const B=await readFile(c['plan_path'],'utf-8'),C=checkQaCompleteness(B),D=C['filter'](E=>!E['hasQa']);return ok(JSON['stringify']({'total':C['length'],'with_qa':C['length']-D['length'],'missing_qa':D['length'],'details':C},null,0x2));}case'update_draft':{return await updateDraft(BASE_PATH,c['name'],c['section'],c['content']),ok('Draft\x20updated:\x20section\x20\x22'+c['section']+'\x22');}case'delete_draft':{return await deleteDraft(BASE_PATH,c['name']),ok('Draft\x20deleted:\x20'+c['name']);}case'append_to_notepad':{return await appendToNotepad(BASE_PATH,c['plan_name'],c['category'],c['content'],c?.['task_id']),ok('Appended\x20to\x20'+c['category']);}case'get_inherited_wisdom':{const E=await getInheritedWisdom(BASE_PATH,c['plan_name']);return ok(E);}case'verify_evidence':{const F=await verifyEvidence(BASE_PATH,c['plan_name'],c['task_id']);return ok(JSON['stringify'](F,null,0x2));}default:return err('Unknown\x20tool:\x20'+b);}}catch(G){return err(G instanceof Error?G['message']:String(G));}});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]\x20Plan\x20Manager\x20server\x20started');}main()['catch'](a=>{console['error']('[MCP]\x20Fatal\x20error:',a),process['exit'](0x1);});
|
|
@@ -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{gitDiffSummary,gitBlameLines,gitLogSummary}from'./git-ops.js';import{getFileStructure,verifyFileReferences,verifyLineContent,getDependencyGraph}from'./project-analysis.js';const BASE_PATH=process
|
|
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{gitDiffSummary,gitBlameLines,gitLogSummary}from'./git-ops.js';import{getFileStructure,verifyFileReferences,verifyLineContent,getDependencyGraph}from'./project-analysis.js';const BASE_PATH=process['env']['PROJECT_PATH']||process['cwd'](),server=new Server({'name':'mcp-project-context','version':'1.0.0'},{'capabilities':{'tools':{}}});server['setRequestHandler'](ListToolsRequestSchema,async()=>({'tools':[{'name':'find_files','description':'Find\x20files\x20by\x20glob\x20pattern.\x20Returns\x20matching\x20file\x20paths.','inputSchema':{'type':'object','properties':{'pattern':{'type':'string','description':'Glob\x20pattern\x20(e.g.\x20\x22**/*.ts\x22,\x20\x22src/**/*.test.ts\x22)'},'path':{'type':'string','description':'Base\x20path\x20(default:\x20project\x20root)'},'max_results':{'type':'number','description':'Max\x20results\x20(default:\x2050)'}},'required':['pattern']}},{'name':'search_code','description':'Search\x20code\x20by\x20regex\x20pattern\x20across\x20files.\x20Returns\x20matching\x20lines\x20with\x20file\x20path\x20and\x20line\x20number.','inputSchema':{'type':'object','properties':{'pattern':{'type':'string','description':'Search\x20pattern\x20(regex\x20supported)'},'file_pattern':{'type':'string','description':'File\x20glob\x20filter\x20(e.g.\x20\x22*.ts\x22)'},'max_results':{'type':'number','description':'Max\x20results\x20(default:\x2030)'}},'required':['pattern']}},{'name':'get_file_structure','description':'Get\x20directory\x20tree\x20structure\x20as\x20JSON.','inputSchema':{'type':'object','properties':{'path':{'type':'string','description':'Root\x20path\x20(default:\x20project\x20root)'},'depth':{'type':'number','description':'Max\x20depth\x20(default:\x203)'}}}},{'name':'verify_file_references','description':'Check\x20if\x20referenced\x20file\x20paths\x20exist\x20in\x20the\x20project.','inputSchema':{'type':'object','properties':{'references':{'type':'array','items':{'type':'object','properties':{'path':{'type':'string'},'line':{'type':'number'}},'required':['path']}}},'required':['references']}},{'name':'verify_line_content','description':'Verify\x20that\x20specific\x20lines\x20in\x20a\x20file\x20contain\x20expected\x20content.','inputSchema':{'type':'object','properties':{'path':{'type':'string'},'start_line':{'type':'number'},'end_line':{'type':'number'},'expected_pattern':{'type':'string','description':'Regex\x20pattern\x20to\x20match\x20against\x20line\x20content'}},'required':['path','start_line','end_line']}},{'name':'git_diff_summary','description':'Get\x20structured\x20summary\x20of\x20git\x20diff:\x20files\x20changed,\x20insertions,\x20deletions.','inputSchema':{'type':'object','properties':{'base':{'type':'string','description':'Base\x20ref\x20(default:\x20HEAD)'},'head':{'type':'string','description':'Head\x20ref\x20(optional)'}}}},{'name':'git_blame_lines','description':'Get\x20blame\x20info\x20for\x20specific\x20lines:\x20author,\x20date,\x20commit\x20SHA.','inputSchema':{'type':'object','properties':{'path':{'type':'string'},'start_line':{'type':'number'},'end_line':{'type':'number'}},'required':['path','start_line','end_line']}},{'name':'git_log_summary','description':'Get\x20recent\x20commit\x20log\x20entries.','inputSchema':{'type':'object','properties':{'path':{'type':'string','description':'Optional\x20file\x20path\x20filter'},'count':{'type':'number','description':'Number\x20of\x20entries\x20(default:\x2010)'}}}},{'name':'get_dependency_graph','description':'Build\x20import-based\x20dependency\x20graph\x20from\x20an\x20entry\x20file.','inputSchema':{'type':'object','properties':{'entry_file':{'type':'string','description':'Entry\x20file\x20path\x20(relative\x20or\x20absolute)'}},'required':['entry_file']}}]})),server['setRequestHandler'](CallToolRequestSchema,async a=>{const {name:b,arguments:c}=a['params'];try{switch(b){case'find_files':{const d=c['pattern'],e=c?.['path']||BASE_PATH,f=c?.['max_results']||0x32,g=[e,'-path','*/node_modules','-prune','-o','-path','*/.git','-prune','-o','-path','*/dist','-prune','-o','-name',d['replace'](/\*\*/g,'*'),'-print'];let h;try{const j=execFileSync('find',g,{'encoding':'utf-8','timeout':0x2710}),k=j['trim']()['split']('\x0a')['filter'](Boolean);h=k['slice'](0x0,f)['join']('\x0a');}catch{h='';}const i=h?h['split']('\x0a')['filter'](Boolean):[];return ok(JSON['stringify']({'count':i['length'],'files':i},null,0x2));}case'search_code':{const l=c['pattern'],m=c?.['file_pattern'],n=c?.['max_results']||0x1e,o=['-rn'];m?o['push']('--include='+m):o['push']('--include=*.ts','--include=*.js','--include=*.tsx','--include=*.jsx','--include=*.py');o['push'](l,BASE_PATH);let p;try{const r=execFileSync('grep',o,{'encoding':'utf-8','timeout':0x3a98}),s=r['trim']()['split']('\x0a');p=s['slice'](0x0,n)['join']('\x0a');}catch{p='';}const q=p?p['split']('\x0a')['filter'](Boolean)['map'](t=>{const [u,...v]=t['split'](':'),w=u?.['split'](':')||[];return{'file':w[0x0]||u,'line':w[0x1]||'','content':v['join'](':')['trim']()||''};}):[];return ok(JSON['stringify']({'count':q['length'],'matches':q},null,0x2));}case'get_file_structure':{const t=c?.['path']||BASE_PATH,u=c?.['depth']||0x3,v=await getFileStructure(t,u);return ok(JSON['stringify'](v,null,0x2));}case'verify_file_references':{const w=c['references'],x=await verifyFileReferences(BASE_PATH,w),y=x['filter'](z=>z['exists'])['length'];return ok(JSON['stringify']({'total':x['length'],'existing':y,'missing':x['length']-y,'details':x},null,0x2));}case'verify_line_content':{const z=await verifyLineContent(BASE_PATH,c['path'],c['start_line'],c['end_line'],c?.['expected_pattern']);return ok(JSON['stringify'](z,null,0x2));}case'git_diff_summary':{const A=gitDiffSummary(BASE_PATH,c?.['base'],c?.['head']);return ok(JSON['stringify'](A,null,0x2));}case'git_blame_lines':{const B=gitBlameLines(BASE_PATH,c['path'],c['start_line'],c['end_line']);return ok(JSON['stringify'](B,null,0x2));}case'git_log_summary':{const C=gitLogSummary(BASE_PATH,c?.['path'],c?.['count']);return ok(JSON['stringify'](C,null,0x2));}case'get_dependency_graph':{const D=await getDependencyGraph(BASE_PATH,c['entry_file']);return ok(JSON['stringify']({'nodeCount':D['nodes']['length'],'edgeCount':D['edges']['length'],'nodes':D['nodes'],'edges':D['edges']},null,0x2));}default:return err('Unknown\x20tool:\x20'+b);}}catch(E){return err(E instanceof Error?E['message']:String(E));}});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]\x20Project\x20Context\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*as a0c from'crypto';import{homedir}from'os';const PROJECT_DIR=process
|
|
1
|
+
import*as a0a from'fs';import*as a0b from'path';import*as a0c from'crypto';import{homedir}from'os';const PROJECT_DIR=process['env']['PROJECT_DIR']||process['cwd'](),PROJECT_HASH=a0c['createHash']('sha256')['update'](PROJECT_DIR)['digest']('hex')['slice'](0x0,0xc),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']||a0b['join'](homedir(),'.routinecode','knowledge'),TELEMETRY_FILE=a0b['join'](KNOWLEDGE_DIR,'agent-telemetry.jsonl'),STATE_FILE='/tmp/routinecode-agent-state-'+PROJECT_HASH+'.json',RECENT_WINDOW_MS=0xa*0x3c*0x3e8,EXPLORER_SOFT_LIMIT=0x3,EXPLORER_HARD_LIMIT=0x5,LOCK_TIMEOUT_MS=0x1f4,LOCK_STALE_MS=0x1388,LOCK_FILE=STATE_FILE+'.lock',EXPLORER_LIKE_TYPES=new Set(['explorer','Explore']);function isExplorerLike(a){return EXPLORER_LIKE_TYPES['has'](a);}function acquireLock(){const a=Date['now']()+LOCK_TIMEOUT_MS;while(Date['now']()<a){try{const b=a0a['openSync'](LOCK_FILE,'wx');return a0a['writeSync'](b,String(process['pid'])),a0a['closeSync'](b),!![];}catch(c){if(c['code']!=='EEXIST')return![];try{const f=a0a['statSync'](LOCK_FILE);if(Date['now']()-f['mtimeMs']>LOCK_STALE_MS){try{a0a['unlinkSync'](LOCK_FILE);}catch{}continue;}}catch{}const d=Date['now']()+0x8+Math['floor'](Math['random']()*0x8);while(Date['now']()<d){}}}return![];}function releaseLock(){try{a0a['unlinkSync'](LOCK_FILE);}catch{}}function withLock(a){const b=acquireLock();try{return a();}finally{if(b)releaseLock();}}function loadState(){try{if(!a0a['existsSync'](STATE_FILE))return{'projectHash':PROJECT_HASH,'spawns':[],'updatedAt':new Date()['toISOString']()};const a=a0a['readFileSync'](STATE_FILE,'utf-8'),b=JSON['parse'](a);if(b['projectHash']!==PROJECT_HASH)return{'projectHash':PROJECT_HASH,'spawns':[],'updatedAt':new Date()['toISOString']()};return b;}catch{return{'projectHash':PROJECT_HASH,'spawns':[],'updatedAt':new Date()['toISOString']()};}}function persistState(a){try{a['updatedAt']=new Date()['toISOString']();const b=STATE_FILE+'.tmp.'+process['pid'];a0a['writeFileSync'](b,JSON['stringify'](a,null,0x2)),a0a['renameSync'](b,STATE_FILE);}catch{}}function persistTelemetry(a){try{!a0a['existsSync'](KNOWLEDGE_DIR)&&a0a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});const b=JSON['stringify']({...a,'projectHash':PROJECT_HASH})+'\x0a';a0a['appendFileSync'](TELEMETRY_FILE,b);}catch{}}function pruneStale(a){const b=Date['now']()-RECENT_WINDOW_MS;return a['spawns']=a['spawns']['filter'](c=>{const d=Date['parse'](c['startedAt']);return Number['isFinite'](d)&&d>=b;}),a;}function hashPrompt(a){return a0c['createHash']('sha256')['update'](a)['digest']('hex')['slice'](0x0,0x10);}function hasStructuredJustification(a){if(!a)return![];return a['trim']()['length']>=0x32;}export function trackSpawn(a){return withLock(()=>trackSpawnInner(a));}function trackSpawnInner(a){let b=loadState();b=pruneStale(b);const c=b['spawns']['filter'](k=>isExplorerLike(k['agentType'])&&k['result']!=='blocked'),d=c['length'],e=hashPrompt(a['prompt']);let f=!![],g,h;if(isExplorerLike(a['agentType'])){const k=c['some'](l=>l['promptHash']===e);if(k)f=![],g='직전\x20explorer와\x20동일한\x20프롬프트.\x20같은\x20탐색\x20반복은\x20토큰\x20낭비이자\x20정확도\x20저하.',h='첫\x20explorer\x20결과를\x20재활용하거나,\x20SCOPE를\x20명시적으로\x20좁혀\x20다른\x20질문으로\x20재구성하세요.';else{if(d>=EXPLORER_HARD_LIMIT)f=![],g='최근\x2010분\x20내\x20explorer\x20'+d+'회\x20호출됨.\x20'+'단일\x20explorer\x20+\x20Sequential\x20가설-검증\x20사이클로\x20전환하세요.',h='정말\x20더\x20필요하면\x20mcp__routinecode__reset_agent_session\x20호출\x20후\x20재시도.\x20그러나\x20대부분\x20경우\x20기존\x20결과\x20통합으로\x20충분합니다.';else d>=EXPLORER_SOFT_LIMIT&&!hasStructuredJustification(a['justification'])&&(f=![],g=d+0x1+'번째\x20explorer\x20호출에는\x20justification이\x20필요합니다\x20(최소\x2050자).',h='prompt에\x20다음을\x20명시하세요:\x0a'+'1.\x20첫\x20explorer의\x20결과로\x20왜\x20불충분한가\x0a'+'2.\x20새\x20explorer의\x20SCOPE가\x20첫\x20scope와\x20어떻게\x20disjoint한가\x0a'+'3.\x20둘\x20사이\x20cross-feedback이\x20구조적으로\x20없는\x20이유');}}const i=a0c['randomUUID'](),j={'spawnId':i,'agentType':a['agentType'],'parentAgent':a['parentAgent'],'promptHash':e,'promptSnippet':a['prompt']['slice'](0x0,0xc8),'invocationMode':a['invocationMode'],'justification':a['justification'],'startedAt':new Date()['toISOString'](),'result':f?'pending':'blocked'};b['spawns']['push'](j),persistState(b);if(!f)persistTelemetry(j);return{'spawnId':i,'recentExplorerCount':d,'accepted':f,'reason':g,'suggestion':h};}export function completeSpawn(a){return withLock(()=>{const b=loadState(),c=b['spawns']['findIndex'](d=>d['spawnId']===a['spawnId']);if(c===-0x1)return{'updated':![]};return b['spawns'][c]={...b['spawns'][c],'completedAt':new Date()['toISOString'](),'toolCallCount':a['toolCallCount'],'tokensIn':a['tokensIn'],'tokensOut':a['tokensOut'],'filesRead':a['filesRead'],'result':a['result']},persistState(b),persistTelemetry(b['spawns'][c]),{'updated':!![]};});}export function getAgentSessionReport(){let a=loadState();a=pruneStale(a);const b=new Map();for(const g of a['spawns']){const h=b['get'](g['agentType'])??[];h['push'](g),b['set'](g['agentType'],h);}const c=Array['from'](b['entries']())['map'](([i,j])=>{const k=j['reduce']((o,p)=>o+(p['tokensIn']??0x0)+(p['tokensOut']??0x0),0x0),l=j['filter'](o=>typeof o['toolCallCount']==='number'),m=l['length']?l['reduce']((o,p)=>o+(p['toolCallCount']??0x0),0x0)/l['length']:0x0,n=j['filter'](o=>o['result']==='blocked')['length'];return{'agentType':i,'count':j['length'],'totalTokens':k,'avgToolCalls':m,'blockedCount':n};}),d=[],e=a['spawns']['filter'](i=>i['result']==='blocked')['length'];e>0x0&&d['push']('최근\x2010분\x20내\x20'+e+'개\x20spawn이\x20차단됨');const f=a['spawns']['filter'](i=>i['agentType']==='explorer'&&(i['toolCallCount']??0x63)<=0x2)['length'];return f>0x0&&d['push']('explorer\x20호출\x20'+f+'건이\x20tool\x20call\x202회\x20이하\x20—\x20Main이\x20직접\x20처리\x20가능했을\x20가능성'),{'projectHash':PROJECT_HASH,'windowMinutes':RECENT_WINDOW_MS/0xea60,'recentSpawns':a['spawns'],'breakdown':c,'warnings':d};}export function resetAgentSession(){return withLock(()=>{try{const a=a0a['existsSync'](STATE_FILE);if(a)a0a['unlinkSync'](STATE_FILE);return{'reset':!![],'hadState':a};}catch{return{'reset':![],'hadState':![]};}});}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as a1a from'fs';import*as a1b from'path';import*as a1c from'crypto';import{homedir}from'os';export function knowledgeDir(){return process
|
|
1
|
+
import*as a1a from'fs';import*as a1b from'path';import*as a1c from'crypto';import{homedir}from'os';export function knowledgeDir(){return process['env']['ROUTINECODE_KNOWLEDGE_DIR']||a1b['join'](homedir(),'.routinecode','knowledge');}export function attestDir(){return a1b['join'](knowledgeDir(),'attest');}function attestFile(){return a1b['join'](attestDir(),'attestations.jsonl');}function loadKey(){const a=a1b['join'](attestDir(),'.key');try{return a1a['readFileSync'](a);}catch{}try{a1a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),a1a['writeFileSync'](a,a1c['randomBytes'](0x20),{'flag':'wx','mode':0x180});}catch{}try{return a1a['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 a1c['createHmac']('sha256',a)['update'](canonical(b))['digest']('hex');}export function normalizeProjectDir(a){if(!a)return null;try{return a1a['realpathSync'](a);}catch{return a1b['resolve'](a);}}const ROTATE_BYTES=0x5*0x400*0x400,KEEP_MS=0x7*0x18*0x3c*0x3c*0x3e8;function rotateIfLarge(){const a=a1b['join'](attestDir(),'.rotate.lock');try{const b=attestFile();if(a1a['statSync'](b)['size']<ROTATE_BYTES)return;try{a1a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}catch{try{if(Date['now']()-a1a['statSync'](a)['mtimeMs']<0x2710)return;a1a['rmSync'](a,{'force':!![]});}catch{return;}a1a['writeFileSync'](a,String(process['pid']),{'flag':'wx'});}const c=b+'.'+process['pid']+'.rotating';a1a['renameSync'](b,c);const d=Date['now']()-KEEP_MS,e=a1a['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'])a1a['appendFileSync'](b,e['join']('\x0a')+'\x0a',{'mode':0x180});a1a['rmSync'](c,{'force':!![]});}catch{}finally{try{if(a1a['readFileSync'](a,'utf-8')===String(process['pid']))a1a['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 a1a['mkdirSync'](attestDir(),{'recursive':!![],'mode':0x1c0}),rotateIfLarge(),a1a['appendFileSync'](attestFile(),d+'\x0a',{'mode':0x180}),!![];}catch{return![];}}export function signPayload(a){const b=loadKey();return b?a1c['createHmac']('sha256',b)['update'](a)['digest']('hex'):null;}export function readAttestations(b={}){let c;try{c=a1a['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']||!a1c['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+a1b['sep'])||e['startsWith'](h['projectDir']+a1b['sep'])))continue;f['push'](h);}return f;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import a2a from'fs-extra';import*as a2b from'path';import{execFileSync}from'child_process';import{homedir}from'os';import*as a2c from'crypto';import{calculateBatchRisk,mergeCausalDupes}from'./file-risk-scorer.js';import{readDenotes,readDomainKnowledge,relatedSourceIds,domainKnowledgeSourceId,SOURCE}from'./contracts.generated.js';import{extractRoutes as a2d}from'./route-match.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR||a2b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a2b['join'](ROUTINECODE_DIR,'knowledge'),BLAST_RADIUS_DIR=a2b['join'](KNOWLEDGE_DIR,'blast-radius'),CAUSAL_LINKS_PATH=a2b['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),CONFIG_PATH=process.env.ROUTINECODE_CONFIG_PATH||a2b['join'](ROUTINECODE_DIR,'config.json');function currentTenantId(){try{const a=JSON['parse'](a2a['readFileSync'](CONFIG_PATH,'utf-8'));return a['tenantId']??null;}catch{return null;}}function isLegacyTenant(a){return a===undefined||a===null||a===0x0||a==='0'||a==='';}function tenantMatchesForSurface(a,b){if(isLegacyTenant(a))return!![];if(isLegacyTenant(b))return![];return String(a)===String(b);}function grepInProject(a,b,c='*.ts'){let d='';try{d=execFileSync('grep',['-rn','--include='+c,'-E','-e',a,'--',b],{'encoding':'utf-8','maxBuffer':0x5*0x400*0x400});}catch(f){d=(f?.['stdout']??'')['toString']();}return d['trim']()['split']('\x0a')['filter'](Boolean);}function readFileSafe(a){try{return a2a['readFileSync'](a,'utf-8');}catch{return'';}}function makeId(a,b){return a+'-'+a2c['randomBytes'](0x3)['toString']('hex')+'-'+b;}function extractExports(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e],g=f['match'](/export\s+(?:async\s+)?function\s+(\w+)/);if(g){c['push']({'name':g[0x1],'type':'function','file':a,'line':e+0x1});continue;}const h=f['match'](/export\s+const\s+(\w+)/);if(h){const j=/Router\(\)/['test'](f)||/Router\b/['test'](d[e+0x1]||'');c['push']({'name':h[0x1],'type':j?'router':'const','file':a,'line':e+0x1});}}return c;}export function extractRouteDefinitions(a,b){const c=b['split']('\x0a');return a2d(a,b)['map'](d=>{const e=c[d['line']-0x1]??'',f=d['path']&&e['includes'](d['path'])?e['indexOf'](d['path'])+d['path']['length']:0x0,g=e['slice'](f)['match'](/(\w+(?:Auth|Limit|validate\w*|tryCatch\w*))/g)??[];return{'method':d['method'],'path':d['path'],'file':a,'line':d['line'],'middlewares':g};});}function traceImportCallers(a,b){const c=[],d=a2b['basename'](a['file'],a2b['extname'](a['file']))['replace'](/\.js$/,''),e='from.*[\x27\x22].*'+d+'[\x27\x22]|require.*[\x27\x22].*'+d+'[\x27\x22]',f=grepInProject(e,b);for(const g of f){const [h]=g['split'](':');if(!h||h===a['file'])continue;const i='\x5cb'+a['name']+'\x5cb',j=grepInProject(i,a2b['dirname'](h),a2b['basename'](h));j['length']>0x0&&c['push']({'entry':a2b['basename'](h)+':'+a['name'],'hops':[a2b['basename'](a['file'])+':'+a['name']],'exitPoint':a2b['basename'](a['file'])+':'+a['line'],'type':'import'});}return c;}function traceUrlCallers(a,b){const c=[];for(const d of a){const e=d['path']['replace'](/:[^/]+/g,'[^/]+'),f='fetch.*'+e+'|axios.*'+e+'|\x5c$\x5c{.*\x5c}.*'+e,g=grepInProject(f,b);for(const h of g){const [i]=h['split'](':');if(!i||i===d['file'])continue;c['push']({'entry':a2b['basename'](i)+':fetch('+d['path']+')','hops':[d['method']+'\x20'+d['path']],'exitPoint':a2b['basename'](d['file'])+':'+d['line'],'type':'url'});}}return c;}function detectFrameworkPatterns(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e],g=f['match'](/(\w+(?:Router|router))\.use\s*\(\s*(\w*[Aa]uth\w*|\w*[Mm]iddleware\w*)/);g&&c['push']({'type':'router-level-middleware','file':a,'line':e+0x1,'detail':g[0x1]+'.use('+g[0x2]+')\x20applies\x20to\x20ALL\x20sub-routes.\x20Verify\x20each\x20route\x20intends\x20this\x20auth.\x20Routes\x20with\x20different\x20auth\x20requirements\x20will\x20be\x20blocked.'});}return c;}function detectSymmetryGaps(c,d){const e=[],f=d['split']('\x0a'),g=new Map();for(let h=0x0;h<f['length'];h++){const k=f[h],m=k['match'](/if\s*\(\s*(\w+)\s*===?\s*['"`]([^'"`]+)['"`]\s*\)/);if(!m)continue;const n=m[0x1],o=m[0x2],p=new Set();let q=0x0,r=![];for(let s=h;s<Math['min'](h+0x32,f['length']);s++){const t=f[s];q+=(t['match'](/{/g)||[])['length']-(t['match'](/}/g)||[])['length'];if(q>0x0)r=!![];const u=t['match'](/\b(\w{3,})\s*\(/g);if(u)for(const v of u){const w=v['replace'](/\s*\($/,'');!['if','for','while','switch','catch','return','const','let','var','new','typeof','await']['includes'](w)&&p['add'](w);}if(r&&q<=0x0)break;}if(p['size']>0x0){if(!g['has'](n))g['set'](n,[]);g['get'](n)['push']({'condition':o,'calls':p,'lineStart':h+0x1});}}for(const [x,y]of g){if(y['length']<0x2)continue;for(let z=0x0;z<y['length'];z++){for(let A=z+0x1;A<y['length'];A++){if(Math['abs'](y[z]['lineStart']-y[A]['lineStart'])>0x64)continue;const B=[...y[z]['calls']]['filter'](D=>!y[A]['calls']['has'](D)),C=[...y[A]['calls']]['filter'](D=>!y[z]['calls']['has'](D));B['length']>0x0&&B['length']<=0x3&&e['push']({'file':c,'variable':x,'branchA':{'condition':y[z]['condition'],'calls':[...y[z]['calls']]},'branchB':{'condition':y[A]['condition'],'calls':[...y[A]['calls']]},'missingInB':B}),C['length']>0x0&&C['length']<=0x3&&e['push']({'file':c,'variable':x,'branchA':{'condition':y[A]['condition'],'calls':[...y[A]['calls']]},'branchB':{'condition':y[z]['condition'],'calls':[...y[z]['calls']]},'missingInB':C});}}}return e;}function detectFieldConsistency(a,b){const c=[],d=new Map();for(const e of a){const f=readFileSafe(e),g=f['match'](/(\w+Id|machineId|apiKey|userId|tenantId)\s*[:=]/g);if(!g)continue;for(const h of g){const i=h['replace'](/\s*[:=]$/,'');if(!d['has'](i))d['set'](i,[]);d['get'](i)['push'](e);}}for(const [j,k]of d){if(k['length']<0x2)continue;const l=grepInProject('\x5cb'+j+'\x5cb',b),m=new Set(l['map'](n=>n['split'](':')[0x0])['filter'](Boolean));m['size']>k['length']&&c['push']({'id':makeId('field',c['length']),'category':'field-consistency','description':'Field\x20\x22'+j+'\x22\x20is\x20defined/used\x20in\x20'+m['size']+'\x20files.\x20Verify\x20consistent\x20generation/usage\x20across\x20all\x20occurrences.','targetFile':k[0x0],'autoVerifiable':![]});}return c;}function detectExternalApiFieldRefs(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e];if(!/\bfetch\s*\(|\baxios\b/['test'](f))continue;for(let g=e+0x1;g<Math['min'](e+0xa,d['length']);g++){const h=d[g]['match'](/(?:data|result|json|body|response)(?:\.\w+){1,3}/g);if(h){for(const k of h){const l=k['split']('.'),m=l['length']>0x2?l['slice'](0x1)['join']('.'):l['pop']();m&&m['length']>0x2&&c['push']({'id':makeId('api-field',c['length']),'category':'field-consistency','description':'Line\x20'+(g+0x1)+':\x20references\x20external\x20API\x20field\x20\x22'+m+'\x22.\x20Verify\x20this\x20field\x20exists\x20in\x20the\x20API\x20response\x20(test_endpoint\x20or\x20API\x20docs).','targetFile':a,'autoVerifiable':![]});}break;}}}return c;}function loadCausalLinks(a){if(!a2a['existsSync'](CAUSAL_LINKS_PATH))return[];try{const b=a2a['readFileSync'](CAUSAL_LINKS_PATH,'utf-8')['trim']();if(!b)return[];const c=b['split']('\x0a')['filter'](Boolean)['map'](i=>{try{return JSON['parse'](i);}catch{return null;}})['filter'](i=>i!==null),d=mergeCausalDupes(c),e=[],f=new Set(a['map'](i=>a2b['basename'](i))),g=0.3,h=0x2;for(const i of d['values']()){const j=i['confidence']??0.5,k=i['observedCount']??0x1;if(j<g||k<h)continue;const l=a2b['basename'](i['trigger']['file']);f['has'](l)&&e['push']({'triggerFile':i['trigger']['file'],'effectFile':i['effect']['file'],'errorSignature':i['effect']['errorSignature']??'','confidence':j,'observedCount':k});}return e['sort']((m,n)=>n['confidence']-m['confidence']);}catch{return[];}}const RULES_PATH=a2b['join'](KNOWLEDGE_DIR,'rules.jsonl');function loadVerificationRules(a){if(!a2a['existsSync'](RULES_PATH))return[];try{const b=a2a['readFileSync'](RULES_PATH,'utf-8')['trim']();if(!b)return[];const c=b['split']('\x0a')['filter'](Boolean)['map'](e=>{try{return JSON['parse'](e);}catch{return null;}})['filter'](e=>e&&e['type']==='verification'&&e['confidence']>=0.3),d=new Set(a['map'](e=>a2b['basename'](e)));return c['filter'](e=>e['condition']?.['trigger_file']&&d['has'](a2b['basename'](e['condition']['trigger_file'])))['map'](e=>({'trigger':e['condition']['trigger_file'],'verify_files':e['action']?.['verify_files']??[]}));}catch{return[];}}export function scopeMatchesFile(a,b){if(typeof a!=='string'||!a||!b)return![];if(a===b)return!![];if(b['endsWith']('/'+a))return!![];if(a['endsWith']('/'+b))return!![];return![];}function loadDomainKnowledge(a){const b=currentTenantId(),c=readDomainKnowledge()['filter'](m=>tenantMatchesForSurface(m['tenantId'],b));if(c['length']===0x0)return[];const d=[],f=new Set(),g=[];for(const m of c){let n=![];for(const o of m['scope']??[]){if(typeof o!=='string')continue;const p=a['some'](r=>scopeMatchesFile(o,r));if(!p)continue;const q=m['title']+'::'+o;if(f['has'](q))continue;f['add'](q),d['push']({'category':m['category']??'unknown','title':m['title']??'','knowledge':m['knowledge']??'','scopeFile':o,'source':m['source']??'unknown','via':'scope'}),n=!![];}if(n)g['push'](m);}if(g['length']===0x0)return d;const h=readDenotes();if(h['length']===0x0)return d;const i=r=>domainKnowledgeSourceId(r['project'],r['title']),j=new Set(g['map'](i)),k=new Set(h['filter'](r=>r['sourceId']&&j['has'](r['sourceId']))['map'](r=>r['conceptId'])),l=relatedSourceIds(h,k,SOURCE['DOMAIN_KNOWLEDGE'],j);if(l['size']===0x0)return d;for(const r of c){const t=i(r);if(!l['has'](t)||f['has']('concept::'+t))continue;f['add']('concept::'+t),d['push']({'category':r['category']??'unknown','title':r['title']??'','knowledge':r['knowledge']??'','scopeFile':(r['scope']??[])[0x0]??'','source':r['source']??'unknown','via':'concept'});}return d;}export function traceBlastRadius(a){const {taskId:b,targetFiles:c,projectDir:d}=a,e=[],f=[],h=[],i=[],j=new Set(c),k=new Set(),l=loadVerificationRules(c);for(const v of l){for(const x of v['verify_files']){k['add'](a2b['basename'](x)),j['add'](x);}i['push']({'id':makeId('rule',i['length']),'category':'import-chain','description':'[Rule]\x20'+a2b['basename'](v['trigger'])+'\x20→\x20auto-verify:\x20'+v['verify_files']['map'](y=>a2b['basename'](y))['join'](',\x20')+'.\x20Promoted\x20from\x20repeated\x20observations.','targetFile':v['verify_files'][0x0]??'','autoVerifiable':!![]});}const m=loadDomainKnowledge(c);for(const y of m){const z=y['via']==='concept'?'동일\x20개념\x20연결':a2b['basename'](y['scopeFile']);i['push']({'id':makeId('domain',i['length']),'category':'framework-semantic','description':'[도메인규칙/'+y['category']+(y['via']==='concept'?'·개념경유':'')+']\x20'+z+'\x20—\x20\x22'+y['title']+'\x22:\x20'+y['knowledge']+'\x20(출처:\x20'+y['source']+').\x20코드로\x20유도\x20불가한\x20제약이니\x20수정\x20전\x20반드시\x20확인.','targetFile':y['scopeFile'],'autoVerifiable':![]});}const n=loadCausalLinks(c);for(const A of n){if(k['has'](a2b['basename'](A['effectFile'])))continue;j['add'](A['effectFile']),i['push']({'id':makeId('causal',i['length']),'category':'import-chain','description':'[Learned]\x20Modifying\x20'+a2b['basename'](A['triggerFile'])+'\x20has\x20previously\x20caused\x20\x22'+A['errorSignature']+'\x22\x20in\x20'+a2b['basename'](A['effectFile'])+'\x20(observed\x20'+A['observedCount']+'x,\x20confidence\x20'+(A['confidence']*0x64)['toFixed'](0x0)+'%).\x20Verify\x20after\x20changes.','targetFile':A['effectFile'],'autoVerifiable':!![]});}for(const B of c){const C=readFileSafe(B);if(!C)continue;const D=extractExports(B,C),E=extractRouteDefinitions(B,C);for(const I of D){const J=traceImportCallers(I,d);e['push'](...J),J['forEach'](K=>{const L=K['entry']['split'](':')[0x0];if(L)j['add'](L);});}if(E['length']>0x0){const K=traceUrlCallers(E,d);e['push'](...K),K['forEach'](L=>{const M=L['entry']['split'](':')[0x0];if(M)j['add'](M);});for(const L of E){i['push']({'id':makeId('url',i['length']),'category':'url-caller','description':L['method']+'\x20'+L['path']+'\x20('+a2b['basename'](B)+':'+L['line']+')\x20—\x20verify\x20all\x20callers\x20send\x20correct\x20request\x20format','targetFile':B,'autoVerifiable':!![]});}}const F=detectFrameworkPatterns(B,C);f['push'](...F);for(const M of F){i['push']({'id':makeId('fw',i['length']),'category':'framework-semantic','description':M['detail'],'targetFile':M['file'],'autoVerifiable':![]});}const G=detectSymmetryGaps(B,C);h['push'](...G);for(const N of G){i['push']({'id':makeId('sym',i['length']),'category':'symmetry','description':'Branch\x20\x22'+N['branchA']['condition']+'\x22\x20has\x20['+N['missingInB']['join'](',\x20')+']\x20but\x20branch\x20\x22'+N['branchB']['condition']+'\x22\x20does\x20not.\x20Verify\x20if\x20intentional.','targetFile':N['file'],'autoVerifiable':![]});}const H=detectExternalApiFieldRefs(B,C);i['push'](...H);}const o=detectFieldConsistency(c,d);i['push'](...o);for(const O of e){O['type']==='import'&&i['push']({'id':makeId('import',i['length']),'category':'import-chain','description':O['entry']+'\x20imports\x20from\x20modified\x20file.\x20Verify\x20caller\x20still\x20works\x20after\x20changes.','targetFile':O['exitPoint']['split'](':')[0x0],'autoVerifiable':!![]});}const p=deduplicateChecklist(i),q=calculateRisk(p,f,h),r=calculateBatchRisk(c),s=r['files']['map'](P=>({'file':P['file'],'score':P['score'],'level':P['level'],'factors':P['factors']})),t=r['aggregateLevel']!=='low'?r['aggregateLevel']:q,u={'taskId':b,'chains':e,'affectedFiles':[...j],'frameworkWarnings':f,'symmetryGaps':h,'causalDependencies':n,'domainKnowledge':m,'fileRiskScores':s,'riskScore':t,'checklistItems':p,'persistedAt':new Date()['toISOString']()};return a2a['ensureDirSync'](BLAST_RADIUS_DIR),a2a['writeFileSync'](a2b['join'](BLAST_RADIUS_DIR,b+'.json'),JSON['stringify'](u,null,0x2),'utf-8'),u;}function deduplicateChecklist(a){const b=new Set();return a['filter'](c=>{const d=c['category']+':'+c['description']['slice'](0x0,0x50);if(b['has'](d))return![];return b['add'](d),!![];});}function calculateRisk(a,b,c){const d=a['length']+b['length']*0x3+c['length']*0x2;if(d>=0xa)return'high';if(d>=0x5)return'medium';return'low';}
|
|
1
|
+
import a2a from'fs-extra';import*as a2b from'path';import{execFileSync}from'child_process';import{homedir}from'os';import*as a2c from'crypto';import{calculateBatchRisk,mergeCausalDupes}from'./file-risk-scorer.js';import{readDenotes,readDomainKnowledge,relatedSourceIds,domainKnowledgeSourceId,SOURCE}from'./contracts.generated.js';import{extractRoutes as a2d}from'./route-match.js';const ROUTINECODE_DIR=process['env']['ROUTINECODE_DIR']||a2b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process['env']['ROUTINECODE_KNOWLEDGE_DIR']||a2b['join'](ROUTINECODE_DIR,'knowledge'),BLAST_RADIUS_DIR=a2b['join'](KNOWLEDGE_DIR,'blast-radius'),CAUSAL_LINKS_PATH=a2b['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),CONFIG_PATH=process['env']['ROUTINECODE_CONFIG_PATH']||a2b['join'](ROUTINECODE_DIR,'config.json');function currentTenantId(){try{const a=JSON['parse'](a2a['readFileSync'](CONFIG_PATH,'utf-8'));return a['tenantId']??null;}catch{return null;}}function isLegacyTenant(a){return a===undefined||a===null||a===0x0||a==='0'||a==='';}function tenantMatchesForSurface(a,b){if(isLegacyTenant(a))return!![];if(isLegacyTenant(b))return![];return String(a)===String(b);}function grepInProject(a,b,c='*.ts'){let d='';try{d=execFileSync('grep',['-rn','--include='+c,'-E','-e',a,'--',b],{'encoding':'utf-8','maxBuffer':0x5*0x400*0x400});}catch(f){d=(f?.['stdout']??'')['toString']();}return d['trim']()['split']('\x0a')['filter'](Boolean);}function readFileSafe(a){try{return a2a['readFileSync'](a,'utf-8');}catch{return'';}}function makeId(a,b){return a+'-'+a2c['randomBytes'](0x3)['toString']('hex')+'-'+b;}function extractExports(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e],g=f['match'](/export\s+(?:async\s+)?function\s+(\w+)/);if(g){c['push']({'name':g[0x1],'type':'function','file':a,'line':e+0x1});continue;}const h=f['match'](/export\s+const\s+(\w+)/);if(h){const j=/Router\(\)/['test'](f)||/Router\b/['test'](d[e+0x1]||'');c['push']({'name':h[0x1],'type':j?'router':'const','file':a,'line':e+0x1});}}return c;}export function extractRouteDefinitions(a,b){const c=b['split']('\x0a');return a2d(a,b)['map'](d=>{const e=c[d['line']-0x1]??'',f=d['path']&&e['includes'](d['path'])?e['indexOf'](d['path'])+d['path']['length']:0x0,g=e['slice'](f)['match'](/(\w+(?:Auth|Limit|validate\w*|tryCatch\w*))/g)??[];return{'method':d['method'],'path':d['path'],'file':a,'line':d['line'],'middlewares':g};});}function traceImportCallers(a,b){const c=[],d=a2b['basename'](a['file'],a2b['extname'](a['file']))['replace'](/\.js$/,''),e='from.*[\x27\x22].*'+d+'[\x27\x22]|require.*[\x27\x22].*'+d+'[\x27\x22]',f=grepInProject(e,b);for(const g of f){const [h]=g['split'](':');if(!h||h===a['file'])continue;const i='\x5cb'+a['name']+'\x5cb',j=grepInProject(i,a2b['dirname'](h),a2b['basename'](h));j['length']>0x0&&c['push']({'entry':a2b['basename'](h)+':'+a['name'],'hops':[a2b['basename'](a['file'])+':'+a['name']],'exitPoint':a2b['basename'](a['file'])+':'+a['line'],'type':'import'});}return c;}function traceUrlCallers(a,b){const c=[];for(const d of a){const e=d['path']['replace'](/:[^/]+/g,'[^/]+'),f='fetch.*'+e+'|axios.*'+e+'|\x5c$\x5c{.*\x5c}.*'+e,g=grepInProject(f,b);for(const h of g){const [i]=h['split'](':');if(!i||i===d['file'])continue;c['push']({'entry':a2b['basename'](i)+':fetch('+d['path']+')','hops':[d['method']+'\x20'+d['path']],'exitPoint':a2b['basename'](d['file'])+':'+d['line'],'type':'url'});}}return c;}function detectFrameworkPatterns(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e],g=f['match'](/(\w+(?:Router|router))\.use\s*\(\s*(\w*[Aa]uth\w*|\w*[Mm]iddleware\w*)/);g&&c['push']({'type':'router-level-middleware','file':a,'line':e+0x1,'detail':g[0x1]+'.use('+g[0x2]+')\x20applies\x20to\x20ALL\x20sub-routes.\x20Verify\x20each\x20route\x20intends\x20this\x20auth.\x20Routes\x20with\x20different\x20auth\x20requirements\x20will\x20be\x20blocked.'});}return c;}function detectSymmetryGaps(c,d){const e=[],f=d['split']('\x0a'),g=new Map();for(let h=0x0;h<f['length'];h++){const k=f[h],m=k['match'](/if\s*\(\s*(\w+)\s*===?\s*['"`]([^'"`]+)['"`]\s*\)/);if(!m)continue;const n=m[0x1],o=m[0x2],p=new Set();let q=0x0,r=![];for(let s=h;s<Math['min'](h+0x32,f['length']);s++){const t=f[s];q+=(t['match'](/{/g)||[])['length']-(t['match'](/}/g)||[])['length'];if(q>0x0)r=!![];const u=t['match'](/\b(\w{3,})\s*\(/g);if(u)for(const v of u){const w=v['replace'](/\s*\($/,'');!['if','for','while','switch','catch','return','const','let','var','new','typeof','await']['includes'](w)&&p['add'](w);}if(r&&q<=0x0)break;}if(p['size']>0x0){if(!g['has'](n))g['set'](n,[]);g['get'](n)['push']({'condition':o,'calls':p,'lineStart':h+0x1});}}for(const [x,y]of g){if(y['length']<0x2)continue;for(let z=0x0;z<y['length'];z++){for(let A=z+0x1;A<y['length'];A++){if(Math['abs'](y[z]['lineStart']-y[A]['lineStart'])>0x64)continue;const B=[...y[z]['calls']]['filter'](D=>!y[A]['calls']['has'](D)),C=[...y[A]['calls']]['filter'](D=>!y[z]['calls']['has'](D));B['length']>0x0&&B['length']<=0x3&&e['push']({'file':c,'variable':x,'branchA':{'condition':y[z]['condition'],'calls':[...y[z]['calls']]},'branchB':{'condition':y[A]['condition'],'calls':[...y[A]['calls']]},'missingInB':B}),C['length']>0x0&&C['length']<=0x3&&e['push']({'file':c,'variable':x,'branchA':{'condition':y[A]['condition'],'calls':[...y[A]['calls']]},'branchB':{'condition':y[z]['condition'],'calls':[...y[z]['calls']]},'missingInB':C});}}}return e;}function detectFieldConsistency(a,b){const c=[],d=new Map();for(const e of a){const f=readFileSafe(e),g=f['match'](/(\w+Id|machineId|apiKey|userId|tenantId)\s*[:=]/g);if(!g)continue;for(const h of g){const i=h['replace'](/\s*[:=]$/,'');if(!d['has'](i))d['set'](i,[]);d['get'](i)['push'](e);}}for(const [j,k]of d){if(k['length']<0x2)continue;const l=grepInProject('\x5cb'+j+'\x5cb',b),m=new Set(l['map'](n=>n['split'](':')[0x0])['filter'](Boolean));m['size']>k['length']&&c['push']({'id':makeId('field',c['length']),'category':'field-consistency','description':'Field\x20\x22'+j+'\x22\x20is\x20defined/used\x20in\x20'+m['size']+'\x20files.\x20Verify\x20consistent\x20generation/usage\x20across\x20all\x20occurrences.','targetFile':k[0x0],'autoVerifiable':![]});}return c;}function detectExternalApiFieldRefs(a,b){const c=[],d=b['split']('\x0a');for(let e=0x0;e<d['length'];e++){const f=d[e];if(!/\bfetch\s*\(|\baxios\b/['test'](f))continue;for(let g=e+0x1;g<Math['min'](e+0xa,d['length']);g++){const h=d[g]['match'](/(?:data|result|json|body|response)(?:\.\w+){1,3}/g);if(h){for(const k of h){const l=k['split']('.'),m=l['length']>0x2?l['slice'](0x1)['join']('.'):l['pop']();m&&m['length']>0x2&&c['push']({'id':makeId('api-field',c['length']),'category':'field-consistency','description':'Line\x20'+(g+0x1)+':\x20references\x20external\x20API\x20field\x20\x22'+m+'\x22.\x20Verify\x20this\x20field\x20exists\x20in\x20the\x20API\x20response\x20(test_endpoint\x20or\x20API\x20docs).','targetFile':a,'autoVerifiable':![]});}break;}}}return c;}function loadCausalLinks(a){if(!a2a['existsSync'](CAUSAL_LINKS_PATH))return[];try{const b=a2a['readFileSync'](CAUSAL_LINKS_PATH,'utf-8')['trim']();if(!b)return[];const c=b['split']('\x0a')['filter'](Boolean)['map'](i=>{try{return JSON['parse'](i);}catch{return null;}})['filter'](i=>i!==null),d=mergeCausalDupes(c),e=[],f=new Set(a['map'](i=>a2b['basename'](i))),g=0.3,h=0x2;for(const i of d['values']()){const j=i['confidence']??0.5,k=i['observedCount']??0x1;if(j<g||k<h)continue;const l=a2b['basename'](i['trigger']['file']);f['has'](l)&&e['push']({'triggerFile':i['trigger']['file'],'effectFile':i['effect']['file'],'errorSignature':i['effect']['errorSignature']??'','confidence':j,'observedCount':k});}return e['sort']((m,n)=>n['confidence']-m['confidence']);}catch{return[];}}const RULES_PATH=a2b['join'](KNOWLEDGE_DIR,'rules.jsonl');function loadVerificationRules(a){if(!a2a['existsSync'](RULES_PATH))return[];try{const b=a2a['readFileSync'](RULES_PATH,'utf-8')['trim']();if(!b)return[];const c=b['split']('\x0a')['filter'](Boolean)['map'](e=>{try{return JSON['parse'](e);}catch{return null;}})['filter'](e=>e&&e['type']==='verification'&&e['confidence']>=0.3),d=new Set(a['map'](e=>a2b['basename'](e)));return c['filter'](e=>e['condition']?.['trigger_file']&&d['has'](a2b['basename'](e['condition']['trigger_file'])))['map'](e=>({'trigger':e['condition']['trigger_file'],'verify_files':e['action']?.['verify_files']??[]}));}catch{return[];}}export function scopeMatchesFile(a,b){if(typeof a!=='string'||!a||!b)return![];if(a===b)return!![];if(b['endsWith']('/'+a))return!![];if(a['endsWith']('/'+b))return!![];return![];}function loadDomainKnowledge(a){const b=currentTenantId(),c=readDomainKnowledge()['filter'](m=>tenantMatchesForSurface(m['tenantId'],b));if(c['length']===0x0)return[];const d=[],f=new Set(),g=[];for(const m of c){let n=![];for(const o of m['scope']??[]){if(typeof o!=='string')continue;const p=a['some'](r=>scopeMatchesFile(o,r));if(!p)continue;const q=m['title']+'::'+o;if(f['has'](q))continue;f['add'](q),d['push']({'category':m['category']??'unknown','title':m['title']??'','knowledge':m['knowledge']??'','scopeFile':o,'source':m['source']??'unknown','via':'scope'}),n=!![];}if(n)g['push'](m);}if(g['length']===0x0)return d;const h=readDenotes();if(h['length']===0x0)return d;const i=r=>domainKnowledgeSourceId(r['project'],r['title']),j=new Set(g['map'](i)),k=new Set(h['filter'](r=>r['sourceId']&&j['has'](r['sourceId']))['map'](r=>r['conceptId'])),l=relatedSourceIds(h,k,SOURCE['DOMAIN_KNOWLEDGE'],j);if(l['size']===0x0)return d;for(const r of c){const t=i(r);if(!l['has'](t)||f['has']('concept::'+t))continue;f['add']('concept::'+t),d['push']({'category':r['category']??'unknown','title':r['title']??'','knowledge':r['knowledge']??'','scopeFile':(r['scope']??[])[0x0]??'','source':r['source']??'unknown','via':'concept'});}return d;}export function traceBlastRadius(a){const {taskId:b,targetFiles:c,projectDir:d}=a,e=[],f=[],h=[],i=[],j=new Set(c),k=new Set(),l=loadVerificationRules(c);for(const v of l){for(const x of v['verify_files']){k['add'](a2b['basename'](x)),j['add'](x);}i['push']({'id':makeId('rule',i['length']),'category':'import-chain','description':'[Rule]\x20'+a2b['basename'](v['trigger'])+'\x20→\x20auto-verify:\x20'+v['verify_files']['map'](y=>a2b['basename'](y))['join'](',\x20')+'.\x20Promoted\x20from\x20repeated\x20observations.','targetFile':v['verify_files'][0x0]??'','autoVerifiable':!![]});}const m=loadDomainKnowledge(c);for(const y of m){const z=y['via']==='concept'?'동일\x20개념\x20연결':a2b['basename'](y['scopeFile']);i['push']({'id':makeId('domain',i['length']),'category':'framework-semantic','description':'[도메인규칙/'+y['category']+(y['via']==='concept'?'·개념경유':'')+']\x20'+z+'\x20—\x20\x22'+y['title']+'\x22:\x20'+y['knowledge']+'\x20(출처:\x20'+y['source']+').\x20코드로\x20유도\x20불가한\x20제약이니\x20수정\x20전\x20반드시\x20확인.','targetFile':y['scopeFile'],'autoVerifiable':![]});}const n=loadCausalLinks(c);for(const A of n){if(k['has'](a2b['basename'](A['effectFile'])))continue;j['add'](A['effectFile']),i['push']({'id':makeId('causal',i['length']),'category':'import-chain','description':'[Learned]\x20Modifying\x20'+a2b['basename'](A['triggerFile'])+'\x20has\x20previously\x20caused\x20\x22'+A['errorSignature']+'\x22\x20in\x20'+a2b['basename'](A['effectFile'])+'\x20(observed\x20'+A['observedCount']+'x,\x20confidence\x20'+(A['confidence']*0x64)['toFixed'](0x0)+'%).\x20Verify\x20after\x20changes.','targetFile':A['effectFile'],'autoVerifiable':!![]});}for(const B of c){const C=readFileSafe(B);if(!C)continue;const D=extractExports(B,C),E=extractRouteDefinitions(B,C);for(const I of D){const J=traceImportCallers(I,d);e['push'](...J),J['forEach'](K=>{const L=K['entry']['split'](':')[0x0];if(L)j['add'](L);});}if(E['length']>0x0){const K=traceUrlCallers(E,d);e['push'](...K),K['forEach'](L=>{const M=L['entry']['split'](':')[0x0];if(M)j['add'](M);});for(const L of E){i['push']({'id':makeId('url',i['length']),'category':'url-caller','description':L['method']+'\x20'+L['path']+'\x20('+a2b['basename'](B)+':'+L['line']+')\x20—\x20verify\x20all\x20callers\x20send\x20correct\x20request\x20format','targetFile':B,'autoVerifiable':!![]});}}const F=detectFrameworkPatterns(B,C);f['push'](...F);for(const M of F){i['push']({'id':makeId('fw',i['length']),'category':'framework-semantic','description':M['detail'],'targetFile':M['file'],'autoVerifiable':![]});}const G=detectSymmetryGaps(B,C);h['push'](...G);for(const N of G){i['push']({'id':makeId('sym',i['length']),'category':'symmetry','description':'Branch\x20\x22'+N['branchA']['condition']+'\x22\x20has\x20['+N['missingInB']['join'](',\x20')+']\x20but\x20branch\x20\x22'+N['branchB']['condition']+'\x22\x20does\x20not.\x20Verify\x20if\x20intentional.','targetFile':N['file'],'autoVerifiable':![]});}const H=detectExternalApiFieldRefs(B,C);i['push'](...H);}const o=detectFieldConsistency(c,d);i['push'](...o);for(const O of e){O['type']==='import'&&i['push']({'id':makeId('import',i['length']),'category':'import-chain','description':O['entry']+'\x20imports\x20from\x20modified\x20file.\x20Verify\x20caller\x20still\x20works\x20after\x20changes.','targetFile':O['exitPoint']['split'](':')[0x0],'autoVerifiable':!![]});}const p=deduplicateChecklist(i),q=calculateRisk(p,f,h),r=calculateBatchRisk(c),s=r['files']['map'](P=>({'file':P['file'],'score':P['score'],'level':P['level'],'factors':P['factors']})),t=r['aggregateLevel']!=='low'?r['aggregateLevel']:q,u={'taskId':b,'chains':e,'affectedFiles':[...j],'frameworkWarnings':f,'symmetryGaps':h,'causalDependencies':n,'domainKnowledge':m,'fileRiskScores':s,'riskScore':t,'checklistItems':p,'persistedAt':new Date()['toISOString']()};return a2a['ensureDirSync'](BLAST_RADIUS_DIR),a2a['writeFileSync'](a2b['join'](BLAST_RADIUS_DIR,b+'.json'),JSON['stringify'](u,null,0x2),'utf-8'),u;}function deduplicateChecklist(a){const b=new Set();return a['filter'](c=>{const d=c['category']+':'+c['description']['slice'](0x0,0x50);if(b['has'](d))return![];return b['add'](d),!![];});}function calculateRisk(a,b,c){const d=a['length']+b['length']*0x3+c['length']*0x2;if(d>=0xa)return'high';if(d>=0x5)return'medium';return'low';}
|