@routinecrew/routinecode 2.31.85 → 2.31.86
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/cli.sh +10 -0
- package/bin/prompt-vault.dat +1 -1
- package/bin/rc-board.js +58 -0
- package/bin/rc-skills.js +31 -0
- package/bin/setup.js +1 -1
- package/hooks/hooks-config.json +10 -1
- package/hooks/lib/agent_telemetry.py +143 -0
- package/hooks/lib/board-golden.json +268 -0
- package/hooks/lib/board.py +503 -0
- package/hooks/lib/board_sync.py +535 -0
- package/hooks/lib/completion_log.py +12 -5
- package/hooks/lib/config_bash_track.py +14 -26
- package/hooks/lib/config_guard.py +133 -4
- package/hooks/lib/edit_tracker.py +182 -0
- package/hooks/lib/i18n.py +14 -0
- package/hooks/lib/knowledge_items.py +74 -8
- package/hooks/lib/usage_v2.py +12 -0
- package/hooks/post-agent-return.sh +5 -0
- package/hooks/post-edit-track.sh +19 -28
- package/hooks/post-orch-decision.sh +17 -0
- package/hooks/pre-account-guard.sh +1 -1
- package/hooks/pre-credit-guard.sh +1 -1
- package/hooks/pre-edit-board.sh +44 -0
- package/hooks/pre-edit-check.sh +27 -3
- package/hooks/pre-mark-complete.sh +17 -3
- package/hooks/session-start.sh +63 -3
- package/hooks/skill-knowledge.sh +6 -0
- package/mcp-routinecode/dist/board.js +1 -0
- package/mcp-routinecode/dist/build-id.js +1 -0
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/applied.js +1 -0
- package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
- package/mcp-routinecode/dist/config-map/architect-store.js +1 -7
- 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/blocks.js +1 -1
- package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -1
- package/mcp-routinecode/dist/config-map/decisions.js +1 -1
- package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
- package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
- package/mcp-routinecode/dist/config-map/hash.js +1 -1
- package/mcp-routinecode/dist/config-map/index-store.js +62 -5
- package/mcp-routinecode/dist/config-map/link.js +1 -1
- package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
- package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/proposals.js +1 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/route-security.js +1 -1
- package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
- package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
- package/mcp-routinecode/dist/config-map/shape.js +1 -1
- package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
- package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
- package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
- package/mcp-routinecode/dist/config-map/store.js +1 -1
- package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
- package/mcp-routinecode/dist/config-map/templates.js +1 -1
- package/mcp-routinecode/dist/contracts.generated.js +1 -1
- package/mcp-routinecode/dist/coverage.js +1 -1
- package/mcp-routinecode/dist/edit-tracker.js +1 -0
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-lock-registry.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/normalize-sig.js +1 -1
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -0
- package/mcp-routinecode/dist/pattern-matcher.js +1 -1
- package/mcp-routinecode/dist/route-match.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 -0
- package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
- package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/verification.js +1 -1
- package/mcp-routinecode/package.json +1 -1
- package/package.json +2 -2
- package/plugin/.claude-plugin/plugin.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.md.sealed +1 -1
- package/plugin/agents/looker.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/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 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a51a from'fs';import*as a51b from'path';import{homedir}from'os';import{noteAuthFailure}from'./config-auth.js';import{knowledgeSendAllowed,logTransmission,queueAllowed,sanitizeDeep}from'./sanitize.generated.js';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a51b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a51b['join'](ROUTINECODE_DIR,'knowledge'),EVENTS_PATH=a51b['join'](KNOWLEDGE_DIR,'events.jsonl'),CONFIG_PATH=process.env.ROUTINECODE_CONFIG_PATH??a51b['join'](ROUTINECODE_DIR,'config.json'),USAGE_EVENTS_PATH=a51b['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};a51a['mkdirSync'](a51b['dirname'](USAGE_EVENTS_PATH),{'recursive':!![]}),a51a['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']);}export 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(!a51a['existsSync'](EVENTS_PATH))return[];const a=a51a['statSync'](EVENTS_PATH)['mtimeMs'];if(cachedEntries&&cachedMtime===a)return cachedEntries;const b=a51a['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'](a51a['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 PENDING_PATH=a51b['join'](KNOWLEDGE_DIR,'pending-sync.jsonl'),LOCK_STALE_MS=0x1388;function acquireLock(a){const b=a+'.lock';for(let c=0x0;c<0x32;c++){try{const d=a51a['openSync'](b,'wx');return a51a['closeSync'](d),b;}catch{try{const g=a51a['statSync'](b);if(Date['now']()-g['mtimeMs']>LOCK_STALE_MS){a51a['unlinkSync'](b);continue;}}catch{}const f=Date['now']()+0x14;while(Date['now']()<f){}}}return null;}function releaseLock(a){try{a51a['unlinkSync'](a);}catch{}}export function enqueueVerify(a,b){if(!a||a['length']===0x0)return 0x0;if(!queueAllowed(loadConfig()))return 0x0;const c=acquireLock(PENDING_PATH);if(!c)return 0x0;try{const d=a['map'](f=>JSON['stringify']({'endpoint':'ontology/verify','data':{'errorFixId':f,'result':'prevented','project':b,'techStack':{},'source':'auto-hook'},'ts':new Date()['toISOString'](),'retries':0x0}))['join']('\x0a')+'\x0a';return a51a['appendFileSync'](PENDING_PATH,d),a['length'];}catch{return 0x0;}finally{releaseLock(c);}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a52c from'fs';import*as a52d from'path';import{homedir}from'os';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a52d['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a52d['join'](ROUTINECODE_DIR,'knowledge'),LEDGER_PATH=a52d['join'](ROUTINECODE_DIR,'ledger','current.jsonl'),CAUSAL_LINKS_PATH=a52d['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),MINE_STATE_PATH=a52d['join'](KNOWLEDGE_DIR,'last-ledger-mine.json'),MINE_INTERVAL_MS=0x3c*0x3c*0x3e8,COCHANGE_WINDOW_MS=0xa*0x3c*0x3e8,MIN_OBS=0x1;function projectRoot(c){const d=c['match'](/\/dev\/kangsan\/([^/]+)\//)||c['match'](/\/([^/]+)\/(?:src|apps|packages)\//);return d?d[0x1]:null;}function isProjectFile(c){if(!c)return![];if(/\/(node_modules|\.git|dist|build)\//['test'](c))return![];if(/^\/(private\/)?tmp\/|\/T\/|scratch|\.output$/['test'](c))return![];return/\.(ts|tsx|js|jsx|py|go|rs|java|rb|php|sql|vue|svelte)$/['test'](c)||/\/(src|apps|packages)\//['test'](c);}export function mineLedgerCoChanges(c=![]){if(!c)try{const m=JSON['parse'](a52c['readFileSync'](MINE_STATE_PATH,'utf-8'))['ts']??0x0;if(Date['now']()-m<MINE_INTERVAL_MS)return{'mined':0x0,'pairs':0x0,'sessions':0x0,'skipped':'interval'};}catch{}if(!a52c['existsSync'](LEDGER_PATH))return{'mined':0x0,'pairs':0x0,'sessions':0x0,'skipped':'no-ledger'};const d=new Map();try{for(const n of a52c['readFileSync'](LEDGER_PATH,'utf-8')['split']('\x0a')){if(!n)continue;let o;try{o=JSON['parse'](n);}catch{continue;}if(o['category']!=='code_change')continue;const p=o['payload']?.['file'];if(!isProjectFile(p))continue;const q=o['session_id']??'default',r=(o['ts']??0x0)*0x3e8;if(!d['has'](q))d['set'](q,{'files':[]});d['get'](q)['files']['push']({'file':p,'ts':r});}}catch{return{'mined':0x0,'pairs':0x0,'sessions':0x0,'skipped':'read-error'};}const g=new Map();for(const [t,u]of d){const v=Array['from'](new Set(u['files']['map'](y=>y['file']))),w=u['files']['slice']()['sort']((z,A)=>z['ts']-A['ts']),x=new Set();for(let y=0x0;y<w['length'];y++){for(let z=y+0x1;z<w['length'];z++){if(w[z]['ts']-w[y]['ts']>COCHANGE_WINDOW_MS)break;if(w[y]['file']===w[z]['file'])continue;const A=projectRoot(w[y]['file']),B=projectRoot(w[z]['file']);if(!A||A!==B)continue;const [C,D]=[w[y]['file'],w[z]['file']]['sort'](),E=C+'::'+D;if(x['has'](E))continue;x['add'](E);if(!g['has'](E))g['set'](E,{'a':C,'b':D,'sessions':new Set()});g['get'](E)['sessions']['add'](t);}}void v;}const h=new Date()['toISOString'](),k=[];let l=0x0;for(const {a:F,b:G,sessions:H}of g['values']()){if(H['size']<MIN_OBS)continue;l++;const I=Math['min'](0.9,0.4+H['size']*0.1);k['push'](JSON['stringify']({'trigger':{'file':F,'changeSummary':'co-change\x20(ledger-derived)'},'effect':{'file':G,'errorSignature':''},'project':'ledger-mined','confidence':I,'observedCount':H['size'],'source':'ledger-miner','ts':h})),k['push'](JSON['stringify']({'trigger':{'file':G,'changeSummary':'co-change\x20(ledger-derived)'},'effect':{'file':F,'errorSignature':''},'project':'ledger-mined','confidence':I,'observedCount':H['size'],'source':'ledger-miner','ts':h}));}try{a52c['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});let J=[];a52c['existsSync'](CAUSAL_LINKS_PATH)&&(J=a52c['readFileSync'](CAUSAL_LINKS_PATH,'utf-8')['split']('\x0a')['filter'](L=>{if(!L['trim']())return![];try{return JSON['parse'](L)['source']!=='ledger-miner';}catch{return!![];}}));const K=[...J,...k];if(K['length']>0x0){const L=CAUSAL_LINKS_PATH+'.tmp';a52c['writeFileSync'](L,K['join']('\x0a')+'\x0a'),a52c['renameSync'](L,CAUSAL_LINKS_PATH);}}catch{}try{a52c['writeFileSync'](MINE_STATE_PATH,JSON['stringify']({'ts':Date['now'](),'pairs':l,'sessions':d['size']}));}catch{}return{'mined':k['length'],'pairs':l,'sessions':d['size']};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a53a from'crypto';const 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 a53a['createHash']('sha1')['update'](normalizeSigText(b))['digest']('hex')['slice'](0x0,0xc);}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import{recordEdits}from'./edit-tracker.js';import*as a54a from'fs';import*as a54b from'path';import{homedir}from'os';import{execSync}from'child_process';const ROUTINECODE_DIR=process.env.ROUTINECODE_DIR??a54b['join'](homedir(),'.routinecode'),KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a54b['join'](ROUTINECODE_DIR,'knowledge'),OBSERVED_DIR=a54b['join'](KNOWLEDGE_DIR,'observed');export 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 a54b['join'](OBSERVED_DIR,'draft-'+projectHash(a)+'.json');}function gitHead(a){try{return execSync('git\x20rev-parse\x20HEAD',{'cwd':a,'encoding':'utf-8','stdio':['ignore','pipe','ignore'],'timeout':0xbb8})['trim']();}catch{return null;}}function loadDraftFile(a){try{return JSON['parse'](a54a['readFileSync'](a,'utf-8'));}catch{return null;}}function writeDraftAtomic(a,b){a54a['mkdirSync'](OBSERVED_DIR,{'recursive':!![]});const c=a+'.tmp';a54a['writeFileSync'](c,JSON['stringify'](b,null,0x2)),a54a['renameSync'](c,a);}export function observeFailure(a){try{const b=draftPath(a['projectDir']),c=loadDraftFile(b),d=new Date()['toISOString']();if(c&&!c['resolvedAt']){c['attempts']+=0x1,c['errorSignature']=a['errorSignature']||c['errorSignature'],c['communityRefs']=Array['from'](new Set([...c['communityRefs']??[],...a['communityRefs']])),writeDraftAtomic(b,c);return;}const e=projectHash(a['projectDir']);writeDraftAtomic(b,{'draftId':'d-'+e+'-'+Date['now'](),'projectHash':e,'project':a['project'],'directory':a['projectDir'],'type':a['type'],'errorSignature':a['errorSignature'],'attempts':0x1,'editedFiles':[],'communityRefs':a['communityRefs'],'gitHeadAtFail':gitHead(a['projectDir']),'firstSeen':d,'resolvedAt':null});}catch{}}export function observeResolution(a){try{const b=draftPath(a),c=loadDraftFile(b);if(!c||c['resolvedAt'])return null;c['editedFiles']=gitEditedFiles(a,c['gitHeadAtFail']),c['resolvedAt']=new Date()['toISOString'](),writeDraftAtomic(b,c);try{if(c['editedFiles']['length']>0x0)recordEdits(c['editedFiles']);}catch{}return c;}catch{return null;}}function gitEditedFiles(a,b){const c=new Set(),d=e=>{try{return execSync(e,{'cwd':a,'encoding':'utf-8','stdio':['ignore','pipe','ignore'],'timeout':0xbb8})['trim']();}catch{return'';}};return b&&d('git\x20diff\x20--name-only\x20'+b+'\x20HEAD')['split']('\x0a')['filter'](Boolean)['forEach'](e=>c['add'](e)),d('git\x20diff\x20--name-only\x20HEAD')['split']('\x0a')['filter'](Boolean)['forEach'](e=>c['add'](e)),d('git\x20diff\x20--name-only\x20--staged')['split']('\x0a')['filter'](Boolean)['forEach'](e=>c['add'](e)),Array['from'](c)['map'](e=>a54b['isAbsolute'](e)?e:a54b['join'](a,e));}export function loadResolvedDraftById(a){try{if(!a54a['existsSync'](OBSERVED_DIR))return null;for(const b of a54a['readdirSync'](OBSERVED_DIR)){if(!b['startsWith']('draft-')||!b['endsWith']('.json'))continue;const c=loadDraftFile(a54b['join'](OBSERVED_DIR,b));if(c&&c['draftId']===a)return c;}}catch{}return null;}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as a55a from'fs';import*as a55b from'path';import{homedir}from'os';import{currentSessionId}from'./session-registry.js';export const OBSERVED_STRIKES=0x2;const OPEN_TTL_MS=0x2*0xe10*0x3e8;export function observedProblems(b=currentSessionId(),c=Date['now']()){if(!b)return[];const e=process.env.ROUTINECODE_KNOWLEDGE_DIR||a55b['join'](homedir(),'.routinecode','knowledge');let g=[];try{g=a55a['readdirSync'](e)['filter'](i=>/^[pt]-/['test'](i));}catch{return[];}const h=[];for(const i of g){let j={};try{j=JSON['parse'](a55a['readFileSync'](a55b['join'](e,i,'open-problems.json'),'utf-8'));}catch{continue;}for(const [k,l]of Object['entries'](j)){if(!k['startsWith'](b)||!Array['isArray'](l))continue;for(const m of l){const n=Number(m['ts'])*0x3e8;if(!Number['isFinite'](n)||c-n>OPEN_TTL_MS)continue;const o=Number(m['refuted'])||0x0,p=new Set();for(const q of Array['isArray'](m['attempts'])?m['attempts']:[]){for(const t of Array['isArray'](q['files'])?q['files']:[])if(typeof t==='string')p['add'](t);}h['push']({'issueId':String(m['pk']??''),'label':String(m['label']??''),'check':String(m['check']??''),'failures':o+0x1,'blocking':o>=OBSERVED_STRIKES,'notTheCause':[...p]});}}}return h['sort']((u,v)=>Number(v['blocking'])-Number(u['blocking'])||v['failures']-u['failures']);}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a56a from'fs';import*as a56b from'path';import{readDomainKnowledge,knowledgePath,FILES}from'./contracts.generated.js';import{emitExposure,tokenOverlap}from'./known-solutions.js';const MATCH_THRESHOLD=0.25;function readJsonl(a){try{if(!a56a['existsSync'](a))return[];return a56a['readFileSync'](a,'utf-8')['trim']()['split']('\x0a')['filter'](Boolean)['map'](b=>{try{return JSON['parse'](b);}catch{return null;}})['filter'](b=>b!==null);}catch{return[];}}const IMPL_AGENTS=new Set(['implementor','planner','analyzer','reviewer']);export function shouldInjectForAgent(a){const b=(a||'')['toLowerCase']();return[...IMPL_AGENTS]['some'](c=>b['includes'](c));}export function matchDelegationKnowledge(a,b){const c=readJsonl(knowledgePath(FILES['PATTERNS'])),d=readJsonl(knowledgePath(FILES['DECISIONS'])),e=j=>!b||!j||j['toLowerCase']()['includes'](b['toLowerCase']())||b['toLowerCase']()['includes'](j['toLowerCase']()),f=c['map'](j=>({'p':j,'score':tokenOverlap(a,(j['title']??'')+'\x20'+(j['description']??''))+(e(j['domain'])?0.15:0x0)}))['filter'](j=>j['score']>=MATCH_THRESHOLD)['sort']((j,k)=>(k['p']['confidence']??0.5)-(j['p']['confidence']??0.5)||k['score']-j['score'])['slice'](0x0,0x3)['map'](j=>j['p']),g=d['filter'](j=>e(j['project']))['map'](j=>({'d':j,'score':tokenOverlap(a,(j['statement']??'')+'\x20'+(j['rejected']??''))}))['sort']((j,k)=>k['score']-j['score'])['slice'](0x0,0x3)['map'](j=>j['d']),h=readDomainKnowledge()['filter'](j=>e(j['project'])||(j['scope']??[])['some'](k=>typeof k==='string'&&a['includes'](a56b['basename'](k))))['slice'](0x0,0x5);if(f['length']===0x0&&g['length']===0x0&&h['length']===0x0)return'';const i=['\x0a\x0a[KNOWN-SOLUTIONS-CTX]'];return h['length']>0x0&&(i['push']('[DOMAIN\x20RULES]\x20constraints\x20not\x20derivable\x20from\x20code\x20—\x20treat\x20as\x20HARD\x20preconditions;\x20do\x20NOT\x20re-discover\x20or\x20flag\x20as\x20bugs:'),h['forEach']((j,k)=>{i['push'](k+0x1+'.\x20['+san(j['category']??'rule')+']\x20'+san(j['title']??'')+':\x20'+san((j['knowledge']??'')['slice'](0x0,0x12c))+(j['source']?'\x20(src:\x20'+san(j['source'])+')':''));})),f['length']>0x0&&(i['push']('[KNOWN\x20PATTERNS]\x20'+(b||'this')+'\x20domain\x20—\x20verified\x20implementation\x20patterns:'),f['forEach']((j,k)=>{i['push'](k+0x1+'.\x20'+san(j['title']??'')+'\x20(confidence:'+(j['confidence']??0.5)+')\x20—\x20'+san((j['description']??'')['slice'](0x0,0x12c))),j['serverId']!=null&&emitExposure('pt:'+j['serverId'],'pattern','inject:T12',{'k_author':j['authorUserId'],'k_problem':j['problemKey'],'k_scope':j['scope']});})),g['length']>0x0&&(i['push']('[DECISIONS]\x20confirmed\x20decisions\x20for\x20this\x20area\x20—\x20do\x20NOT\x20re-propose\x20rejected\x20approaches:'),g['forEach']((j,k)=>{const l=j['rejected']?'\x20(rejected:\x20'+san(j['rejected'])+')':'';i['push'](k+0x1+'.\x20'+san(j['statement']??'')+l+(j['reason']?'\x20—\x20'+san(j['reason']):''));for(const m of premiseLines(j))i['push'](m);}),g['some'](j=>premiseLines(j)['length']>0x0)&&i['push'](PREMISE_RECHECK)),i['push']('Include\x20the\x20relevant\x20items\x20in\x20the\x20delegated\x20task\x20CONTEXT.\x20Reference\x20only\x20—\x20verify\x20against\x20current\x20code.'),i['push']('[/KNOWN-SOLUTIONS-CTX]'),i['join']('\x0a');}export const PREMISE_RECHECK='If\x20a\x20rejected\x20approach\x20comes\x20up\x20again,\x20run\x20each\x20premise\x20check\x20first.\x20If\x20a\x20premise\x20no\x20longer\x20holds,\x20record\x20a\x20new\x20decision\x20with\x20supersedes\x20instead\x20of\x20following\x20the\x20old\x20one.';export function premiseLines(a){if(!Array['isArray'](a['premises']))return[];return a['premises']['filter'](b=>b&&typeof b['text']==='string'&&b['text']['trim']())['slice'](0x0,0x5)['map'](b=>'\x20\x20\x20-\x20premise:\x20'+san(b['text']['trim']()['slice'](0x0,0xc8))+(typeof b['check']==='string'&&b['check']['trim']()?'\x20—\x20check:\x20'+san(b['check']['trim']()['slice'](0x0,0xc8)):''));}function san(a){return a['replace'](/"/g,'\x27')['replace'](/[A-Za-z0-9_\-]{32,}/g,'[REDACTED]');}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a57a from'fs';import*as a57b from'path';import{changedLines}from'./changeset.js';const CALL_RE=/\.(get|post|put|patch|delete|all)\s*\(\s*(['"`])([^'"`]*)\2/gi,DECORATOR_RE=/@(Get|Post|Put|Patch|Delete|All)\s*\(\s*(?:(['"`])([^'"`]*)\2)?\s*\)/g,ROUTE_CHAIN_RE=/\.route\s*\(\s*(['"`])([^'"`]*)\1\s*\)((?:\s*\.\s*(?:get|post|put|patch|delete|all)\s*\()+)/gi;export function extractRoutes(a,b){let c=b;if(c===undefined)try{c=a57a['readFileSync'](a,'utf-8');}catch{return[];}const d=[],e=g=>c['slice'](0x0,g)['split']('\x0a')['length'];let f;CALL_RE['lastIndex']=0x0;while((f=CALL_RE['exec'](c))!==null){if(!f[0x3]['startsWith']('/')&&f[0x3]!=='')continue;d['push']({'method':f[0x1]['toUpperCase'](),'path':f[0x3]||'/','file':a,'line':e(f['index'])});}DECORATOR_RE['lastIndex']=0x0;while((f=DECORATOR_RE['exec'](c))!==null){d['push']({'method':f[0x1]['toUpperCase'](),'path':'/'+(f[0x3]??'')['replace'](/^\/+/,''),'file':a,'line':e(f['index'])});}ROUTE_CHAIN_RE['lastIndex']=0x0;while((f=ROUTE_CHAIN_RE['exec'](c))!==null){const g=f[0x3]['match'](/(get|post|put|patch|delete|all)/gi)??[];for(const h of g)d['push']({'method':h['toUpperCase'](),'path':f[0x2],'file':a,'line':e(f['index'])});}return d['filter'](i=>!i['path']['startsWith']('http'));}const PARAM_SEG=/^(:[\w]+\??|\{[\w]+\}|<[\w:]+>|\*)$/;export function hasLiteralSegment(a){return a['replace'](/^\/+|\/+$/g,'')['split']('/')['filter'](Boolean)['some'](b=>!PARAM_SEG['test'](b));}function routeRegex(a){const b=a['replace'](/^\/+|\/+$/g,'')['split']('/')['filter'](Boolean);if(!hasLiteralSegment(a))return/(?!)/;const c=b['map'](d=>PARAM_SEG['test'](d)?'[^/]+':d['replace'](/[.*+?^${}()|[\]\\]/g,'\x5c$&'))['join']('/');return new RegExp('(^|/)'+c+'/?$');}export function endpointMatchesRoute(a,b,c){if(c['method']!=='ALL'&&c['method']!==a['toUpperCase']())return![];const d=b['split']('?')[0x0];return routeRegex(c['path'])['test'](d);}export function changedRoutes(a,b){const c=new Set();for(const i of a){if(!b['test'](i))continue;if(/\.controller\.[cm]?[jt]s$/['test'](i))try{for(const j of a57a['readdirSync'](a57b['dirname'](i))){if(/\.(route|routes|router)\.[jt]s$|^router\.[jt]s$/['test'](j))c['add'](a57b['join'](a57b['dirname'](i),j));}}catch{}else c['add'](i);}const d=[],e=[];for(const k of c){const l=extractRoutes(k);d['push'](...l);if(a['includes'](k)){const m=new Set(changedLines(k)??[]);e['push'](...l['filter'](n=>m['has'](n['line'])));}}const g=e['length']>0x0?e:d,h=g['filter'](n=>hasLiteralSegment(n['path']));return{'routes':h,'inDiff':e['length']>0x0,'routeFiles':Array['from'](c),'unmatchable':g['length']-h['length']};}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import a58a from'fs-extra';import a58b from'path';import a58c from'os';import{execSync}from'child_process';const BUILD_STATE_FILE=a58b['join'](process.env.ROUTINECODE_KNOWLEDGE_DIR||a58b['join'](a58c['homedir'](),'.routinecode','knowledge'),'build-state.json'),BUILD_STATE_TTL_MS=0x18*0x3c*0x3c*0x3e8,KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR??a58b['join'](process.env.ROUTINECODE_DIR??a58b['join'](a58c['homedir'](),'.routinecode'),'knowledge'),PENDING_SYNC_FILE=a58b['join'](KNOWLEDGE_DIR,'pending-sync.jsonl'),DEADLETTER_SYNC_FILE=a58b['join'](KNOWLEDGE_DIR,'pending-sync.deadletter.jsonl'),LAST_DRAIN_FILE=a58b['join'](KNOWLEDGE_DIR,'.last-drain');function countJsonl(a){try{const b=a58a['readFileSync'](a,'utf-8'),c=b['split']('\x0a')['filter'](e=>e['trim']()!=='');let d=null;for(const e of c){try{const f=JSON['parse'](e),g=f&&typeof f['ts']==='string'?Date['parse'](f['ts']):NaN;if(!Number['isNaN'](g)){if(d===null||g<d)d=g;}}catch{}}return{'count':c['length'],'oldestTs':d};}catch{return{'count':0x0,'oldestTs':null};}}function getKnowledgeSyncHealth(){const a=countJsonl(PENDING_SYNC_FILE),b=countJsonl(DEADLETTER_SYNC_FILE);let c=0x0;a['oldestTs']!==null&&(c=Math['max'](0x0,Math['round']((Date['now']()-a['oldestTs'])/0x5265c00*0xa)/0xa));let d=null;try{const e=a58a['statSync'](LAST_DRAIN_FILE);d=e['mtime']['toISOString']();}catch{}return{'pending':a['count'],'oldestAgeDays':c,'deadletter':b['count'],'lastDrainAt':d};}export function detectBuildCommand(a){const b=[['package.json',''],['Cargo.toml','cargo\x20build'],['go.mod','go\x20build\x20./...'],['build.gradle','./gradlew\x20build'],['build.gradle.kts','./gradlew\x20build'],['pom.xml','mvn\x20compile\x20-q'],['pyproject.toml','python\x20-m\x20compileall\x20src/\x20-q'],['setup.py','python\x20-m\x20compileall\x20.\x20-q'],['Makefile','make\x20build'],['CMakeLists.txt','cmake\x20--build\x20build'],['Package.swift','swift\x20build']];for(const [c,d]of b){if(a58a['pathExistsSync'](a58b['join'](a,c))){if(c==='package.json'){const e=a58a['readJsonSync'](a58b['join'](a,c),{'throws':![]})??{};if(e['scripts']?.['build'])return'npm\x20run\x20build';if(e['scripts']?.['typecheck'])return'npm\x20run\x20typecheck';return null;}return d;}}return null;}export async function buildCheck(a,b,c){const d={'success':!![],'backend':null,'frontend':null,'standalone':null},e=b||a58b['basename'](a);if(c==='all'||c==='backend'){const f=a58b['join'](a,e+'-backend');if(await a58a['pathExists'](f)){const g=detectBuildCommand(f)??'pnpm\x20build';d['backend']=runBuild(f,g);}}if(c==='all'||c==='frontend'){const h=a58b['join'](a,e+'-frontend');if(await a58a['pathExists'](h)){const i=detectBuildCommand(h)??'npm\x20run\x20build';d['frontend']=runBuild(h,i);}}if(!d['backend']&&!d['frontend']){const j=detectBuildCommand(a);j&&(d['standalone']=runBuild(a,j));}return d['success']=(d['backend']===null||d['backend']['success'])&&(d['frontend']===null||d['frontend']['success'])&&(d['standalone']===null||d['standalone']['success']),await persistBuildState(a,d['success'],c),d;}async function persistBuildState(a,b,c){try{const d=await a58a['readJSON'](BUILD_STATE_FILE)['catch'](()=>({}))||{},e=Date['now']();for(const [f,g]of Object['entries'](d)){const h=g?.['timestamp']?Date['parse'](g['timestamp']):0x0;(!h||e-h>BUILD_STATE_TTL_MS)&&delete d[f];}d[a]={'success':b,'target':c,'timestamp':new Date()['toISOString']()},await a58a['ensureDir'](a58b['dirname'](BUILD_STATE_FILE)),await a58a['writeJSON'](BUILD_STATE_FILE,d,{'spaces':0x2});}catch{}}function runBuild(a,b){try{const c=execSync(b,{'cwd':a,'timeout':0x5*0x3c*0x3e8,'encoding':'utf-8','stdio':['ignore','pipe','pipe']});return{'success':!![],'output':(c||'')['slice'](-0x1f4)};}catch(d){const e=(d['stdout']||'')+'\x0a'+(d['stderr']||'');return{'success':![],'output':e['slice'](-0x7d0),'exitCode':d['status']};}}export async function getProjectState(a,b){const c=a58b['join'](a,'.dev-cycle','contracts'),d=b||a58b['basename'](a),e=await a58a['pathExists'](a58b['join'](c,'spec.json')),f=await a58a['pathExists'](a58b['join'](c,'api-contract.json')),g=await a58a['pathExists'](a58b['join'](c,'db-schema.json')),h=a58b['join'](a,d+'-backend'),i=a58b['join'](a,d+'-frontend'),j=await a58a['pathExists'](h),k=await a58a['pathExists'](i);let l=[],m=[];if(e)try{const o=await a58a['readJSON'](a58b['join'](c,'spec.json'));l=(o['entities']||[])['map'](p=>p['name']),m=o['relations']||[];}catch{}let n=0x0;if(f)try{const p=await a58a['readJSON'](a58b['join'](c,'api-contract.json'));n=p['endpoints']?.['length']||0x0;}catch{}return{'projectDir':a,'projectName':d,'spec':e?{'exists':!![],'entities':l,'relations':m}:{'exists':![]},'contracts':{'apiContract':f?{'exists':!![],'endpoints':n}:{'exists':![]},'dbSchema':g?{'exists':!![]}:{'exists':![]}},'backend':{'exists':j,'dir':j?h:null},'frontend':{'exists':k,'dir':k?i:null},'knowledgeSync':getKnowledgeSyncHealth()};}export{getKnowledgeSyncHealth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a59a from'fs';import*as a59b from'path';import{homedir}from'os';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a59b['join'](homedir(),'.routinecode','knowledge'),RULES_PATH=a59b['join'](KNOWLEDGE_DIR,'rules.jsonl');let rulesCache=null,rulesCacheMtime=0x0;function loadRules(){try{if(!consuming)consumeRuleApplications();if(!a59a['existsSync'](RULES_PATH))return[];const a=a59a['statSync'](RULES_PATH)['mtimeMs'];if(rulesCache&&rulesCacheMtime===a)return rulesCache;const b=a59a['readFileSync'](RULES_PATH,'utf-8')['trim']();if(!b)return[];return rulesCache=b['split']('\x0a')['filter'](Boolean)['map'](c=>{try{return JSON['parse'](c);}catch{return null;}})['filter'](c=>c!==null),rulesCacheMtime=a,rulesCache;}catch{return[];}}function normalizeFile(a){return a59b['basename'](a);}function matchCondition(a,b){if(a['trigger_file']&&b['file']){if(normalizeFile(a['trigger_file'])!==normalizeFile(b['file']))return![];}if(a['trigger_pattern']&&b['file']){if(!b['file']['includes'](a['trigger_pattern']))return![];}if(a['error_type']&&b['errorType']){if(a['error_type']!==b['errorType'])return![];}if(a['min_risk']!==undefined&&b['riskScore']!==undefined){if(b['riskScore']<a['min_risk'])return![];}return!![];}export function getMatchingRules(a){const b=loadRules();return b['filter'](c=>matchCondition(c['condition'],a));}export function getVerificationRules(a){const b=getMatchingRules({'file':a});return b['filter'](c=>c['type']==='verification')['map'](c=>c['action']);}export function recordRuleApplication(a,b){const c=loadRules(),d=c['find'](e=>e['id']===a);if(!d)return;d['last_applied']=new Date()['toISOString'](),b?(d['preventions']++,d['confidence']=Math['min'](0x1,d['confidence']+0.05)):d['confidence']=Math['max'](0x0,d['confidence']-0.1),saveRules(c);}export function saveRules(a){try{!a59a['existsSync'](KNOWLEDGE_DIR)&&a59a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]});const b=a['filter'](e=>e['confidence']>=0.3),c=b['map'](e=>JSON['stringify'](e))['join']('\x0a')+'\x0a',d=RULES_PATH+'.tmp';a59a['writeFileSync'](d,c,'utf-8'),a59a['renameSync'](d,RULES_PATH),rulesCache=null;}catch{}}export function getAllRules(){return loadRules();}const RULE_APPLICATIONS_PATH=a59b['join'](KNOWLEDGE_DIR,'rule-applications.jsonl'),RA_LOCK_STALE_MS=0x1388;let consuming=![];function acquireRaLock(){const a=RULE_APPLICATIONS_PATH+'.lock';for(let b=0x0;b<0x32;b++){try{return a59a['closeSync'](a59a['openSync'](a,'wx')),a;}catch{try{const d=a59a['statSync'](a);if(Date['now']()-d['mtimeMs']>RA_LOCK_STALE_MS){a59a['unlinkSync'](a);continue;}}catch{}const c=Date['now']()+0x14;while(Date['now']()<c){}}}return null;}export function consumeRuleApplications(){if(consuming)return;if(!a59a['existsSync'](RULE_APPLICATIONS_PATH))return;consuming=!![];const a=acquireRaLock();if(!a){consuming=![];return;}try{const b=a59a['readFileSync'](RULE_APPLICATIONS_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&&typeof i['ruleId']==='string');if(c['length']===0x0){a59a['writeFileSync'](RULE_APPLICATIONS_PATH,'');return;}let d=[];try{const i=a59a['readFileSync'](RULES_PATH,'utf-8')['trim']();if(i)d=i['split']('\x0a')['filter'](Boolean)['map'](j=>{try{return JSON['parse'](j);}catch{return null;}})['filter'](j=>j!==null);}catch{}const e=new Map(d['map'](j=>[j['id'],j]));let f=0x0;for(const j of c){const k=e['get'](j['ruleId']);if(!k){f++;continue;}k['last_applied']=new Date()['toISOString'](),j['success']?(k['preventions']++,k['confidence']=Math['min'](0x1,k['confidence']+0.05)):k['confidence']=Math['max'](0x0,k['confidence']-0.1);}if(f>0x0)console['error']('[rule-engine]\x20consumed\x20'+c['length']+'\x20applications,\x20'+f+'\x20orphaned\x20(rule\x20deprecated)');const g=d['filter'](l=>l['confidence']>=0.3),h=RULES_PATH+'.tmp';a59a['writeFileSync'](h,g['map'](l=>JSON['stringify'](l))['join']('\x0a')+'\x0a','utf-8'),a59a['renameSync'](h,RULES_PATH),rulesCache=null,a59a['writeFileSync'](RULE_APPLICATIONS_PATH,'');}catch{}finally{releaseRaLock(a),consuming=![];}}function releaseRaLock(a){try{a59a['unlinkSync'](a);}catch{}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as a60a from'fs';import*as a60b from'path';import*as a60c from'crypto';import{homedir}from'os';import{getAllRules,saveRules}from'./rule-engine.js';import{calculateFileRisk}from'./file-risk-scorer.js';import{readJsonl}from'./contracts.generated.js';const KNOWLEDGE_DIR=process.env.ROUTINECODE_KNOWLEDGE_DIR||a60b['join'](homedir(),'.routinecode','knowledge'),CAUSAL_LINKS_PATH=a60b['join'](KNOWLEDGE_DIR,'causal-links.jsonl'),RECOVERY_STATS_PATH=a60b['join'](KNOWLEDGE_DIR,'recovery-stats.jsonl'),EVENTS_PATH=a60b['join'](KNOWLEDGE_DIR,'events.jsonl'),PROMOTE_STATE_PATH=a60b['join'](KNOWLEDGE_DIR,'last-rule-promote.json'),PROMOTE_INTERVAL_MS=0x3c*0x3c*0x3e8;function makeId(){return'rule-'+a60c['randomBytes'](0x4)['toString']('hex');}function basename(a){return a60b['basename'](a);}const MATURITY_RANK={'observation':0x0,'pattern':0x1,'rule':0x2,'constraint':0x3};function ruleKeyOf(a,b){return a+':'+b;}export function promoteRules(){const a=getAllRules(),b=new Map(a['map'](t=>[t['type']+':'+(t['condition']['trigger_file']??t['condition']['error_type']??''),t])),c=[],d=[];let e=0x0,g=0x0;const h=(t,u,v,w,x,y)=>{const z=b['get'](t);if(!z)return'new';if(MATURITY_RANK[u]<MATURITY_RANK[z['maturity']]&&(z['preventions']??0x0)===0x0){const A=z['maturity'];return z['maturity']=u,z['confidence']=Math['min'](z['confidence'],v),z['observations']=w,d['push']('[CORRECTED]\x20'+y+'\x20('+A+'\x20→\x20'+u+',\x20obs='+w+',\x20no\x20preventions)'),e++,'skipped';}if(MATURITY_RANK[u]>MATURITY_RANK[z['maturity']]){const B=z['maturity'];z['maturity']=u,z['confidence']=v,z['observations']=w,z['action']=x,d['push']('[REPROMOTED]\x20'+y+'\x20('+B+'\x20→\x20'+u+',\x20obs='+w+',\x20conf='+v['toFixed'](0x2)+')'),g++;}return'skipped';},i=t=>/co-change/i['test'](t['trigger']?.['changeSummary']??''),j=t=>{const u=t['observedCount']??0x1;return i(t)?u>=0x2?u:0x0:u;},k=(t,u)=>u['every'](i)&&MATURITY_RANK[t]>MATURITY_RANK['pattern']?'pattern':t,l=readJsonl(CAUSAL_LINKS_PATH),m=new Map();for(const t of l){const u=basename(t['trigger']?.['file']??'');if(!u)continue;const v=m['get'](u)??[];v['push'](t),m['set'](u,v);}for(const [w,x]of m){const y=ruleKeyOf('verification',w),z=x['filter'](F=>j(F)>0x0),A=x['reduce']((F,G)=>F+j(G),0x0),B=z['length']>0x0?z['reduce']((F,G)=>F+(G['confidence']??0.5),0x0)/z['length']:0x0;let C;if(A>=0xa&&B>=0.9)C='rule';else{if(A>=0x3&&B>=0.7)C='pattern';else C='observation';}C=k(C,z['length']>0x0?z:x);const D=[...new Set(z['map'](F=>F['effect']?.['file']??'')['filter'](Boolean))];if(C==='observation'){h(y,C,B,A,{'verify_files':D},'verification:\x20'+w);continue;}if(h(y,C,B,A,{'verify_files':D},'verification:\x20'+w)==='skipped')continue;const E={'id':makeId(),'type':'verification','maturity':C,'condition':{'trigger_file':w},'action':{'verify_files':D},'confidence':B,'observations':A,'preventions':0x0,'created_at':new Date()['toISOString']()};c['push'](E),d['push']('[PROMOTED]\x20verification:\x20'+w+'\x20→\x20verify\x20'+D['join'](',')+'\x20('+C+',\x20obs='+A+',\x20conf='+B['toFixed'](0x2)+')');}const n=readJsonl(RECOVERY_STATS_PATH),o=new Map();for(const F of n){const [G,H]=(F['key']??'')['split']('::');if(!G||!H)continue;const I=o['get'](G)??[];let J=I['find'](K=>K['strategy']===H);!J&&(J={'strategy':H,'success':0x0,'total':0x0},I['push'](J));J['total']++;if(F['success'])J['success']++;o['set'](G,I);}for(const [K,L]of o){const M=ruleKeyOf('strategy',K),N=L['reduce']((S,T)=>S+T['total'],0x0);if(N<0xa)continue;const O=L['filter'](S=>S['total']>=0x3)['sort']((S,T)=>T['success']/T['total']-S['success']/S['total']);if(O['length']===0x0)continue;const P=O[0x0]['success']/O[0x0]['total'];if(P<0.8)continue;const Q=P>=0.95?'rule':'pattern';if(h(M,Q,P,N,{'strategy_order':O['map'](S=>S['strategy'])},'strategy:\x20'+K)==='skipped')continue;const R={'id':makeId(),'type':'strategy','maturity':P>=0.95?'rule':'pattern','condition':{'error_type':K},'action':{'strategy_order':O['map'](S=>S['strategy'])},'confidence':P,'observations':N,'preventions':0x0,'created_at':new Date()['toISOString']()};c['push'](R),d['push']('[PROMOTED]\x20strategy:\x20'+K+'\x20→\x20order\x20['+O['map'](S=>S['strategy'])['join'](',')+']\x20(obs='+N+',\x20top='+(P*0x64)['toFixed'](0x0)+'%)');}const p=new Set();for(const [S,T]of m){const U=T['reduce']((V,W)=>V+j(W),0x0);if(U>=0x3)p['add'](S);}const q=readJsonl(EVENTS_PATH);for(const V of q){const W=(V['errorSignature']??'')+'\x20'+(V['rootCause']??'')+'\x20'+(V['fixApproach']??''),X=W['match'](/[\w-]+\.(?:ts|tsx|js|jsx|py|go|java|kt|rs)/);if(X)p['add'](X[0x0]);}for(const Y of p){const Z=ruleKeyOf('agent',Y);let a0;try{const aa=calculateFileRisk(Y);a0=aa['score'];}catch{a0=0x0;}if(a0<0x32)continue;const a1=(m['get'](Y)??[])['reduce']((ab,ac)=>ab+j(ac),0x0),a2=q['filter'](ab=>{const ac=(ab['errorSignature']??'')+'\x20'+(ab['rootCause']??'')+'\x20'+(ab['fixApproach']??'');return ac['includes'](Y);})['length'],a3=a1+a2;if(a3<0x3)continue;const a4=a3>=0xa&&a2>0x0?'rule':'pattern',a5=Math['min'](0x1,0.5+a3*0.05),a6=(m['get'](Y)??[])['map'](ab=>basename(ab['effect']?.['file']??''))['filter'](Boolean),a7=a6['length']>0x0?'known\x20side-effects\x20on\x20'+[...new Set(a6)]['join'](',\x20'):a2+'\x20past\x20errors\x20in\x20this\x20file',a8={'prepend_agent':'reviewer','reviewer_focus':a7};if(h(Z,a4,a5,a3,a8,'agent:\x20'+Y)==='skipped')continue;const a9={'id':makeId(),'type':'agent','maturity':a4,'condition':{'trigger_file':Y,'min_risk':0x32},'action':a8,'confidence':a5,'observations':a3,'preventions':0x0,'created_at':new Date()['toISOString']()};c['push'](a9),d['push']('[PROMOTED]\x20agent:\x20'+Y+'\x20→\x20reviewer\x20first\x20('+a4+',\x20evidence='+a3+',\x20risk='+a0+',\x20focus=\x22'+a7+'\x22)');}for(const ab of a){if(ab['type']!=='agent'||(ab['preventions']??0x0)>0x0)continue;const ac=ab['condition']['trigger_file'];if(!ac||p['has'](ac))continue;ab['confidence']=0.2,d['push']('[RETRACTED]\x20agent:\x20'+ac+'\x20(co-change\x20잡음\x20기반,\x20현재\x20증거\x20미충족)');}const r=Date['now']()-0xb4*0x18*0x3c*0x3c*0x3e8;for(const ad of a){if(ad['confidence']<0.3)d['push']('[DEMOTED]\x20'+ad['type']+':\x20'+(ad['condition']['trigger_file']??ad['condition']['error_type'])+'\x20(confidence='+ad['confidence']['toFixed'](0x2)+')'),e++;else{if(ad['last_applied']){const ae=Date['parse'](ad['last_applied']);ae<r&&(ad['confidence']=0x0,d['push']('[STALE]\x20'+ad['type']+':\x20'+(ad['condition']['trigger_file']??ad['condition']['error_type'])+'\x20(unused\x206+\x20months)'),e++);}}}const s=[...a,...c];return saveRules(s),{'promoted':c['length'],'repromoted':g,'demoted':e,'details':d};}export function promoteRulesIfStale(a=![]){if(!a)try{const c=JSON['parse'](a60a['readFileSync'](PROMOTE_STATE_PATH,'utf-8'))['ts']??0x0;if(Date['now']()-c<PROMOTE_INTERVAL_MS)return{'promoted':0x0,'repromoted':0x0,'demoted':0x0,'details':[],'skipped':'interval'};}catch{}const b=promoteRules();try{a60a['mkdirSync'](KNOWLEDGE_DIR,{'recursive':!![]}),a60a['writeFileSync'](PROMOTE_STATE_PATH,JSON['stringify']({'ts':Date['now']()}));}catch{}return b;}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as a61a from'fs';import*as a61b from'path';import{homedir}from'os';import{spawnSync}from'child_process';export function boardRoot(){return process.env.ROUTINECODE_BOARD_DIR||a61b['join'](homedir(),'.routinecode','board');}export function sessionsDir(){return a61b['join'](boardRoot(),'sessions');}export function sessionPid(){const a=Number(process.env.ROUTINECODE_SESSION_PID);return Number['isInteger'](a)&&a>0x1?a:process['ppid'];}function lstart(a){try{const b=spawnSync('ps',['-o','lstart=','-p',String(a)],{'encoding':'utf-8','timeout':0xbb8}),c=(b['stdout']??'')['trim']();return b['status']===0x0&&c?c:null;}catch{return null;}}export function sessionIdOf(a,b){for(const c of[a61b['join'](sessionsDir(),b+'.json'),...a?[a61b['join'](a,'sessions',b+'.json')]:[]]){try{const e=JSON['parse'](a61a['readFileSync'](c,'utf-8'));if(e&&typeof e['session']==='string'&&e['session']){if(typeof e['start']==='string'&&e['start']){const f=lstart(b);if(f!==null&&f!==e['start'])continue;}return e['session']['slice'](0x0,0xc);}}catch{}}return'pid-'+b;}export function currentSessionId(){const a=sessionIdOf(null,sessionPid());return a['startsWith']('pid-')?null:a;}
|