@routinecrew/routinecode 2.31.88 → 2.31.90
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/setup.js +1 -1
- package/hooks/lib/agent_budget.py +2 -0
- package/hooks/lib/codemode_guard.py +30 -0
- package/hooks/lib/knowledge_items.py +94 -5
- package/hooks/lib/knowledge_stock.py +107 -3
- package/hooks/lib/known_solution.py +1 -1
- package/hooks/pre-bash-guard.sh +9 -0
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-routinecode/dist/index.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
package/bin/setup.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/* rc-min */
|
|
3
3
|
|
|
4
|
-
import{readFileSync,writeFileSync,existsSync,mkdirSync,chmodSync}from'fs';import{join,dirname}from'path';import{fileURLToPath}from'url';import{execSync}from'child_process';import{homedir}from'os';import{randomBytes}from'crypto';import{createInterface}from'readline';import{extractPrompts}from'./prompt-vault.js';const __filename=fileURLToPath(import.meta.url),__dirname=dirname(__filename),PACKAGE_ROOT=join(__dirname,'..'),CLAUDE_DIR=join(homedir(),'.claude'),SETTINGS_PATH=join(CLAUDE_DIR,'settings.json'),RC_CONFIG_DIR=join(homedir(),'.routinecode'),RC_CONFIG_PATH=join(RC_CONFIG_DIR,'config.json'),MCP_SERVERS=['mcp-routinecode','mcp-log-watcher','mcp-intelligence','mcp-project-context','mcp-plan-manager','mcp-doc-fetcher','mcp-dev-tester','mcp-db-manager','mcp-html-renderer'];function ask(a){const b=createInterface({'input':process['stdin'],'output':process['stdout']});return new Promise(c=>{b['question'](a,d=>{b['close'](),c(d['trim']());});});}function loadSettings(){if(!existsSync(SETTINGS_PATH))return{};return JSON['parse'](readFileSync(SETTINGS_PATH,'utf-8'));}function saveSettings(a){if(!existsSync(CLAUDE_DIR))mkdirSync(CLAUDE_DIR,{'recursive':!![]});writeFileSync(SETTINGS_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}const CLAUDE_JSON_PATH=join(homedir(),'.claude.json');function loadClaudeJson(){if(!existsSync(CLAUDE_JSON_PATH))return{};try{return JSON['parse'](readFileSync(CLAUDE_JSON_PATH,'utf-8'));}catch{return null;}}function saveClaudeJson(a){writeFileSync(CLAUDE_JSON_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}function loadRcConfig(){if(!existsSync(RC_CONFIG_PATH))return{'syncEnabled':![],'machineId':randomBytes(0x8)['toString']('hex')};return JSON['parse'](readFileSync(RC_CONFIG_PATH,'utf-8'));}function saveRcConfig(a){if(!existsSync(RC_CONFIG_DIR))mkdirSync(RC_CONFIG_DIR,{'recursive':!![]});writeFileSync(RC_CONFIG_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}function isClaudeCodeInstalled(){try{return execSync('claude\x20--version',{'stdio':'pipe'}),!![];}catch{return![];}}async function ensureClaudeCode(){if(isClaudeCodeInstalled())return;console['log']('\x20\x20Claude\x20Code\x20is\x20not\x20installed.'),console['log']('\x20\x20RoutineCode\x20runs\x20on\x20top\x20of\x20Claude\x20Code\x20(Anthropic\x27s\x20CLI).\x0a');const a=await ask('\x20\x20Install\x20Claude\x20Code\x20now?\x20(Y/n):\x20');a['toLowerCase']()==='n'&&(console['log']('\x0a\x20\x20To\x20install\x20manually:'),console['log']('\x20\x20\x20\x20npm\x20install\x20-g\x20@anthropic-ai/claude-code'),console['log']('\x0a\x20\x20Then\x20run\x20this\x20setup\x20again.'),process['exit'](0x0));console['log']('\x0a\x20\x20Installing\x20Claude\x20Code...\x0a');try{execSync('npm\x20install\x20-g\x20@anthropic-ai/claude-code',{'stdio':'inherit'}),console['log']('\x0a\x20\x20Claude\x20Code\x20installed.');}catch{console['log']('\x0a\x20\x20Auto-install\x20failed.\x20Install\x20manually:'),console['log']('\x20\x20\x20\x20npm\x20install\x20-g\x20@anthropic-ai/claude-code'),console['log']('\x0a\x20\x20Then\x20run\x20this\x20setup\x20again.'),process['exit'](0x1);}}async function setupMcpServers(){console['log']('\x0a[1/3]\x20Registering\x20MCP\x20servers\x20+\x20permissions...\x0a');const a=loadSettings();a['permissions']={'defaultMode':'bypassPermissions','allow':['Bash','Read','Edit','Write','Glob','Grep','Agent','WebFetch','WebSearch','mcp__routinecode__*','mcp__intelligence__*','mcp__project_context__*','mcp__plan_manager__*','mcp__doc_fetcher__*','mcp__dev_tester__*','mcp__db_manager__*','mcp__log_watcher__*','mcp__html_renderer__*','mcp__mcp-routinecode__*','mcp__mcp-intelligence__*','mcp__mcp-project-context__*','mcp__mcp-plan-manager__*','mcp__mcp-doc-fetcher__*','mcp__mcp-dev-tester__*','mcp__mcp-db-manager__*','mcp__mcp-log-watcher__*','mcp__mcp-html-renderer__*']},a['skipDangerousModePermissionPrompt']=!![],a['sandbox']={'enabled':![]};const b=loadClaudeJson();if(b===null)console['log']('\x20\x20FAIL\x20\x20~/.claude.json\x20파손\x20—\x20MCP\x20등록\x20건너뜀\x20(수동\x20복구\x20필요)');else{if(!b['mcpServers'])b['mcpServers']={};for(const c of MCP_SERVERS){const d=join(PACKAGE_ROOT,c,'dist','index.cjs'),e=join(PACKAGE_ROOT,c,'dist','index.js'),f=existsSync(d)?d:e;if(!existsSync(f)){console['log']('\x20\x20SKIP\x20\x20'+c+'\x20(not\x20built)');continue;}const g=new Set(['mcp-routinecode']);b['mcpServers'][c]={'command':'node','args':[f],...g['has'](c)?{'alwaysLoad':!![]}:{}};if(a['mcpServers']&&a['mcpServers'][c])delete a['mcpServers'][c];console['log']('\x20\x20OK\x20\x20\x20\x20'+c);}saveClaudeJson(b);}if(a['mcpServers']&&Object['keys'](a['mcpServers'])['length']===0x0)delete a['mcpServers'];saveSettings(a),console['log']('\x0a\x20\x20->\x20'+CLAUDE_JSON_PATH+'\x20(user\x20scope)'),console['log']('\x20\x20->\x20All\x20tools\x20auto-allowed\x20(no\x20permission\x20prompts)');}function setupHooks(){console['log']('\x0a[2/3]\x20Registering\x20hooks...\x0a');const a=loadSettings(),b=join(PACKAGE_ROOT,'hooks');for(const c of['session-start.sh','pre-edit-check.sh','post-build-check.sh','post-edit-track.sh','pre-edit-config-gate.sh','pre-agent-briefing.sh']){const d=join(b,c);existsSync(d)&&chmodSync(d,'755');}a['hooks']={'SessionStart':[{'matcher':'','hooks':[{'type':'command','command':join(b,'session-start.sh')}]}],'PostToolUse':[{'matcher':'mcp__(mcp-)?routinecode__build_check','hooks':[{'type':'command','command':join(b,'post-build-check.sh')}]},{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'post-edit-track.sh')}]}],'PreToolUse':[{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'pre-edit-check.sh')}]},{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'pre-edit-config-gate.sh')}]},{'matcher':'Agent','hooks':[{'type':'command','command':join(b,'pre-agent-briefing.sh')}]}]},saveSettings(a),console['log']('\x20\x20OK\x20\x20\x20\x20SessionStart\x20\x20(escalation\x20reset)'),console['log']('\x20\x20OK\x20\x20\x20\x20PostToolUse\x20\x20\x20(build\x20failure\x20->\x20knowledge\x20query)'),console['log']('\x20\x20OK\x20\x20\x20\x20PostToolUse\x20\x20\x20(edit\x20capture\x20->\x20build\x20reminder)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(3-Strike\x20edit\x20block\x20+\x20attempt\x20reminder)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(config\x20gate:\x20reuse\x20existing\x20code\x20+\x20structure\x20rules)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(subagent\x20architecture\x20briefing)');}function setupPlugin(){console['log']('\x0a[3/3]\x20Registering\x20plugin...\x0a');const a=loadSettings();if(!a['enabledPlugins'])a['enabledPlugins']={};const b=join(PACKAGE_ROOT,'plugin');try{extractPrompts();}catch(d){console['log']('\x20\x20WARN\x20\x20prompt\x20extract\x20failed:\x20'+d['message']);}const c=['routinecode-prompt.md','routinecode-prompt.md.sealed',join('agents','explorer.md')]['some'](g=>existsSync(join(b,g)));if(c){if(!a['extraKnownMarketplaces'])a['extraKnownMarketplaces']={};a['extraKnownMarketplaces']['routinecode-marketplace']={'source':{'source':'directory','path':PACKAGE_ROOT}},delete a['enabledPlugins']['routinecode@local'],a['enabledPlugins']['routinecode@routinecode-marketplace']=!![],console['log']('\x20\x20OK\x20\x20\x20\x20routinecode\x20plugin\x20(9\x20agents\x20+\x20/rc\x20command)'),console['log']('\x20\x20PATH\x20\x20'+b);}else console['log']('\x20\x20SKIP\x20\x20plugin\x20directory\x20not\x20found');saveSettings(a);}async function activateApiKey(a){console['log']('\x0a[4/4]\x20Activating\x20intelligence\x20sync...\x0a');const b=loadRcConfig();let c=a||null;if(!c&&b['tenantId']&&b['apiKey']){console['log']('\x20\x20Already\x20activated:\x20tenant='+b['tenantId']);const e=await ask('\x20\x20Re-activate\x20with\x20a\x20different\x20key?\x20(y/N):\x20');if(e['toLowerCase']()!=='y')return;}!c&&(console['log']('\x20\x20On\x20a\x20machine\x20with\x20a\x20browser,\x20just\x20run:\x20routinecode\x20login\x20(the\x20key\x20is\x20issued\x20automatically)'),console['log']('\x20\x20Server\x20/\x20CI\x20(no\x20browser):\x20issue\x20a\x20key\x20at\x20https://routinecode.routinecrew.net/dashboard#ci-keys'),console['log']('\x20\x20then\x20run:\x20routinecode\x20setup\x20--key\x20YOUR_KEY\x0a'),c=await ask('\x20\x20API\x20Key:\x20'));if(!c){console['log']('\x0a\x20\x20Skipped.\x20Run\x20`routinecode\x20setup`\x20again\x20to\x20activate\x20later.');return;}const d='https://api.routinecrew.com';console['log']('\x0a\x20\x20Validating...');try{const f=await fetch(d+'/api/v1/api-keys/verify',{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+c},'signal':AbortSignal['timeout'](0x2710)});if(f['ok']){const g=await f['json']();b['tenantId']=String(g['tenantId']),b['userId']=String(g['userId']??g['createdBy']??null),b['tenantCode']=g['tenantCode']??null,b['serverUrl']=d,b['publishingUrl']='https://publishing.routinecrew.com',b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Activated!'),console['log']('\x20\x20Tenant:\x20\x20'+(b['tenantCode']??b['tenantId'])),console['log']('\x20\x20Sync:\x20\x20\x20\x20enabled'),console['log']('\x20\x20Your\x20development\x20intelligence\x20will\x20sync\x20to\x20your\x20account.');}else f['status']===0x191?console['log']('\x0a\x20\x20Invalid\x20API\x20Key.\x20Run\x20routinecode\x20login,\x20or\x20issue\x20a\x20new\x20key\x20at\x20routinecode.routinecrew.net/dashboard#ci-keys'):(b['serverUrl']=d,b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Server\x20unavailable\x20('+f['status']+').\x20Key\x20saved.'),console['log']('\x20\x20Intelligence\x20sync\x20will\x20activate\x20automatically\x20when\x20connected.'));}catch{b['serverUrl']=d,b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Offline.\x20Key\x20saved.'),console['log']('\x20\x20Intelligence\x20sync\x20will\x20activate\x20when\x20connected.');}}function showStatus(){console['log']('\x0a===\x20RoutineCode\x20Status\x20===\x0a');const a=loadRcConfig();console['log']('Account:'),console['log']('\x20\x20tenantId:\x20\x20\x20\x20'+(a['tenantId']??'(not\x20activated)')),console['log']('\x20\x20tenantCode:\x20\x20'+(a['tenantCode']??'-')),console['log']('\x20\x20userId:\x20\x20\x20\x20\x20\x20'+(a['userId']??'-')),console['log']('\x20\x20machineId:\x20\x20\x20'+a['machineId']),console['log']('\x20\x20syncEnabled:\x20'+a['syncEnabled']),console['log']('\x20\x20serverUrl:\x20\x20\x20'+(a['serverUrl']??'(not\x20set)'));const b=join(RC_CONFIG_DIR,'knowledge');console['log']('\x0aKnowledge:');for(const h of['events.jsonl','patterns.jsonl','quirks.jsonl']){const i=join(b,h);if(existsSync(i)){const j=readFileSync(i,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['length'];console['log']('\x20\x20'+h+':\x20'+j+'\x20entries');}else console['log']('\x20\x20'+h+':\x20(empty)');}const c=loadSettings(),d=(loadClaudeJson()||{})['mcpServers']||{};console['log']('\x0aMCP\x20Servers:');for(const k of MCP_SERVERS){const l=d[k]||c['mcpServers']?.[k]?'ON':'OFF';console['log']('\x20\x20'+l+'\x20\x20'+k);}console['log']('\x0aHooks:');const e=c['hooks'];console['log']('\x20\x20SessionStart:\x20'+(e?.['SessionStart']?'ON':'OFF')),console['log']('\x20\x20PostToolUse:\x20\x20'+(e?.['PostToolUse']?'ON':'OFF')),console['log']('\x20\x20PreToolUse:\x20\x20\x20'+(e?.['PreToolUse']?'ON':'OFF')),console['log']('\x0aPermissions:');const f=c['permissions']?.['allow']??[],g=f['filter'](m=>m['startsWith']('mcp__'));console['log']('\x20\x20Auto-allowed:\x20'+g['length']+'\x20MCP\x20tool\x20patterns');}function mcpDepsHealthy(){const a=['node_modules','@modelcontextprotocol','sdk','package.json'];return existsSync(join(PACKAGE_ROOT,...a))||existsSync(join(PACKAGE_ROOT,'mcp-routinecode',...a));}async function ensureMcpDeps(){if(mcpDepsHealthy())return;console['log']('\x0a\x20\x20MCP\x20runtime\x20dependencies\x20missing\x20—\x20installing...'),await installDeps();}async function installDeps(){console['log']('\x0aInstalling\x20MCP\x20server\x20dependencies...\x0a');const a=[];for(const b of MCP_SERVERS){const c=join(PACKAGE_ROOT,b);if(!existsSync(join(c,'package.json'))){console['log']('\x20\x20SKIP\x20\x20'+b);continue;}console['log']('\x20\x20...\x20\x20\x20'+b);try{execSync('npm\x20install\x20--production\x20--silent',{'cwd':c,'stdio':'pipe'});if(!existsSync(join(c,'node_modules','@modelcontextprotocol','sdk')))throw new Error('@modelcontextprotocol/sdk\x20missing\x20after\x20install');console['log']('\x20\x20OK\x20\x20\x20\x20'+b);}catch(d){console['log']('\x20\x20FAIL\x20\x20'+b+':\x20'+d['message']),a['push'](b);}}if(a['length'])return console['log']('\x0a\x20\x20⚠\x20'+a['length']+'/'+MCP_SERVERS['length']+'\x20MCP\x20server(s)\x20FAILED\x20dependency\x20install:'),console['log']('\x20\x20\x20\x20\x20\x20'+a['join'](',\x20')),console['log']('\x20\x20이\x20서버들은\x20의존성이\x20설치될\x20때까지\x20기동되지\x20않습니다(무음\x20실패\x20방지).'),console['log']('\x20\x20네트워크/npm\x20확인\x20후\x20재실행:\x20\x20routinecode\x20install-deps'),process['exitCode']=0x1,![];return console['log']('\x0a\x20\x20All\x20'+MCP_SERVERS['length']+'\x20MCP\x20servers\x20verified\x20(deps\x20+\x20SDK\x20present).'),!![];}function getPackageVersion(){try{const a=JSON['parse'](readFileSync(join(PACKAGE_ROOT,'package.json'),'utf-8'));return a['version']??'unknown';}catch{return'unknown';}}function saveInstallInfo(){const a=loadRcConfig();a['installPath']=PACKAGE_ROOT,a['installedVersion']=getPackageVersion(),a['lastUpdated']=new Date()['toISOString'](),saveRcConfig(a);}async function runUpdate(){const a=loadRcConfig(),b=a['installedVersion']??'unknown',c=getPackageVersion();console['log']('\x20\x20Updating:\x20'+b+'\x20->\x20'+c),await ensureMcpDeps(),await setupMcpServers(),setupHooks(),setupPlugin(),saveInstallInfo(),console['log']('\x0a\x20\x20Updated\x20to\x20v'+c),console['log']('\x20\x20Run\x20`routinecode`\x20to\x20start\x20with\x20updated\x20config.\x0a');}const command=process['argv'][0x2]||'help';function parseFlag(a){const b=process['argv']['indexOf'](a);return b!==-0x1&&b+0x1<process['argv']['length']?process['argv'][b+0x1]:null;}const silent=process['argv']['includes']('--silent');!silent&&(console['log'](''),console['log']('\x20\x20RoutineCode\x20v'+getPackageVersion()),console['log']('\x20\x20Claude\x20Code\x20Superset\x20—\x2059\x20MCP\x20Tools\x20+\x20Multi-Agent\x20Orchestration'),console['log']('\x20\x20https://github.com/routinecrew/routinecode'),console['log'](''));switch(command){case'setup':{const keyArg=parseFlag('--key');await ensureClaudeCode(),await ensureMcpDeps(),await setupMcpServers(),setupHooks(),setupPlugin(),saveInstallInfo(),await activateApiKey(keyArg),console['log']('\x0a===\x20Setup\x20Complete\x20==='),console['log']('\x0aRun\x20`routinecode`\x20to\x20start.\x0a');break;}case'update':await runUpdate();break;case'status':showStatus();break;case'install-deps':await installDeps();break;case'help':default:if(command!=='help')console['log']('Unknown\x20command:\x20'+command+'\x0a');console['log']('Usage:'),console['log']('\x20\x20routinecode\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Launch\x20RoutineCode\x20(Claude\x20Code\x20superset)'),console['log']('\x20\x20routinecode\x20setup\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Full\x20setup\x20(interactive\x20API\x20key)'),console['log']('\x20\x20routinecode\x20setup\x20--key\x20<KEY>\x20\x20\x20\x20\x20\x20Full\x20setup\x20with\x20API\x20key'),console['log']('\x20\x20routinecode\x20update\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Update\x20MCP\x20servers\x20+\x20hooks\x20(non-interactive)'),console['log']('\x20\x20routinecode\x20status\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Show\x20current\x20configuration'),console['log']('\x20\x20routinecode\x20install-deps\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Install\x20MCP\x20server\x20dependencies'),process['exit'](command==='help'?0x0:0x1);}
|
|
4
|
+
import{readFileSync,writeFileSync,existsSync,mkdirSync,chmodSync}from'fs';import{join,dirname}from'path';import{fileURLToPath}from'url';import{execSync}from'child_process';import{homedir}from'os';import{randomBytes}from'crypto';import{createInterface}from'readline';import{extractPrompts}from'./prompt-vault.js';const __filename=fileURLToPath(import.meta.url),__dirname=dirname(__filename),PACKAGE_ROOT=join(__dirname,'..'),CLAUDE_DIR=join(homedir(),'.claude'),SETTINGS_PATH=join(CLAUDE_DIR,'settings.json'),RC_CONFIG_DIR=join(homedir(),'.routinecode'),RC_CONFIG_PATH=join(RC_CONFIG_DIR,'config.json'),MCP_SERVERS=['mcp-routinecode','mcp-log-watcher','mcp-intelligence','mcp-project-context','mcp-plan-manager','mcp-doc-fetcher','mcp-dev-tester','mcp-db-manager','mcp-html-renderer'];function ask(a){const b=createInterface({'input':process['stdin'],'output':process['stdout']});return new Promise(c=>{b['question'](a,d=>{b['close'](),c(d['trim']());});});}function loadSettings(){if(!existsSync(SETTINGS_PATH))return{};return JSON['parse'](readFileSync(SETTINGS_PATH,'utf-8'));}function saveSettings(a){if(!existsSync(CLAUDE_DIR))mkdirSync(CLAUDE_DIR,{'recursive':!![]});writeFileSync(SETTINGS_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}const CLAUDE_JSON_PATH=join(homedir(),'.claude.json');function loadClaudeJson(){if(!existsSync(CLAUDE_JSON_PATH))return{};try{return JSON['parse'](readFileSync(CLAUDE_JSON_PATH,'utf-8'));}catch{return null;}}function saveClaudeJson(a){writeFileSync(CLAUDE_JSON_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}function loadRcConfig(){if(!existsSync(RC_CONFIG_PATH))return{'syncEnabled':![],'machineId':randomBytes(0x8)['toString']('hex')};return JSON['parse'](readFileSync(RC_CONFIG_PATH,'utf-8'));}function saveRcConfig(a){if(!existsSync(RC_CONFIG_DIR))mkdirSync(RC_CONFIG_DIR,{'recursive':!![]});writeFileSync(RC_CONFIG_PATH,JSON['stringify'](a,null,0x2)+'\x0a','utf-8');}function isClaudeCodeInstalled(){try{return execSync('claude\x20--version',{'stdio':'pipe'}),!![];}catch{return![];}}async function ensureClaudeCode(){if(isClaudeCodeInstalled())return;console['log']('\x20\x20Claude\x20Code\x20is\x20not\x20installed.'),console['log']('\x20\x20RoutineCode\x20runs\x20on\x20top\x20of\x20Claude\x20Code\x20(Anthropic\x27s\x20CLI).\x0a');const a=await ask('\x20\x20Install\x20Claude\x20Code\x20now?\x20(Y/n):\x20');a['toLowerCase']()==='n'&&(console['log']('\x0a\x20\x20To\x20install\x20manually:'),console['log']('\x20\x20\x20\x20npm\x20install\x20-g\x20@anthropic-ai/claude-code'),console['log']('\x0a\x20\x20Then\x20run\x20this\x20setup\x20again.'),process['exit'](0x0));console['log']('\x0a\x20\x20Installing\x20Claude\x20Code...\x0a');try{execSync('npm\x20install\x20-g\x20@anthropic-ai/claude-code',{'stdio':'inherit'}),console['log']('\x0a\x20\x20Claude\x20Code\x20installed.');}catch{console['log']('\x0a\x20\x20Auto-install\x20failed.\x20Install\x20manually:'),console['log']('\x20\x20\x20\x20npm\x20install\x20-g\x20@anthropic-ai/claude-code'),console['log']('\x0a\x20\x20Then\x20run\x20this\x20setup\x20again.'),process['exit'](0x1);}}async function setupMcpServers(){console['log']('\x0a[1/3]\x20Registering\x20MCP\x20servers\x20+\x20permissions...\x0a');const a=loadSettings();a['permissions']={'defaultMode':'bypassPermissions','allow':['Bash','Read','Edit','Write','Glob','Grep','Agent','WebFetch','WebSearch','mcp__routinecode__*','mcp__intelligence__*','mcp__project_context__*','mcp__plan_manager__*','mcp__doc_fetcher__*','mcp__dev_tester__*','mcp__db_manager__*','mcp__log_watcher__*','mcp__html_renderer__*','mcp__mcp-routinecode__*','mcp__mcp-intelligence__*','mcp__mcp-project-context__*','mcp__mcp-plan-manager__*','mcp__mcp-doc-fetcher__*','mcp__mcp-dev-tester__*','mcp__mcp-db-manager__*','mcp__mcp-log-watcher__*','mcp__mcp-html-renderer__*']},a['skipDangerousModePermissionPrompt']=!![],a['sandbox']={'enabled':![]};const b=loadClaudeJson();if(b===null)console['log']('\x20\x20FAIL\x20\x20~/.claude.json\x20파손\x20—\x20MCP\x20등록\x20건너뜀\x20(수동\x20복구\x20필요)');else{if(!b['mcpServers'])b['mcpServers']={};for(const c of MCP_SERVERS){const d=join(PACKAGE_ROOT,c,'dist','index.cjs'),e=join(PACKAGE_ROOT,c,'dist','index.js'),f=existsSync(d)?d:e;if(!existsSync(f)){console['log']('\x20\x20SKIP\x20\x20'+c+'\x20(not\x20built)');continue;}b['mcpServers'][c]={'command':'node','args':[f]};if(a['mcpServers']&&a['mcpServers'][c])delete a['mcpServers'][c];console['log']('\x20\x20OK\x20\x20\x20\x20'+c);}saveClaudeJson(b);}if(a['mcpServers']&&Object['keys'](a['mcpServers'])['length']===0x0)delete a['mcpServers'];saveSettings(a),console['log']('\x0a\x20\x20->\x20'+CLAUDE_JSON_PATH+'\x20(user\x20scope)'),console['log']('\x20\x20->\x20All\x20tools\x20auto-allowed\x20(no\x20permission\x20prompts)');}function setupHooks(){console['log']('\x0a[2/3]\x20Registering\x20hooks...\x0a');const a=loadSettings(),b=join(PACKAGE_ROOT,'hooks');for(const c of['session-start.sh','pre-edit-check.sh','post-build-check.sh','post-edit-track.sh','pre-edit-config-gate.sh','pre-agent-briefing.sh']){const d=join(b,c);existsSync(d)&&chmodSync(d,'755');}a['hooks']={'SessionStart':[{'matcher':'','hooks':[{'type':'command','command':join(b,'session-start.sh')}]}],'PostToolUse':[{'matcher':'mcp__(mcp-)?routinecode__build_check','hooks':[{'type':'command','command':join(b,'post-build-check.sh')}]},{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'post-edit-track.sh')}]}],'PreToolUse':[{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'pre-edit-check.sh')}]},{'matcher':'Edit|Write|MultiEdit','hooks':[{'type':'command','command':join(b,'pre-edit-config-gate.sh')}]},{'matcher':'Agent','hooks':[{'type':'command','command':join(b,'pre-agent-briefing.sh')}]}]},saveSettings(a),console['log']('\x20\x20OK\x20\x20\x20\x20SessionStart\x20\x20(escalation\x20reset)'),console['log']('\x20\x20OK\x20\x20\x20\x20PostToolUse\x20\x20\x20(build\x20failure\x20->\x20knowledge\x20query)'),console['log']('\x20\x20OK\x20\x20\x20\x20PostToolUse\x20\x20\x20(edit\x20capture\x20->\x20build\x20reminder)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(3-Strike\x20edit\x20block\x20+\x20attempt\x20reminder)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(config\x20gate:\x20reuse\x20existing\x20code\x20+\x20structure\x20rules)'),console['log']('\x20\x20OK\x20\x20\x20\x20PreToolUse\x20\x20\x20\x20(subagent\x20architecture\x20briefing)');}function setupPlugin(){console['log']('\x0a[3/3]\x20Registering\x20plugin...\x0a');const a=loadSettings();if(!a['enabledPlugins'])a['enabledPlugins']={};const b=join(PACKAGE_ROOT,'plugin');try{extractPrompts();}catch(d){console['log']('\x20\x20WARN\x20\x20prompt\x20extract\x20failed:\x20'+d['message']);}const c=['routinecode-prompt.md','routinecode-prompt.md.sealed',join('agents','explorer.md')]['some'](g=>existsSync(join(b,g)));if(c){if(!a['extraKnownMarketplaces'])a['extraKnownMarketplaces']={};a['extraKnownMarketplaces']['routinecode-marketplace']={'source':{'source':'directory','path':PACKAGE_ROOT}},delete a['enabledPlugins']['routinecode@local'],a['enabledPlugins']['routinecode@routinecode-marketplace']=!![],console['log']('\x20\x20OK\x20\x20\x20\x20routinecode\x20plugin\x20(9\x20agents\x20+\x20/rc\x20command)'),console['log']('\x20\x20PATH\x20\x20'+b);}else console['log']('\x20\x20SKIP\x20\x20plugin\x20directory\x20not\x20found');saveSettings(a);}async function activateApiKey(a){console['log']('\x0a[4/4]\x20Activating\x20intelligence\x20sync...\x0a');const b=loadRcConfig();let c=a||null;if(!c&&b['tenantId']&&b['apiKey']){console['log']('\x20\x20Already\x20activated:\x20tenant='+b['tenantId']);const e=await ask('\x20\x20Re-activate\x20with\x20a\x20different\x20key?\x20(y/N):\x20');if(e['toLowerCase']()!=='y')return;}!c&&(console['log']('\x20\x20On\x20a\x20machine\x20with\x20a\x20browser,\x20just\x20run:\x20routinecode\x20login\x20(the\x20key\x20is\x20issued\x20automatically)'),console['log']('\x20\x20Server\x20/\x20CI\x20(no\x20browser):\x20issue\x20a\x20key\x20at\x20https://routinecode.routinecrew.net/dashboard#ci-keys'),console['log']('\x20\x20then\x20run:\x20routinecode\x20setup\x20--key\x20YOUR_KEY\x0a'),c=await ask('\x20\x20API\x20Key:\x20'));if(!c){console['log']('\x0a\x20\x20Skipped.\x20Run\x20`routinecode\x20setup`\x20again\x20to\x20activate\x20later.');return;}const d='https://api.routinecrew.com';console['log']('\x0a\x20\x20Validating...');try{const f=await fetch(d+'/api/v1/api-keys/verify',{'method':'POST','headers':{'Content-Type':'application/json','Authorization':'Bearer\x20'+c},'signal':AbortSignal['timeout'](0x2710)});if(f['ok']){const g=await f['json']();b['tenantId']=String(g['tenantId']),b['userId']=String(g['userId']??g['createdBy']??null),b['tenantCode']=g['tenantCode']??null,b['serverUrl']=d,b['publishingUrl']='https://publishing.routinecrew.com',b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Activated!'),console['log']('\x20\x20Tenant:\x20\x20'+(b['tenantCode']??b['tenantId'])),console['log']('\x20\x20Sync:\x20\x20\x20\x20enabled'),console['log']('\x20\x20Your\x20development\x20intelligence\x20will\x20sync\x20to\x20your\x20account.');}else f['status']===0x191?console['log']('\x0a\x20\x20Invalid\x20API\x20Key.\x20Run\x20routinecode\x20login,\x20or\x20issue\x20a\x20new\x20key\x20at\x20routinecode.routinecrew.net/dashboard#ci-keys'):(b['serverUrl']=d,b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Server\x20unavailable\x20('+f['status']+').\x20Key\x20saved.'),console['log']('\x20\x20Intelligence\x20sync\x20will\x20activate\x20automatically\x20when\x20connected.'));}catch{b['serverUrl']=d,b['apiKey']=c,b['syncEnabled']=!![],saveRcConfig(b),console['log']('\x0a\x20\x20Offline.\x20Key\x20saved.'),console['log']('\x20\x20Intelligence\x20sync\x20will\x20activate\x20when\x20connected.');}}function showStatus(){console['log']('\x0a===\x20RoutineCode\x20Status\x20===\x0a');const a=loadRcConfig();console['log']('Account:'),console['log']('\x20\x20tenantId:\x20\x20\x20\x20'+(a['tenantId']??'(not\x20activated)')),console['log']('\x20\x20tenantCode:\x20\x20'+(a['tenantCode']??'-')),console['log']('\x20\x20userId:\x20\x20\x20\x20\x20\x20'+(a['userId']??'-')),console['log']('\x20\x20machineId:\x20\x20\x20'+a['machineId']),console['log']('\x20\x20syncEnabled:\x20'+a['syncEnabled']),console['log']('\x20\x20serverUrl:\x20\x20\x20'+(a['serverUrl']??'(not\x20set)'));const b=join(RC_CONFIG_DIR,'knowledge');console['log']('\x0aKnowledge:');for(const h of['events.jsonl','patterns.jsonl','quirks.jsonl']){const i=join(b,h);if(existsSync(i)){const j=readFileSync(i,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['length'];console['log']('\x20\x20'+h+':\x20'+j+'\x20entries');}else console['log']('\x20\x20'+h+':\x20(empty)');}const c=loadSettings(),d=(loadClaudeJson()||{})['mcpServers']||{};console['log']('\x0aMCP\x20Servers:');for(const k of MCP_SERVERS){const l=d[k]||c['mcpServers']?.[k]?'ON':'OFF';console['log']('\x20\x20'+l+'\x20\x20'+k);}console['log']('\x0aHooks:');const e=c['hooks'];console['log']('\x20\x20SessionStart:\x20'+(e?.['SessionStart']?'ON':'OFF')),console['log']('\x20\x20PostToolUse:\x20\x20'+(e?.['PostToolUse']?'ON':'OFF')),console['log']('\x20\x20PreToolUse:\x20\x20\x20'+(e?.['PreToolUse']?'ON':'OFF')),console['log']('\x0aPermissions:');const f=c['permissions']?.['allow']??[],g=f['filter'](m=>m['startsWith']('mcp__'));console['log']('\x20\x20Auto-allowed:\x20'+g['length']+'\x20MCP\x20tool\x20patterns');}function mcpDepsHealthy(){const a=['node_modules','@modelcontextprotocol','sdk','package.json'];return existsSync(join(PACKAGE_ROOT,...a))||existsSync(join(PACKAGE_ROOT,'mcp-routinecode',...a));}async function ensureMcpDeps(){if(mcpDepsHealthy())return;console['log']('\x0a\x20\x20MCP\x20runtime\x20dependencies\x20missing\x20—\x20installing...'),await installDeps();}async function installDeps(){console['log']('\x0aInstalling\x20MCP\x20server\x20dependencies...\x0a');const a=[];for(const b of MCP_SERVERS){const c=join(PACKAGE_ROOT,b);if(!existsSync(join(c,'package.json'))){console['log']('\x20\x20SKIP\x20\x20'+b);continue;}console['log']('\x20\x20...\x20\x20\x20'+b);try{execSync('npm\x20install\x20--production\x20--silent',{'cwd':c,'stdio':'pipe'});if(!existsSync(join(c,'node_modules','@modelcontextprotocol','sdk')))throw new Error('@modelcontextprotocol/sdk\x20missing\x20after\x20install');console['log']('\x20\x20OK\x20\x20\x20\x20'+b);}catch(d){console['log']('\x20\x20FAIL\x20\x20'+b+':\x20'+d['message']),a['push'](b);}}if(a['length'])return console['log']('\x0a\x20\x20⚠\x20'+a['length']+'/'+MCP_SERVERS['length']+'\x20MCP\x20server(s)\x20FAILED\x20dependency\x20install:'),console['log']('\x20\x20\x20\x20\x20\x20'+a['join'](',\x20')),console['log']('\x20\x20이\x20서버들은\x20의존성이\x20설치될\x20때까지\x20기동되지\x20않습니다(무음\x20실패\x20방지).'),console['log']('\x20\x20네트워크/npm\x20확인\x20후\x20재실행:\x20\x20routinecode\x20install-deps'),process['exitCode']=0x1,![];return console['log']('\x0a\x20\x20All\x20'+MCP_SERVERS['length']+'\x20MCP\x20servers\x20verified\x20(deps\x20+\x20SDK\x20present).'),!![];}function getPackageVersion(){try{const a=JSON['parse'](readFileSync(join(PACKAGE_ROOT,'package.json'),'utf-8'));return a['version']??'unknown';}catch{return'unknown';}}function saveInstallInfo(){const a=loadRcConfig();a['installPath']=PACKAGE_ROOT,a['installedVersion']=getPackageVersion(),a['lastUpdated']=new Date()['toISOString'](),saveRcConfig(a);}async function runUpdate(){const a=loadRcConfig(),b=a['installedVersion']??'unknown',c=getPackageVersion();console['log']('\x20\x20Updating:\x20'+b+'\x20->\x20'+c),await ensureMcpDeps(),await setupMcpServers(),setupHooks(),setupPlugin(),saveInstallInfo(),console['log']('\x0a\x20\x20Updated\x20to\x20v'+c),console['log']('\x20\x20Run\x20`routinecode`\x20to\x20start\x20with\x20updated\x20config.\x0a');}const command=process['argv'][0x2]||'help';function parseFlag(a){const b=process['argv']['indexOf'](a);return b!==-0x1&&b+0x1<process['argv']['length']?process['argv'][b+0x1]:null;}const silent=process['argv']['includes']('--silent');!silent&&(console['log'](''),console['log']('\x20\x20RoutineCode\x20v'+getPackageVersion()),console['log']('\x20\x20Claude\x20Code\x20Superset\x20—\x2059\x20MCP\x20Tools\x20+\x20Multi-Agent\x20Orchestration'),console['log']('\x20\x20https://github.com/routinecrew/routinecode'),console['log'](''));switch(command){case'setup':{const keyArg=parseFlag('--key');await ensureClaudeCode(),await ensureMcpDeps(),await setupMcpServers(),setupHooks(),setupPlugin(),saveInstallInfo(),await activateApiKey(keyArg),console['log']('\x0a===\x20Setup\x20Complete\x20==='),console['log']('\x0aRun\x20`routinecode`\x20to\x20start.\x0a');break;}case'update':await runUpdate();break;case'status':showStatus();break;case'install-deps':await installDeps();break;case'help':default:if(command!=='help')console['log']('Unknown\x20command:\x20'+command+'\x0a');console['log']('Usage:'),console['log']('\x20\x20routinecode\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Launch\x20RoutineCode\x20(Claude\x20Code\x20superset)'),console['log']('\x20\x20routinecode\x20setup\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Full\x20setup\x20(interactive\x20API\x20key)'),console['log']('\x20\x20routinecode\x20setup\x20--key\x20<KEY>\x20\x20\x20\x20\x20\x20Full\x20setup\x20with\x20API\x20key'),console['log']('\x20\x20routinecode\x20update\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Update\x20MCP\x20servers\x20+\x20hooks\x20(non-interactive)'),console['log']('\x20\x20routinecode\x20status\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Show\x20current\x20configuration'),console['log']('\x20\x20routinecode\x20install-deps\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Install\x20MCP\x20server\x20dependencies'),process['exit'](command==='help'?0x0:0x1);}
|
|
@@ -31,6 +31,8 @@ def emit(text):
|
|
|
31
31
|
|
|
32
32
|
def worker(inp):
|
|
33
33
|
agent, kind = inp.get('agent_id'), str(inp.get('agent_type') or '')
|
|
34
|
+
if str(inp.get('tool_use_id') or '').startswith('repl_'):
|
|
35
|
+
return # 코드 모드 스크립트 안 호출은 세지 않는다(스크립트 호출 자체 toolu_ 가 1회)
|
|
34
36
|
cap = env_int('ROUTINECODE_AGENT_CALL_LIMIT', 60)
|
|
35
37
|
if not isinstance(agent, str) or not ID.fullmatch(agent) or cap <= 0:
|
|
36
38
|
return
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""코드 모드 스크립트 안 Bash 호출 가드 — 설계 37.
|
|
3
|
+
|
|
4
|
+
코드 모드에서 스크립트(REPL) 안의 호출은 tool_use_id 가 'repl_' 로 시작한다. 이런 호출에서
|
|
5
|
+
되돌리기 어려운 명령(--confirm 실행, swap 스크립트, docker 이미지·컨테이너 삭제)을 막는다.
|
|
6
|
+
toolu_ 로 시작하거나 id 가 없으면(일반 모드) 관여하지 않는다. 보수적이라 따옴표 안 문자열도 걸릴 수 있다.
|
|
7
|
+
check(inp, cmd) -> 사유 문자열 | None. 표준 라이브러리만.
|
|
8
|
+
"""
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
_PATTERNS = (
|
|
12
|
+
('--confirm', re.compile(r'(?<![\w-])--confirm(?![\w-])')),
|
|
13
|
+
('swap-svc.py', re.compile(r'\bswap-svc\.py\b')),
|
|
14
|
+
('swap-auth-env.py', re.compile(r'\bswap-auth-env\.py\b')),
|
|
15
|
+
('swap-agentic-api.sh', re.compile(r'\bswap-agentic-api\.sh\b')),
|
|
16
|
+
('docker rmi', re.compile(r'\bdocker\s+rmi\b')),
|
|
17
|
+
('docker rm', re.compile(r'\bdocker\s+rm\b')),
|
|
18
|
+
('docker image prune', re.compile(r'\bdocker\s+image\s+prune\b')),
|
|
19
|
+
('docker builder prune', re.compile(r'\bdocker\s+builder\s+prune\b')),
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
REASON = ('[RoutineCode] 코드 모드 스크립트 안에서는 되돌리기 어려운 명령(%s)을 실행하지 않습니다. '
|
|
23
|
+
'리허설 결과를 확인한 뒤 스크립트 밖 단독 Bash 호출로 실행하세요.')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def check(inp, cmd):
|
|
27
|
+
if not str((inp or {}).get('tool_use_id') or '').startswith('repl_') or not cmd:
|
|
28
|
+
return None
|
|
29
|
+
hits = [name for name, rx in _PATTERNS if rx.search(cmd)]
|
|
30
|
+
return REASON % ', '.join(hits) if hits else None
|
|
@@ -198,6 +198,19 @@ def load(acct=None):
|
|
|
198
198
|
out = [it for it in out if it.get('kid') not in retired]
|
|
199
199
|
except Exception:
|
|
200
200
|
pass
|
|
201
|
+
# 설계 36-3 R1: 계정 items.retrigger.json 의 덧붙임 트리거를 합친다(원본 불변, 파일 삭제 = 되돌림).
|
|
202
|
+
ov = retrigger_overlay(a)
|
|
203
|
+
if ov:
|
|
204
|
+
merged = []
|
|
205
|
+
for it in out:
|
|
206
|
+
e = ov.get(it.get('kid'))
|
|
207
|
+
if e and e.get('triggers'):
|
|
208
|
+
have = [json.dumps(x, sort_keys=True) for x in (it.get('triggers') or [])]
|
|
209
|
+
extra = [x for x in e['triggers'] if isinstance(x, dict) and json.dumps(x, sort_keys=True) not in have]
|
|
210
|
+
if extra:
|
|
211
|
+
it = dict(it, triggers=list(it.get('triggers') or []) + extra)
|
|
212
|
+
merged.append(it)
|
|
213
|
+
out = merged
|
|
201
214
|
return out
|
|
202
215
|
except Exception:
|
|
203
216
|
return []
|
|
@@ -306,14 +319,78 @@ _CMD_SPLIT_RE = re.compile(r'&&|\|\||[;|\n]')
|
|
|
306
319
|
_ENV_PREFIX_RE = re.compile(r'^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*')
|
|
307
320
|
|
|
308
321
|
|
|
322
|
+
# 명령 낱말 뒤 영어 낱말('python3 has', 'docker is')은 명령 호출이 아니다(설계 36-3 S1 — 실데이터 승격 1건이 'python3 has')
|
|
323
|
+
HEAD_STOPWORDS = frozenset(['has', 'have', 'had', 'is', 'are', 'was', 'were', 'be', 'been', 'not', 'and', 'or', 'the', 'a',
|
|
324
|
+
'an', 'to', 'in', 'on', 'of', 'for', 'with', 'that', 'this', 'it', 'its', 'can', 'cannot',
|
|
325
|
+
'will', 'would', 'does', 'do', 'did', 'should', 'must', 'may', 'also', 'only', 'then', 'here',
|
|
326
|
+
'there', 'itself', 'binary', 'process', 'command', 'commands', 'output', 'when', 'if', 'as',
|
|
327
|
+
'by', 'at', 'from', 'but', 'so', 'no', 'all', 'any'])
|
|
328
|
+
|
|
329
|
+
|
|
309
330
|
def command_heads(text):
|
|
310
|
-
"""문장 안 명령 호출의 머리 2낱말('git status') 집합(소문자)."""
|
|
331
|
+
"""문장 안 명령 호출의 머리 2낱말('git status') 집합(소문자). 둘째 낱말이 영어 불용어면 뺀다."""
|
|
311
332
|
try:
|
|
312
|
-
return set('%s %s' % (m.group(1), m.group(2).lower()) for m in CMD_INVOKE_RE.finditer(text or '')
|
|
333
|
+
return set('%s %s' % (m.group(1), m.group(2).lower()) for m in CMD_INVOKE_RE.finditer(text or '')
|
|
334
|
+
if m.group(2).lower() not in HEAD_STOPWORDS)
|
|
313
335
|
except Exception:
|
|
314
336
|
return set()
|
|
315
337
|
|
|
316
338
|
|
|
339
|
+
# ── 트리거 유도 (설계 36-3 R1·F2) ──────────────────────────────────────────────
|
|
340
|
+
ERR_TEXT_MIN = 8
|
|
341
|
+
_EXC_RE = re.compile(r'\b([A-Z][A-Za-z]*(?:Error|Exception|Exit)):\s*([^\n)\]]{4,100})')
|
|
342
|
+
_QUOTED_RE = re.compile(r"'([^'\n]{8,120})'|\"([^\"\n]{8,120})\"|`([^`\n]{8,120})`")
|
|
343
|
+
_ERR_MARK_RE = re.compile(r'fatal|error|Error|ERR!|not found|No such|denied|failed|cannot|refused|EACCES|ENOENT|ECONN'
|
|
344
|
+
r'|no matches|not a git|Traceback|Unauthorized|forbidden', re.I)
|
|
345
|
+
_SCRIPT_RE = re.compile(r'(?<![\w./-])([A-Za-z0-9][\w-]*\.(?:sh|py|mjs))\b')
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _norm_err(s):
|
|
349
|
+
return ' '.join(str(s or '').split()).casefold()
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def derive_triggers(statement, limit=3):
|
|
353
|
+
"""진술에서 오류 문구(problem.text)·스크립트 이름(command.regex)을 뽑는다. 결정적·토큰 0. 명령 머리(git status 등)는
|
|
354
|
+
command 분기가 진술에서 직접 맞추므로(레포 조건 포함) 여기서 트리거로 만들지 않는다."""
|
|
355
|
+
out, seen = [], set()
|
|
356
|
+
s = str(statement or '')
|
|
357
|
+
|
|
358
|
+
def add(tr):
|
|
359
|
+
k = json.dumps(tr, sort_keys=True, ensure_ascii=False)
|
|
360
|
+
if k not in seen and len(out) < limit:
|
|
361
|
+
seen.add(k)
|
|
362
|
+
out.append(tr)
|
|
363
|
+
try:
|
|
364
|
+
for m in _EXC_RE.finditer(s):
|
|
365
|
+
txt = ('%s: %s' % (m.group(1), m.group(2))).strip().rstrip('.,;:\'"` ')
|
|
366
|
+
if len(txt) >= ERR_TEXT_MIN:
|
|
367
|
+
add({'type': 'problem', 'match': {'text': txt}})
|
|
368
|
+
for m in _QUOTED_RE.finditer(s):
|
|
369
|
+
q = (m.group(1) or m.group(2) or m.group(3) or '').strip()
|
|
370
|
+
if _ERR_MARK_RE.search(q) and len(q) >= ERR_TEXT_MIN:
|
|
371
|
+
add({'type': 'problem', 'match': {'text': q.rstrip('.,;: ')}})
|
|
372
|
+
for m in _SCRIPT_RE.finditer(s):
|
|
373
|
+
add({'type': 'command', 'match': {'regex': r'(?:^|[\s/;&|])' + re.escape(m.group(1)) + r'\b'}})
|
|
374
|
+
except Exception:
|
|
375
|
+
pass
|
|
376
|
+
return out
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
RETRIGGER_FILE = 'items.retrigger.json'
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def retrigger_overlay(acct=None):
|
|
383
|
+
"""계정 items.retrigger.json {'items': {kid: {'triggers': [...], 'round': n, 'at': iso}}}. 없거나 깨졌으면 {}."""
|
|
384
|
+
try:
|
|
385
|
+
a = acct if acct is not None else _ks().account()
|
|
386
|
+
with open(account_path(a, RETRIGGER_FILE), encoding='utf-8') as f:
|
|
387
|
+
d = json.load(f)
|
|
388
|
+
items = d.get('items') if isinstance(d, dict) else None
|
|
389
|
+
return items if isinstance(items, dict) else {}
|
|
390
|
+
except Exception:
|
|
391
|
+
return {}
|
|
392
|
+
|
|
393
|
+
|
|
317
394
|
def _exec_heads(command):
|
|
318
395
|
"""실행 명령을 && ; | 로 나눈 각 조각의 머리."""
|
|
319
396
|
out = set()
|
|
@@ -365,11 +442,23 @@ def match(event, items):
|
|
|
365
442
|
c['_strength'] = st
|
|
366
443
|
out.append(c)
|
|
367
444
|
elif typ == 'problem':
|
|
368
|
-
|
|
369
|
-
if
|
|
445
|
+
et = event.get('errorText')
|
|
446
|
+
pk = event.get('problemKey') or (problem_key_of(et) if et else None)
|
|
447
|
+
hay = _norm_err(et) if et else ''
|
|
448
|
+
if not pk and not hay:
|
|
370
449
|
return []
|
|
371
450
|
for it in items:
|
|
372
|
-
|
|
451
|
+
hit = bool(pk) and it.get('problemKey') == pk
|
|
452
|
+
if not hit and hay:
|
|
453
|
+
# 설계 36-3 E1: 오류 문구 트리거 — 문제 키 해시가 달라도 같은 문구가 오류 출력에 있으면
|
|
454
|
+
for tr in it.get('triggers') or []:
|
|
455
|
+
if not (isinstance(tr, dict) and tr.get('type') == 'problem' and isinstance(tr.get('match'), dict)):
|
|
456
|
+
continue
|
|
457
|
+
txt = _norm_err(tr['match'].get('text'))
|
|
458
|
+
if len(txt) >= ERR_TEXT_MIN and txt in hay:
|
|
459
|
+
hit = True
|
|
460
|
+
break
|
|
461
|
+
if hit:
|
|
373
462
|
c = dict(it)
|
|
374
463
|
c['_strength'] = 2
|
|
375
464
|
out.append(c)
|
|
@@ -447,7 +447,8 @@ def measure(acct, root=None, now=None):
|
|
|
447
447
|
except Exception: # noqa: BLE001 — 파일 하나가 깨져도 나머지는 센다
|
|
448
448
|
continue
|
|
449
449
|
for kid, ts, hit in rows:
|
|
450
|
-
a = agg.setdefault(kid, {'files': set(), 'reflected': set(), 'first': None})
|
|
450
|
+
a = agg.setdefault(kid, {'files': set(), 'reflected': set(), 'first': None, 'events': []})
|
|
451
|
+
a['events'].append((p, ts, hit))
|
|
451
452
|
a['files'].add(p)
|
|
452
453
|
if hit:
|
|
453
454
|
a['reflected'].add(p)
|
|
@@ -456,6 +457,102 @@ def measure(acct, root=None, now=None):
|
|
|
456
457
|
return {'files': len(files), 'items': items, 'agg': agg}
|
|
457
458
|
|
|
458
459
|
|
|
460
|
+
RETRIGGER_MAX_ROUNDS = 2
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _parse_iso(s):
|
|
464
|
+
try:
|
|
465
|
+
return datetime.strptime(str(s), '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).timestamp()
|
|
466
|
+
except Exception:
|
|
467
|
+
return None
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _write_kids(acct, name, kids, source, now):
|
|
471
|
+
rp = ki.account_path(acct, name)
|
|
472
|
+
tmp = rp + '.tmp'
|
|
473
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
474
|
+
json.dump({'kids': sorted(kids), 'updatedAt': _iso(now), 'source': source}, f, ensure_ascii=False, indent=2)
|
|
475
|
+
os.replace(tmp, rp)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _retrigger_round(acct, items, agg, quiet, retired, now):
|
|
479
|
+
"""quiet 지식의 트리거 재작성 회차. items.retrigger.json 만 쓰고(원본 불변) quiet·retired 목록을 갱신한다."""
|
|
480
|
+
res = {'retriggered': 0, 'noTrigger': 0, 'graduated': [], 'retired': []}
|
|
481
|
+
by_kid = {str(it.get('kid')): it for it in items}
|
|
482
|
+
ov = dict(ki.retrigger_overlay(acct))
|
|
483
|
+
changed = False
|
|
484
|
+
for kid in sorted(quiet):
|
|
485
|
+
it = by_kid.get(kid)
|
|
486
|
+
if it is None or kid in retired:
|
|
487
|
+
continue
|
|
488
|
+
e = ov.get(kid)
|
|
489
|
+
if not e:
|
|
490
|
+
have = [json.dumps(x, sort_keys=True) for x in (it.get('triggers') or [])]
|
|
491
|
+
trig = [x for x in ki.derive_triggers(it.get('statement')) if json.dumps(x, sort_keys=True) not in have]
|
|
492
|
+
if trig:
|
|
493
|
+
ov[kid] = {'triggers': trig, 'round': 1, 'at': _iso(now)}
|
|
494
|
+
res['retriggered'] += 1
|
|
495
|
+
changed = True
|
|
496
|
+
else:
|
|
497
|
+
res['noTrigger'] += 1
|
|
498
|
+
continue
|
|
499
|
+
if e.get('ok'):
|
|
500
|
+
continue
|
|
501
|
+
since = _parse_iso(e.get('at'))
|
|
502
|
+
evs = [ev for ev in (agg.get(kid) or {}).get('events', []) if since is None or (ev[1] is not None and ev[1] > since)]
|
|
503
|
+
if any(ev[2] for ev in evs):
|
|
504
|
+
e = dict(e, ok=True)
|
|
505
|
+
res['graduated'].append(kid)
|
|
506
|
+
elif len(set(ev[0] for ev in evs)) >= AUTO_RETIRE_SESSIONS:
|
|
507
|
+
if int(e.get('round') or 1) >= RETRIGGER_MAX_ROUNDS:
|
|
508
|
+
res['retired'].append(kid)
|
|
509
|
+
else:
|
|
510
|
+
e = dict(e, round=int(e.get('round') or 1) + 1, at=_iso(now))
|
|
511
|
+
else:
|
|
512
|
+
continue
|
|
513
|
+
ov[kid] = e
|
|
514
|
+
changed = True
|
|
515
|
+
if changed:
|
|
516
|
+
rp = ki.account_path(acct, ki.RETRIGGER_FILE)
|
|
517
|
+
tmp = rp + '.tmp'
|
|
518
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
519
|
+
json.dump({'items': ov, 'updatedAt': _iso(now)}, f, ensure_ascii=False, indent=2)
|
|
520
|
+
os.replace(tmp, rp)
|
|
521
|
+
if res['graduated']:
|
|
522
|
+
_write_kids(acct, QUIET_FILE, _kids_of(acct, QUIET_FILE) - set(res['graduated']), 'auto-quiet', now)
|
|
523
|
+
if res['retired']:
|
|
524
|
+
_merge_kids(acct, RETIRED_FILE, res['retired'], 'auto-retired-after-retrigger', now)
|
|
525
|
+
return res
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _form_of(it, extra=None):
|
|
529
|
+
trs = list(it.get('triggers') or []) + list(extra or [])
|
|
530
|
+
if any(isinstance(x, dict) and x.get('type') == 'command' for x in trs):
|
|
531
|
+
return 'command'
|
|
532
|
+
if any(isinstance(x, dict) and x.get('type') == 'problem' and isinstance(x.get('match'), dict)
|
|
533
|
+
and x['match'].get('text') for x in trs):
|
|
534
|
+
return 'error'
|
|
535
|
+
if it.get('problemKey'):
|
|
536
|
+
return 'problemKey'
|
|
537
|
+
return 'touch'
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _by_form(items, agg, overlay):
|
|
541
|
+
"""F1: 트리거 형태별 [노출 항목 수, 반영 항목 수]."""
|
|
542
|
+
out = {}
|
|
543
|
+
for it in items:
|
|
544
|
+
kid = str(it.get('kid'))
|
|
545
|
+
a = agg.get(kid)
|
|
546
|
+
if not a or not a['files']:
|
|
547
|
+
continue
|
|
548
|
+
f = _form_of(it, (overlay.get(kid) or {}).get('triggers'))
|
|
549
|
+
c = out.setdefault(f, [0, 0])
|
|
550
|
+
c[0] += 1
|
|
551
|
+
if a['reflected']:
|
|
552
|
+
c[1] += 1
|
|
553
|
+
return out
|
|
554
|
+
|
|
555
|
+
|
|
459
556
|
def _command_eligible(it):
|
|
460
557
|
if any(isinstance(t, dict) and t.get('type') == 'command' for t in (it.get('triggers') or [])):
|
|
461
558
|
return True
|
|
@@ -523,6 +620,10 @@ def run_auto(acct, root=None, force=False, now=None):
|
|
|
523
620
|
_merge_kids(acct, QUIET_FILE, cands, 'auto-quiet', now)
|
|
524
621
|
retired_after = retired_prior
|
|
525
622
|
|
|
623
|
+
# R1·R2(설계 36-3): quiet 지식은 트리거를 다시 쓴다 → 재작성 뒤 반영되면 quiet 해제, 5세션 반영 0 이 2회차면 재움
|
|
624
|
+
rt = _retrigger_round(acct, items, agg, quiet_prior | set(cands), retired_prior, now)
|
|
625
|
+
retired_after = retired_prior | set(rt['retired'])
|
|
626
|
+
|
|
526
627
|
# D1: 명령 지식이 주입 뒤 같은 문제로 2개 이상 세션에서 다시 마주쳤으면 승격
|
|
527
628
|
enc = _encounters(acct)
|
|
528
629
|
promo = []
|
|
@@ -547,6 +648,8 @@ def run_auto(acct, root=None, force=False, now=None):
|
|
|
547
648
|
'reflectedItems': len(reflected),
|
|
548
649
|
'reflectRate': round(len(reflected) / float(len(exposed)), 3) if exposed else 0.0,
|
|
549
650
|
'quietAuto': len(cands), 'promoted': promoted_total,
|
|
651
|
+
'retriggered': rt['retriggered'], 'noTrigger': rt['noTrigger'], 'graduated': len(rt['graduated']),
|
|
652
|
+
'retiredAfterRetrigger': len(rt['retired']), 'byForm': _by_form(items, agg, ki.retrigger_overlay(acct)),
|
|
550
653
|
}
|
|
551
654
|
hp = ki.account_path(acct, AUTO_FILE)
|
|
552
655
|
hist = (_read_history(hp) + [entry])[-AUTO_HISTORY_KEEP:]
|
|
@@ -569,8 +672,9 @@ def _main(argv):
|
|
|
569
672
|
if 'skipped' in r:
|
|
570
673
|
print('자동 점검 건너뜀(%s).' % r['skipped'])
|
|
571
674
|
else:
|
|
572
|
-
print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 승격 누계 %d' % (
|
|
573
|
-
r['exposedItems'], r['reflectedItems'], r['quietAuto'], r
|
|
675
|
+
print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 트리거 재작성 %d · 재작성 후 반영 %d · 재작성 후 재움 %d · 승격 누계 %d' % (
|
|
676
|
+
r['exposedItems'], r['reflectedItems'], r['quietAuto'], r.get('retriggered', 0), r.get('graduated', 0),
|
|
677
|
+
r.get('retiredAfterRetrigger', 0), r['promoted']))
|
|
574
678
|
return 0
|
|
575
679
|
if '--report' in argv:
|
|
576
680
|
out = None
|
|
@@ -166,7 +166,7 @@ def consume_v31(session_id, error_text, command=None, fallback=False):
|
|
|
166
166
|
if not rec:
|
|
167
167
|
return None
|
|
168
168
|
pk = rec['problemKey']
|
|
169
|
-
sel = ki.select([{'type': 'problem', 'problemKey': pk}], session_id=session_id)
|
|
169
|
+
sel = ki.select([{'type': 'problem', 'problemKey': pk, 'errorText': error_text}], session_id=session_id) # 36-3 E1
|
|
170
170
|
if sel:
|
|
171
171
|
ki.record_exposure(sel, session_id, 'inject:bash', problem_key=pk)
|
|
172
172
|
ki.mark_problem_shown(session_id, pk)
|
package/hooks/pre-bash-guard.sh
CHANGED
|
@@ -123,6 +123,15 @@ except SystemExit:
|
|
|
123
123
|
except Exception:
|
|
124
124
|
pass
|
|
125
125
|
|
|
126
|
+
# 설계 37 — 코드 모드 스크립트 안 호출(tool_use_id repl_) 에서 되돌리기 어려운 명령 deny. 모듈 오류는 통과(fail-open).
|
|
127
|
+
try:
|
|
128
|
+
import codemode_guard as _cmg
|
|
129
|
+
_cm_reason = _cmg.check(inp, cmd)
|
|
130
|
+
except Exception:
|
|
131
|
+
_cm_reason = None
|
|
132
|
+
if _cm_reason:
|
|
133
|
+
emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': _cm_reason}})
|
|
134
|
+
|
|
126
135
|
# rm/rmdir — Claude Code 하네스의 '위험 삭제' 확인창(bypass 에서도 안 꺼짐, 훅 allow 로 승인 불가)을
|
|
127
136
|
# 사용자에게 노출하지 않는다. 실측 규칙·처리는 lib/rm_guard.py 헤더 참조.
|
|
128
137
|
# block = 진짜 위험(시스템/홈루트/민감 경로)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as a13a from'crypto';import*as a13b from'fs';import*as a13c from'path';import{SANITIZE_RULES}from'./sanitize.generated.js';export const KNOWLEDGE_KINDS=['structure','convention','rule','decision','procedure','resolution','pitfall','fact'];export const TRIGGER_TYPES=['problem','touch','event','command','schedule','question'];export const EVIDENCE_LEVELS=['verified','stated','inferred'];const EVIDENCE_KEYS=['sessionId','commit','logRef','source'],RE_PATH=/(?:[A-Za-z]:)?(?:[\\/][^\s\\/"':,;)\]}]+){2,}[\\/]?/g,RE_ISO=/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g,RE_EPOCH=/\b\d{10,}\b/g,RE_IPV4=/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?::\d+)?\b/g,RE_LINECOL=/(?<=[A-Za-z0-9_])\.[A-Za-z0-9]{1,6}(:\d+(?::\d+)?)\b/g,RE_UUID=/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,RE_MEMADDR=/\b0x[0-9a-fA-F]+\b/g,RE_HEX=/\b[0-9a-fA-F]{8,}\b/g,RE_SEMVER=/\b(\d+)\.\d+\.\d+(?:[-+][0-9A-Za-z.\-]+)?\b/g;function basenameOf(a){const b=a['replace'](/[\\/]+$/,'')['split'](/[\\/]/);return b[b['length']-0x1]||a;}export function normalizeSigText(a){if(!a)return'';let b=String(a);return b=b['replace'](RE_PATH,c=>basenameOf(c)),b=b['replace'](RE_ISO,'*'),b=b['replace'](RE_EPOCH,'*'),b=b['replace'](RE_IPV4,'*'),b=b['replace'](RE_LINECOL,c=>{const d=c['slice'](c['indexOf'](':'));return c['slice'](0x0,c['indexOf'](':'))+':'+d['slice'](0x1)['split'](':')['map'](()=>'N')['join'](':');}),b=b['replace'](RE_UUID,'*'),b=b['replace'](RE_MEMADDR,'0x*'),b=b['replace'](RE_HEX,'*'),b=b['replace'](RE_SEMVER,(c,d)=>d),b=b['replace'](/\s+/g,'\x20')['trim'](),b['length']>0x200?b['slice'](0x0,0x200):b;}const PROBLEM_KEY_RE=/^[0-9a-f]{12}$/;export function problemKeyOf(a){const b=String(a??'')['trim']();if(PROBLEM_KEY_RE['test'](b))return b;return a13a['createHash']('sha1')['update'](normalizeSigText(b))['digest']('hex')['slice'](0x0,0xc);}export function normalizeStatement(a){return String(a??'')['toLowerCase']()['replace'](/\s+/g,'\x20')['trim']()['replace'](/[.。!?\s]+$/u,'');}export function accountDirName(a){if(!a['tenantId'])return null;return(a['kind']==='team'?'t':'p')+'-'+a['tenantId'];}export function knowledgeLocalId(a,b){const c=a+'|'+b['kind']+'|'+(b['problemKey']??'')+'|'+normalizeStatement(b['statement']);return'k_'+a13a['createHash']('sha1')['update'](c)['digest']('hex')['slice'](0x0,0x10);}const SECRET_DETECTORS=[...SANITIZE_RULES['filter'](a=>a['kind']==='secret'&&a['id']!=='key_value_secret')['map'](a=>({'id':a['id'],'re':new RegExp(a['re']['source'],a['re']['flags']['replace']('g',''))})),{'id':'key_value_secret','re':/(?:api[-_]?key|token|secret|password|passwd|credential)s?\s*[=:]\s*["']?(?=[A-Za-z0-9_\-/+]*\d|[A-Za-z0-9_\-/+]{20,})[A-Za-z0-9_\-/+]{8,}/i}];export function detectSecret(a){for(const b of SECRET_DETECTORS)if(b['re']['test'](a))return b['id'];return null;}function collectStrings(a,b,c){if(typeof a==='string')c['push']({'at':b,'text':a});else{if(Array['isArray'](a))a['forEach']((d,e)=>collectStrings(d,b+'['+e+']',c));else{if(a&&typeof a==='object'){for(const [d,e]of Object['entries'](a))collectStrings(e,b+'.'+d,c);}}}}const PLACEHOLDER_TOKEN_RE=/^(foo|bar|baz|qux|quux|lorem|ipsum|dolor|sit|amet|dummy|placeholder|sample|test\d*|example\.(com|org|net)|asdf+|qwerty|xxx+|todo|tbd|hello|world)$/,FILLER_TOKEN_RE=/^(a|an|the|is|are|and|or|of|to|in|on|for|with|this|that|it)$/,FAKE_PATH_RE=/(^|\/)(tmp|fixtures)\//,TIME_MARKER_RE=/\b20\d\d-\d\d-\d\d\b|\b\d{1,2}\/\d{1,2}\b|관찰\(|실측|오늘|현재|배포한|:[a-z][\w-]*-\d{6}\b/,AUTO_EXPIRY_MS=0x1e*0x18*0x3c*0x3c*0x3e8;export function hasTimeMarker(a){return TIME_MARKER_RE['test'](String(a??''));}export function isPlaceholderText(a){const b=String(a??'')['toLowerCase']()['split'](/[^a-z0-9.@_-]+/)['map'](d=>d['replace'](/^[.\-_]+|[.\-_]+$/g,''))['filter'](Boolean),c=b['filter'](d=>!FILLER_TOKEN_RE['test'](d));return c['length']>0x0&&c['every'](d=>PLACEHOLDER_TOKEN_RE['test'](d));}function isTestAnchorLocal(a){return FAKE_PATH_RE['test'](a);}function isTestSession(a){return!!a&&/^(integration-|test-)/i['test'](a);}export const STATEMENT_MAX=0xc8;const STATEMENT_HEAD_MIN=0x1e,BOUNDARY_RE=/\.\s|。|\s\|\s|\n/g;export function splitStatement(a){const b=String(a??'')['trim']();if(b['length']<=STATEMENT_MAX)return{'statement':b,'detail':null};BOUNDARY_RE['lastIndex']=0x0;for(let c=BOUNDARY_RE['exec'](b);c;c=BOUNDARY_RE['exec'](b)){const d=c[0x0]['startsWith']('.')||c[0x0]==='。'?0x1:0x0,e=b['slice'](0x0,c['index']+d)['trim']();if(e['length']>STATEMENT_MAX)break;if(e['length']>=STATEMENT_HEAD_MIN)return{'statement':e,'detail':b};}return{'statement':b['slice'](0x0,STATEMENT_MAX-0x1)['trimEnd']()+'…','detail':b};}const ANCHOR_RE=/^(code|onto|tech):([^:]+):(.+)$/,MIN_STATEMENT=0xa,MAX_STATEMENT=0x7d0,MAX_ANCHORS=0x14,MAX_TRIGGERS=0xa,MAX_PROBLEM_KEY=0xc8;function isPlainObject(a){return!!a&&typeof a==='object'&&!Array['isArray'](a);}function parseTime(a){if(typeof a!=='string'||!a['trim']())return null;const b=Date['parse'](a);return Number['isFinite'](b)?b:null;}export function validateKnowledge(b,c,d=new Date()){const e=[];if(!isPlainObject(b))return{'ok':![],'reasons':['input:\x20object\x20required']};const f=b;if(!c['tenantId'])e['push']('owner:\x20no\x20account\x20space\x20(login\x20or\x20`routinecode\x20team\x20switch`\x20required)');(typeof f['kind']!=='string'||!KNOWLEDGE_KINDS['includes'](f['kind']))&&e['push']('kind:\x20must\x20be\x20one\x20of\x20'+KNOWLEDGE_KINDS['join']('|'));const g=typeof f['statement']==='string'?f['statement']['trim']():'';if(!g)e['push']('statement:\x20required');else{if(g['length']<MIN_STATEMENT)e['push']('test-data:\x20statement\x20shorter\x20than\x20'+MIN_STATEMENT+'\x20chars');else{if(g['length']>MAX_STATEMENT)e['push']('statement:\x20longer\x20than\x20'+MAX_STATEMENT+'\x20chars');else{if(isPlaceholderText(g))e['push']('test-data:\x20statement\x20is\x20placeholder-only\x20text');}}}let h;if(f['problemKey']!==undefined&&f['problemKey']!==null&&f['problemKey']!==''){if(typeof f['problemKey']!=='string')e['push']('problemKey:\x20string\x20required');else{if(f['problemKey']['length']>MAX_PROBLEM_KEY*0xa)e['push']('problemKey:\x20too\x20long');else h=problemKeyOf(f['problemKey']);}}(f['kind']==='resolution'||f['kind']==='pitfall')&&!h&&e['push']('problemKey:\x20required\x20for\x20kind\x20'+f['kind']+'\x20(R-M4)');const i=[];if(!Array['isArray'](f['anchors'])||f['anchors']['length']===0x0)e['push']('anchors:\x20at\x20least\x20one\x20anchor\x20required\x20(R-T3)');else{if(f['anchors']['length']>MAX_ANCHORS)e['push']('anchors:\x20at\x20most\x20'+MAX_ANCHORS);else for(const w of f['anchors']){const x=typeof w==='string'?ANCHOR_RE['exec'](w['trim']()):null;if(!x){e['push']('anchors:\x20malformed\x20\x27'+String(w)['slice'](0x0,0x50)+'\x27\x20(want\x20<code|onto|tech>:<tenant|_>:<local>)');continue;}const [,y,z,A]=x;if(y==='code'){if(c['tenantId']&&z!==c['tenantId'])e['push']('anchors:\x20code\x20anchor\x20tenant\x20\x27'+z+'\x27\x20is\x20not\x20this\x20account');(/^(?:\/|[A-Za-z]:[\\/])/['test'](A)||A['split'](/[\\/]/)['includes']('..'))&&e['push']('anchors:\x20code\x20anchor\x20must\x20be\x20repo-relative\x20(\x27'+A['slice'](0x0,0x50)+'\x27)');}if(y==='tech'&&z!=='_')e['push']('anchors:\x20tech\x20anchor\x20tenant\x20must\x20be\x20\x27_\x27\x20(\x27'+z+'\x27)');if(isTestAnchorLocal(A))e['push']('test-data:\x20anchor\x20under\x20tmp/\x20or\x20fixtures/\x20(\x27'+A['slice'](0x0,0x50)+'\x27)');if(i['includes'](w['trim']()))e['push']('anchors:\x20duplicate\x20\x27'+w['trim']()['slice'](0x0,0x50)+'\x27');else i['push'](w['trim']());}}const j=[];if(!Array['isArray'](f['triggers'])||f['triggers']['length']===0x0)e['push']('triggers:\x20at\x20least\x20one\x20trigger\x20required');else{if(f['triggers']['length']>MAX_TRIGGERS)e['push']('triggers:\x20at\x20most\x20'+MAX_TRIGGERS);else for(const B of f['triggers']){if(!isPlainObject(B)||typeof B['type']!=='string'||!TRIGGER_TYPES['includes'](B['type'])){e['push']('triggers:\x20type\x20must\x20be\x20one\x20of\x20'+TRIGGER_TYPES['join']('|'));continue;}if(!isPlainObject(B['match'])||Object['keys'](B['match'])['length']===0x0){e['push']('triggers:\x20\x27'+B['type']+'\x27\x20needs\x20a\x20non-empty\x20match\x20object');continue;}j['push']({'type':B['type'],'match':B['match']});}}const l={};if(!isPlainObject(f['evidence']))e['push']('evidence:\x20object\x20with\x20one\x20of\x20sessionId|commit|logRef|source\x20required\x20(R-T1)');else{for(const C of EVIDENCE_KEYS){const D=f['evidence'][C];if(typeof D==='string'&&D['trim']())l[C]=D['trim']();}if(Object['keys'](l)['length']===0x0)e['push']('evidence:\x20one\x20of\x20sessionId|commit|logRef|source\x20required\x20(R-T1)');if(isTestSession(l['sessionId']))e['push']('test-data:\x20evidence\x20from\x20a\x20test\x20session');}let n='inferred';if(f['evidenceLevel']!==undefined&&f['evidenceLevel']!==null){if(!EVIDENCE_LEVELS['includes'](f['evidenceLevel']))e['push']('evidenceLevel:\x20must\x20be\x20one\x20of\x20'+EVIDENCE_LEVELS['join']('|'));else n=f['evidenceLevel'];}n==='verified'&&!l['commit']&&!l['logRef']&&e['push']('evidenceLevel:\x20verified\x20needs\x20evidence.commit\x20or\x20evidence.logRef\x20(R-M7)');let o=d['toISOString']();if(f['observedAt']!==undefined&&f['observedAt']!==null&&f['observedAt']!==''){const E=parseTime(f['observedAt']);if(E===null)e['push']('observedAt:\x20ISO\x20date\x20required');else o=new Date(E)['toISOString']();}let p;if(f['expiresAt']!==undefined&&f['expiresAt']!==null&&f['expiresAt']!==''){const F=parseTime(f['expiresAt']);if(F===null)e['push']('expiresAt:\x20ISO\x20date\x20required');else{if(F<=Date['parse'](o))e['push']('expiresAt:\x20must\x20be\x20after\x20observedAt');else p=new Date(F)['toISOString']();}}!p&&f['kind']!=='fact'&&f['kind']!=='rule'&&f['kind']!=='convention'&&f['kind']!=='decision'&&!e['some'](G=>G['startsWith']('observedAt'))&&typeof f['statement']==='string'&&hasTimeMarker(f['statement'])&&(p=new Date(Date['parse'](o)+AUTO_EXPIRY_MS)['toISOString']());f['kind']==='fact'&&!p&&!e['some'](G=>G['startsWith']('expiresAt'))&&e['push']('expiresAt:\x20required\x20for\x20kind\x20fact\x20(R-T5)');const q=[];collectStrings({'statement':f['statement'],'detail':f['detail'],'problemKey':f['problemKey'],'anchors':f['anchors'],'triggers':f['triggers'],'evidence':f['evidence']},'input',q);for(const G of q){const H=detectSecret(G['text']);if(H)e['push']('secret:\x20'+H+'\x20detected\x20in\x20'+G['at']['replace'](/^input\./,'')+'\x20(R-T6)');}if(f['detail']!==undefined&&f['detail']!==null&&typeof f['detail']!=='string')e['push']('detail:\x20string\x20required');else{if(typeof f['detail']==='string'&&f['detail']['length']>0xfa0)e['push']('detail:\x20longer\x20than\x204000\x20chars');}if(e['length']>0x0)return{'ok':![],'reasons':e};const r=splitStatement(g),u=typeof f['detail']==='string'&&f['detail']['trim']()?f['detail']['trim']():r['detail'];return{'ok':!![],'item':{'kind':f['kind'],'statement':r['statement'],...u?{'detail':u}:{},...h?{'problemKey':h}:{},'anchors':i,'triggers':j,'evidence':l,'evidenceLevel':n,'observedAt':o,...p?{'expiresAt':p}:{}}};}function findRepoRoot(a){let b=a13c['dirname'](a);for(let c=0x0;c<0x28;c++){if(a13b['existsSync'](a13c['join'](b,'.git')))return b;const d=a13c['dirname'](b);if(d===b)return null;b=d;}return null;}export function codeAnchorsFromFiles(a,b){if(!b||!Array['isArray'](a))return[];const c=new Set();for(const d of a){if(typeof d!=='string'||!d['trim']())continue;const e=d['trim']()['replace'](/:\d+(?::\d+)?$/,'');let g;if(a13c['isAbsolute'](e)){const h=findRepoRoot(e);g=h?a13c['join'](a13c['basename'](h),a13c['relative'](h,e))['split'](a13c['sep'])['join']('/'):null;}else g=e['replace'](/^\.\//,'');if(g&&!/\s/['test'](g))c['add']('code:'+b+':'+g);}return[...c];}export function repoAnchor(a,b){if(!b||typeof a!=='string')return[];const c=a['trim']()['replace'](/\s+/g,'-');return c?['code:'+b+':'+c]:[];}export function techAnchor(a){if(typeof a!=='string')return[];const b=a['trim']()['toLowerCase']()['replace'](/\s+/g,'-');return b?['tech:_:'+b]:[];}function capAnchors(a){return[...new Set(a)]['slice'](0x0,MAX_ANCHORS);}function touchTriggers(a){const b=a['filter'](c=>c['startsWith']('code:'));return b['length']>0x0?[{'type':'touch','match':{'anchors':b}}]:[];}function aliasEvidence(a,b={}){const c=process.env.ROUTINECODE_SESSION_ID??process.env.CLAUDE_SESSION_ID;return{'source':a,...c?{'sessionId':c}:{},...b};}function clip(a,b){const c=typeof a==='string'?a['trim']():'';return c['length']>b?c['slice'](0x0,b)+'…':c;}const MISLEADING_ERROR_CATEGORIES=new Set(['error_chain','log_truncated','silent_failure']);export function fromErrorFix(a,b){const c=MISLEADING_ERROR_CATEGORIES['has'](String(a['errorCategory']??''))?'pitfall':'resolution',d=a['errorSignature']&&a['errorSignature']['trim']()||a['rootCause']||'',e=d?problemKeyOf(d):undefined,f=[...codeAnchorsFromFiles(a['files'],b),...techAnchor(a['library']),...techAnchor(a['stack'])];return{'kind':c,'statement':'증상:\x20'+clip(a['errorSignature'],0xc8)+'\x20|\x20원인:\x20'+clip(a['rootCause'],0x190)+'\x20|\x20조치:\x20'+clip(a['fixApproach'],0x190),...e?{'problemKey':e}:{},'anchors':capAnchors(f['length']?f:repoAnchor(a['project'],b)),'triggers':[...e?[{'type':'problem','match':{'problemKey':e}}]:[],...touchTriggers(f)],'evidence':aliasEvidence('record_error_fix',a['draftId']?{'logRef':'draft:'+a['draftId']}:{}),'evidenceLevel':'inferred'};}export function fromQuirk(a,b){const c=a['evidence']&&a['evidence']['trim']()||a['title']||'',d=c?problemKeyOf(c):undefined,e=[...techAnchor(a['library'])];return{'kind':'pitfall','statement':'겉보기:\x20'+clip(a['title'],0xc8)+'\x20|\x20실제:\x20'+clip(a['quirk'],0x190)+'\x20|\x20우회:\x20'+clip(a['workaround'],0x190),...d?{'problemKey':d}:{},'anchors':capAnchors(e['length']?e:repoAnchor(a['project'],b)),'triggers':d?[{'type':'problem','match':{'problemKey':d}}]:[],'evidence':aliasEvidence('record_quirk'),'evidenceLevel':'inferred'};}const CONVENTION_PATTERN_TYPES=new Set(['validation','error_handling','config_management','serialization','multi_tenancy']);export function fromPattern(a,b){const c=CONVENTION_PATTERN_TYPES['has'](String(a['patternType']??''))?'convention':'procedure',d=codeAnchorsFromFiles(a['files'],b),e=d['length']?d:[...repoAnchor(a['project'],b),...techAnchor(a['stack'])],f=touchTriggers(d);return{'kind':c,'statement':clip(a['title'],0xc8)+':\x20'+clip(a['description'],0x258),'anchors':capAnchors(e),'triggers':f['length']?f:[{'type':'question','match':{'topic':clip(a['title'],0xc8)}}],'evidence':aliasEvidence('record_pattern'),'evidenceLevel':'inferred'};}const DEFAULT_FACT_TTL_MS=0xb4*0x18*0x3c*0x3c*0x3e8;export function fromDomainKnowledge(a,b,c=new Date()){const d=a['category']==='external'?'pitfall':a['category']==='tenant'?'fact':'rule',e=codeAnchorsFromFiles(a['scope'],b),f=e['length']?e:repoAnchor(a['project'],b),g=d==='pitfall'&&a['title']?problemKeyOf(a['title']):undefined,h=touchTriggers(f);return{'kind':d,'statement':clip(a['title'],0xc8)+':\x20'+clip(a['knowledge'],0x258),...g?{'problemKey':g}:{},'anchors':capAnchors(f),'triggers':[...h,...g?[{'type':'problem','match':{'problemKey':g}}]:[]],'evidence':aliasEvidence('record_domain_knowledge'),'evidenceLevel':a['source']==='user_correction'||a['source']==='explicit'?'stated':'inferred','observedAt':c['toISOString'](),...d==='fact'?{'expiresAt':new Date(c['getTime']()+DEFAULT_FACT_TTL_MS)['toISOString']()}:{}};}export function fromDecision(a,b){const c=codeAnchorsFromFiles(a['scope'],b),d=c['length']?c:repoAnchor(a['project'],b),e=a['rejected']?'\x20|\x20기각:\x20'+clip(a['rejected'],0x12c):'',f=a['reason']?'\x20|\x20이유:\x20'+clip(a['reason'],0x12c):'',g=touchTriggers(d);return{'kind':'decision','statement':''+clip(a['statement'],0x190)+e+f,'anchors':capAnchors(d),'triggers':g['length']?g:[{'type':'question','match':{'topic':clip(a['statement'],0xc8)}}],'evidence':aliasEvidence('record_decision'),'evidenceLevel':a['sourceQuote']?'stated':'inferred'};}
|
|
1
|
+
import*as a13a from'crypto';import*as a13b from'fs';import*as a13c from'path';import{SANITIZE_RULES}from'./sanitize.generated.js';export const KNOWLEDGE_KINDS=['structure','convention','rule','decision','procedure','resolution','pitfall','fact'];export const TRIGGER_TYPES=['problem','touch','event','command','schedule','question'];export const EVIDENCE_LEVELS=['verified','stated','inferred'];const EVIDENCE_KEYS=['sessionId','commit','logRef','source'],RE_PATH=/(?:[A-Za-z]:)?(?:[\\/][^\s\\/"':,;)\]}]+){2,}[\\/]?/g,RE_ISO=/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g,RE_EPOCH=/\b\d{10,}\b/g,RE_IPV4=/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?::\d+)?\b/g,RE_LINECOL=/(?<=[A-Za-z0-9_])\.[A-Za-z0-9]{1,6}(:\d+(?::\d+)?)\b/g,RE_UUID=/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,RE_MEMADDR=/\b0x[0-9a-fA-F]+\b/g,RE_HEX=/\b[0-9a-fA-F]{8,}\b/g,RE_SEMVER=/\b(\d+)\.\d+\.\d+(?:[-+][0-9A-Za-z.\-]+)?\b/g;function basenameOf(a){const b=a['replace'](/[\\/]+$/,'')['split'](/[\\/]/);return b[b['length']-0x1]||a;}export function normalizeSigText(a){if(!a)return'';let b=String(a);return b=b['replace'](RE_PATH,c=>basenameOf(c)),b=b['replace'](RE_ISO,'*'),b=b['replace'](RE_EPOCH,'*'),b=b['replace'](RE_IPV4,'*'),b=b['replace'](RE_LINECOL,c=>{const d=c['slice'](c['indexOf'](':'));return c['slice'](0x0,c['indexOf'](':'))+':'+d['slice'](0x1)['split'](':')['map'](()=>'N')['join'](':');}),b=b['replace'](RE_UUID,'*'),b=b['replace'](RE_MEMADDR,'0x*'),b=b['replace'](RE_HEX,'*'),b=b['replace'](RE_SEMVER,(c,d)=>d),b=b['replace'](/\s+/g,'\x20')['trim'](),b['length']>0x200?b['slice'](0x0,0x200):b;}const PROBLEM_KEY_RE=/^[0-9a-f]{12}$/;export function problemKeyOf(a){const b=String(a??'')['trim']();if(PROBLEM_KEY_RE['test'](b))return b;return a13a['createHash']('sha1')['update'](normalizeSigText(b))['digest']('hex')['slice'](0x0,0xc);}export function normalizeStatement(a){return String(a??'')['toLowerCase']()['replace'](/\s+/g,'\x20')['trim']()['replace'](/[.。!?\s]+$/u,'');}export function accountDirName(a){if(!a['tenantId'])return null;return(a['kind']==='team'?'t':'p')+'-'+a['tenantId'];}export function knowledgeLocalId(a,b){const c=a+'|'+b['kind']+'|'+(b['problemKey']??'')+'|'+normalizeStatement(b['statement']);return'k_'+a13a['createHash']('sha1')['update'](c)['digest']('hex')['slice'](0x0,0x10);}const SECRET_DETECTORS=[...SANITIZE_RULES['filter'](a=>a['kind']==='secret'&&a['id']!=='key_value_secret')['map'](a=>({'id':a['id'],'re':new RegExp(a['re']['source'],a['re']['flags']['replace']('g',''))})),{'id':'key_value_secret','re':/(?:api[-_]?key|token|secret|password|passwd|credential)s?\s*[=:]\s*["']?(?=[A-Za-z0-9_\-/+]*\d|[A-Za-z0-9_\-/+]{20,})[A-Za-z0-9_\-/+]{8,}/i}];export function detectSecret(a){for(const b of SECRET_DETECTORS)if(b['re']['test'](a))return b['id'];return null;}function collectStrings(a,b,c){if(typeof a==='string')c['push']({'at':b,'text':a});else{if(Array['isArray'](a))a['forEach']((d,e)=>collectStrings(d,b+'['+e+']',c));else{if(a&&typeof a==='object'){for(const [d,e]of Object['entries'](a))collectStrings(e,b+'.'+d,c);}}}}const PLACEHOLDER_TOKEN_RE=/^(foo|bar|baz|qux|quux|lorem|ipsum|dolor|sit|amet|dummy|placeholder|sample|test\d*|example\.(com|org|net)|asdf+|qwerty|xxx+|todo|tbd|hello|world)$/,FILLER_TOKEN_RE=/^(a|an|the|is|are|and|or|of|to|in|on|for|with|this|that|it)$/,FAKE_PATH_RE=/(^|\/)(tmp|fixtures)\//,TIME_MARKER_RE=/\b20\d\d-\d\d-\d\d\b|\b\d{1,2}\/\d{1,2}\b|관찰\(|실측|오늘|현재|배포한|:[a-z][\w-]*-\d{6}\b/,AUTO_EXPIRY_MS=0x1e*0x18*0x3c*0x3c*0x3e8;export function hasTimeMarker(a){return TIME_MARKER_RE['test'](String(a??''));}export function isPlaceholderText(a){const b=String(a??'')['toLowerCase']()['split'](/[^a-z0-9.@_-]+/)['map'](d=>d['replace'](/^[.\-_]+|[.\-_]+$/g,''))['filter'](Boolean),c=b['filter'](d=>!FILLER_TOKEN_RE['test'](d));return c['length']>0x0&&c['every'](d=>PLACEHOLDER_TOKEN_RE['test'](d));}function isTestAnchorLocal(a){return FAKE_PATH_RE['test'](a);}function isTestSession(a){return!!a&&/^(integration-|test-)/i['test'](a);}export const STATEMENT_MAX=0xc8;const STATEMENT_HEAD_MIN=0x1e,BOUNDARY_RE=/\.\s|。|\s\|\s|\n/g;export function splitStatement(a){const b=String(a??'')['trim']();if(b['length']<=STATEMENT_MAX)return{'statement':b,'detail':null};BOUNDARY_RE['lastIndex']=0x0;for(let c=BOUNDARY_RE['exec'](b);c;c=BOUNDARY_RE['exec'](b)){const d=c[0x0]['startsWith']('.')||c[0x0]==='。'?0x1:0x0,e=b['slice'](0x0,c['index']+d)['trim']();if(e['length']>STATEMENT_MAX)break;if(e['length']>=STATEMENT_HEAD_MIN)return{'statement':e,'detail':b};}return{'statement':b['slice'](0x0,STATEMENT_MAX-0x1)['trimEnd']()+'…','detail':b};}const ANCHOR_RE=/^(code|onto|tech):([^:]+):(.+)$/,MIN_STATEMENT=0xa,MAX_STATEMENT=0x7d0,MAX_ANCHORS=0x14,MAX_TRIGGERS=0xa,ERR_TEXT_MIN=0x8,EXC_RE=/\b([A-Z][A-Za-z]*(?:Error|Exception|Exit)):\s*([^\n)\]]{4,100})/g,QUOTED_RE=/'([^'\n]{8,120})'|"([^"\n]{8,120})"|`([^`\n]{8,120})`/g,ERR_MARK_RE=/fatal|error|ERR!|not found|No such|denied|failed|cannot|refused|EACCES|ENOENT|ECONN|no matches|not a git|Traceback|Unauthorized|forbidden/i,SCRIPT_RE=/(?<![\w./-])([A-Za-z0-9][\w-]*\.(?:sh|py|mjs))\b/g,reEscape=a=>a['replace'](/[.*+?^${}()|[\]\\\-]/g,'\x5c$&');export function deriveTriggers(a,b=0x3){const c=[],d=new Set(),e=g=>{const h=JSON['stringify'](g);!d['has'](h)&&c['length']<b&&(d['add'](h),c['push'](g));},f=String(a??'');for(const g of f['matchAll'](EXC_RE)){const h=(g[0x1]+':\x20'+g[0x2])['trim']()['replace'](/[.,;:'"` ]+$/,'');if(h['length']>=ERR_TEXT_MIN)e({'type':'problem','match':{'text':h}});}for(const i of f['matchAll'](QUOTED_RE)){const j=(i[0x1]??i[0x2]??i[0x3]??'')['trim']();if(j['length']>=ERR_TEXT_MIN&&ERR_MARK_RE['test'](j))e({'type':'problem','match':{'text':j['replace'](/[.,;: ]+$/,'')}});}for(const k of f['matchAll'](SCRIPT_RE)){e({'type':'command','match':{'regex':'(?:^|[\x5cs/;&|])'+reEscape(k[0x1]??'')+'\x5cb'}});}return c;}const MAX_PROBLEM_KEY=0xc8;function isPlainObject(a){return!!a&&typeof a==='object'&&!Array['isArray'](a);}function parseTime(a){if(typeof a!=='string'||!a['trim']())return null;const b=Date['parse'](a);return Number['isFinite'](b)?b:null;}export function validateKnowledge(b,c,e=new Date()){const f=[];if(!isPlainObject(b))return{'ok':![],'reasons':['input:\x20object\x20required']};const g=b;if(!c['tenantId'])f['push']('owner:\x20no\x20account\x20space\x20(login\x20or\x20`routinecode\x20team\x20switch`\x20required)');(typeof g['kind']!=='string'||!KNOWLEDGE_KINDS['includes'](g['kind']))&&f['push']('kind:\x20must\x20be\x20one\x20of\x20'+KNOWLEDGE_KINDS['join']('|'));const h=typeof g['statement']==='string'?g['statement']['trim']():'';if(!h)f['push']('statement:\x20required');else{if(h['length']<MIN_STATEMENT)f['push']('test-data:\x20statement\x20shorter\x20than\x20'+MIN_STATEMENT+'\x20chars');else{if(h['length']>MAX_STATEMENT)f['push']('statement:\x20longer\x20than\x20'+MAX_STATEMENT+'\x20chars');else{if(isPlaceholderText(h))f['push']('test-data:\x20statement\x20is\x20placeholder-only\x20text');}}}let j;if(g['problemKey']!==undefined&&g['problemKey']!==null&&g['problemKey']!==''){if(typeof g['problemKey']!=='string')f['push']('problemKey:\x20string\x20required');else{if(g['problemKey']['length']>MAX_PROBLEM_KEY*0xa)f['push']('problemKey:\x20too\x20long');else j=problemKeyOf(g['problemKey']);}}(g['kind']==='resolution'||g['kind']==='pitfall')&&!j&&f['push']('problemKey:\x20required\x20for\x20kind\x20'+g['kind']+'\x20(R-M4)');const l=[];if(!Array['isArray'](g['anchors'])||g['anchors']['length']===0x0)f['push']('anchors:\x20at\x20least\x20one\x20anchor\x20required\x20(R-T3)');else{if(g['anchors']['length']>MAX_ANCHORS)f['push']('anchors:\x20at\x20most\x20'+MAX_ANCHORS);else for(const y of g['anchors']){const z=typeof y==='string'?ANCHOR_RE['exec'](y['trim']()):null;if(!z){f['push']('anchors:\x20malformed\x20\x27'+String(y)['slice'](0x0,0x50)+'\x27\x20(want\x20<code|onto|tech>:<tenant|_>:<local>)');continue;}const [,A,B,C]=z;if(A==='code'){if(c['tenantId']&&B!==c['tenantId'])f['push']('anchors:\x20code\x20anchor\x20tenant\x20\x27'+B+'\x27\x20is\x20not\x20this\x20account');(/^(?:\/|[A-Za-z]:[\\/])/['test'](C)||C['split'](/[\\/]/)['includes']('..'))&&f['push']('anchors:\x20code\x20anchor\x20must\x20be\x20repo-relative\x20(\x27'+C['slice'](0x0,0x50)+'\x27)');}if(A==='tech'&&B!=='_')f['push']('anchors:\x20tech\x20anchor\x20tenant\x20must\x20be\x20\x27_\x27\x20(\x27'+B+'\x27)');if(isTestAnchorLocal(C))f['push']('test-data:\x20anchor\x20under\x20tmp/\x20or\x20fixtures/\x20(\x27'+C['slice'](0x0,0x50)+'\x27)');if(l['includes'](y['trim']()))f['push']('anchors:\x20duplicate\x20\x27'+y['trim']()['slice'](0x0,0x50)+'\x27');else l['push'](y['trim']());}}const n=[];if(!Array['isArray'](g['triggers'])||g['triggers']['length']===0x0)f['push']('triggers:\x20at\x20least\x20one\x20trigger\x20required');else{if(g['triggers']['length']>MAX_TRIGGERS)f['push']('triggers:\x20at\x20most\x20'+MAX_TRIGGERS);else for(const D of g['triggers']){if(!isPlainObject(D)||typeof D['type']!=='string'||!TRIGGER_TYPES['includes'](D['type'])){f['push']('triggers:\x20type\x20must\x20be\x20one\x20of\x20'+TRIGGER_TYPES['join']('|'));continue;}if(!isPlainObject(D['match'])||Object['keys'](D['match'])['length']===0x0){f['push']('triggers:\x20\x27'+D['type']+'\x27\x20needs\x20a\x20non-empty\x20match\x20object');continue;}n['push']({'type':D['type'],'match':D['match']});}}if(h&&(g['kind']==='pitfall'||g['kind']==='resolution'||g['kind']==='procedure')&&!f['some'](E=>E['startsWith']('triggers:')&&!E['includes']('at\x20least\x20one'))){const E=new Set(n['map'](F=>JSON['stringify'](F)));for(const F of deriveTriggers(h)){if(n['length']>=MAX_TRIGGERS)break;!E['has'](JSON['stringify'](F))&&(n['push'](F),E['add'](JSON['stringify'](F)));}if(n['length']>0x0){const G=f['indexOf']('triggers:\x20at\x20least\x20one\x20trigger\x20required');if(G>=0x0)f['splice'](G,0x1);}}const o={};if(!isPlainObject(g['evidence']))f['push']('evidence:\x20object\x20with\x20one\x20of\x20sessionId|commit|logRef|source\x20required\x20(R-T1)');else{for(const H of EVIDENCE_KEYS){const I=g['evidence'][H];if(typeof I==='string'&&I['trim']())o[H]=I['trim']();}if(Object['keys'](o)['length']===0x0)f['push']('evidence:\x20one\x20of\x20sessionId|commit|logRef|source\x20required\x20(R-T1)');if(isTestSession(o['sessionId']))f['push']('test-data:\x20evidence\x20from\x20a\x20test\x20session');}let p='inferred';if(g['evidenceLevel']!==undefined&&g['evidenceLevel']!==null){if(!EVIDENCE_LEVELS['includes'](g['evidenceLevel']))f['push']('evidenceLevel:\x20must\x20be\x20one\x20of\x20'+EVIDENCE_LEVELS['join']('|'));else p=g['evidenceLevel'];}p==='verified'&&!o['commit']&&!o['logRef']&&f['push']('evidenceLevel:\x20verified\x20needs\x20evidence.commit\x20or\x20evidence.logRef\x20(R-M7)');let q=e['toISOString']();if(g['observedAt']!==undefined&&g['observedAt']!==null&&g['observedAt']!==''){const J=parseTime(g['observedAt']);if(J===null)f['push']('observedAt:\x20ISO\x20date\x20required');else q=new Date(J)['toISOString']();}let r;if(g['expiresAt']!==undefined&&g['expiresAt']!==null&&g['expiresAt']!==''){const K=parseTime(g['expiresAt']);if(K===null)f['push']('expiresAt:\x20ISO\x20date\x20required');else{if(K<=Date['parse'](q))f['push']('expiresAt:\x20must\x20be\x20after\x20observedAt');else r=new Date(K)['toISOString']();}}!r&&g['kind']!=='fact'&&g['kind']!=='rule'&&g['kind']!=='convention'&&g['kind']!=='decision'&&!f['some'](L=>L['startsWith']('observedAt'))&&typeof g['statement']==='string'&&hasTimeMarker(g['statement'])&&(r=new Date(Date['parse'](q)+AUTO_EXPIRY_MS)['toISOString']());g['kind']==='fact'&&!r&&!f['some'](L=>L['startsWith']('expiresAt'))&&f['push']('expiresAt:\x20required\x20for\x20kind\x20fact\x20(R-T5)');const u=[];collectStrings({'statement':g['statement'],'detail':g['detail'],'problemKey':g['problemKey'],'anchors':g['anchors'],'triggers':g['triggers'],'evidence':g['evidence']},'input',u);for(const L of u){const M=detectSecret(L['text']);if(M)f['push']('secret:\x20'+M+'\x20detected\x20in\x20'+L['at']['replace'](/^input\./,'')+'\x20(R-T6)');}if(g['detail']!==undefined&&g['detail']!==null&&typeof g['detail']!=='string')f['push']('detail:\x20string\x20required');else{if(typeof g['detail']==='string'&&g['detail']['length']>0xfa0)f['push']('detail:\x20longer\x20than\x204000\x20chars');}if(f['length']>0x0)return{'ok':![],'reasons':f};const w=splitStatement(h),x=typeof g['detail']==='string'&&g['detail']['trim']()?g['detail']['trim']():w['detail'];return{'ok':!![],'item':{'kind':g['kind'],'statement':w['statement'],...x?{'detail':x}:{},...j?{'problemKey':j}:{},'anchors':l,'triggers':n,'evidence':o,'evidenceLevel':p,'observedAt':q,...r?{'expiresAt':r}:{}}};}function findRepoRoot(a){let b=a13c['dirname'](a);for(let c=0x0;c<0x28;c++){if(a13b['existsSync'](a13c['join'](b,'.git')))return b;const d=a13c['dirname'](b);if(d===b)return null;b=d;}return null;}export function codeAnchorsFromFiles(a,b){if(!b||!Array['isArray'](a))return[];const c=new Set();for(const d of a){if(typeof d!=='string'||!d['trim']())continue;const e=d['trim']()['replace'](/:\d+(?::\d+)?$/,'');let g;if(a13c['isAbsolute'](e)){const h=findRepoRoot(e);g=h?a13c['join'](a13c['basename'](h),a13c['relative'](h,e))['split'](a13c['sep'])['join']('/'):null;}else g=e['replace'](/^\.\//,'');if(g&&!/\s/['test'](g))c['add']('code:'+b+':'+g);}return[...c];}export function repoAnchor(a,b){if(!b||typeof a!=='string')return[];const c=a['trim']()['replace'](/\s+/g,'-');return c?['code:'+b+':'+c]:[];}export function techAnchor(a){if(typeof a!=='string')return[];const b=a['trim']()['toLowerCase']()['replace'](/\s+/g,'-');return b?['tech:_:'+b]:[];}function capAnchors(a){return[...new Set(a)]['slice'](0x0,MAX_ANCHORS);}function touchTriggers(a){const b=a['filter'](c=>c['startsWith']('code:'));return b['length']>0x0?[{'type':'touch','match':{'anchors':b}}]:[];}function aliasEvidence(a,b={}){const c=process.env.ROUTINECODE_SESSION_ID??process.env.CLAUDE_SESSION_ID;return{'source':a,...c?{'sessionId':c}:{},...b};}function clip(a,b){const c=typeof a==='string'?a['trim']():'';return c['length']>b?c['slice'](0x0,b)+'…':c;}const MISLEADING_ERROR_CATEGORIES=new Set(['error_chain','log_truncated','silent_failure']);export function fromErrorFix(a,b){const c=MISLEADING_ERROR_CATEGORIES['has'](String(a['errorCategory']??''))?'pitfall':'resolution',d=a['errorSignature']&&a['errorSignature']['trim']()||a['rootCause']||'',e=d?problemKeyOf(d):undefined,f=[...codeAnchorsFromFiles(a['files'],b),...techAnchor(a['library']),...techAnchor(a['stack'])];return{'kind':c,'statement':'증상:\x20'+clip(a['errorSignature'],0xc8)+'\x20|\x20원인:\x20'+clip(a['rootCause'],0x190)+'\x20|\x20조치:\x20'+clip(a['fixApproach'],0x190),...e?{'problemKey':e}:{},'anchors':capAnchors(f['length']?f:repoAnchor(a['project'],b)),'triggers':[...e?[{'type':'problem','match':{'problemKey':e}}]:[],...touchTriggers(f)],'evidence':aliasEvidence('record_error_fix',a['draftId']?{'logRef':'draft:'+a['draftId']}:{}),'evidenceLevel':'inferred'};}export function fromQuirk(a,b){const c=a['evidence']&&a['evidence']['trim']()||a['title']||'',d=c?problemKeyOf(c):undefined,e=[...techAnchor(a['library'])];return{'kind':'pitfall','statement':'겉보기:\x20'+clip(a['title'],0xc8)+'\x20|\x20실제:\x20'+clip(a['quirk'],0x190)+'\x20|\x20우회:\x20'+clip(a['workaround'],0x190),...d?{'problemKey':d}:{},'anchors':capAnchors(e['length']?e:repoAnchor(a['project'],b)),'triggers':d?[{'type':'problem','match':{'problemKey':d}}]:[],'evidence':aliasEvidence('record_quirk'),'evidenceLevel':'inferred'};}const CONVENTION_PATTERN_TYPES=new Set(['validation','error_handling','config_management','serialization','multi_tenancy']);export function fromPattern(a,b){const c=CONVENTION_PATTERN_TYPES['has'](String(a['patternType']??''))?'convention':'procedure',d=codeAnchorsFromFiles(a['files'],b),e=d['length']?d:[...repoAnchor(a['project'],b),...techAnchor(a['stack'])],f=touchTriggers(d);return{'kind':c,'statement':clip(a['title'],0xc8)+':\x20'+clip(a['description'],0x258),'anchors':capAnchors(e),'triggers':f['length']?f:[{'type':'question','match':{'topic':clip(a['title'],0xc8)}}],'evidence':aliasEvidence('record_pattern'),'evidenceLevel':'inferred'};}const DEFAULT_FACT_TTL_MS=0xb4*0x18*0x3c*0x3c*0x3e8;export function fromDomainKnowledge(a,b,c=new Date()){const d=a['category']==='external'?'pitfall':a['category']==='tenant'?'fact':'rule',e=codeAnchorsFromFiles(a['scope'],b),f=e['length']?e:repoAnchor(a['project'],b),g=d==='pitfall'&&a['title']?problemKeyOf(a['title']):undefined,h=touchTriggers(f);return{'kind':d,'statement':clip(a['title'],0xc8)+':\x20'+clip(a['knowledge'],0x258),...g?{'problemKey':g}:{},'anchors':capAnchors(f),'triggers':[...h,...g?[{'type':'problem','match':{'problemKey':g}}]:[]],'evidence':aliasEvidence('record_domain_knowledge'),'evidenceLevel':a['source']==='user_correction'||a['source']==='explicit'?'stated':'inferred','observedAt':c['toISOString'](),...d==='fact'?{'expiresAt':new Date(c['getTime']()+DEFAULT_FACT_TTL_MS)['toISOString']()}:{}};}export function fromDecision(a,b){const c=codeAnchorsFromFiles(a['scope'],b),d=c['length']?c:repoAnchor(a['project'],b),e=a['rejected']?'\x20|\x20기각:\x20'+clip(a['rejected'],0x12c):'',f=a['reason']?'\x20|\x20이유:\x20'+clip(a['reason'],0x12c):'',g=touchTriggers(d);return{'kind':'decision','statement':''+clip(a['statement'],0x190)+e+f,'anchors':capAnchors(d),'triggers':g['length']?g:[{'type':'question','match':{'topic':clip(a['statement'],0xc8)}}],'evidence':aliasEvidence('record_decision'),'evidenceLevel':a['sourceQuote']?'stated':'inferred'};}
|