@vpxa/aikit 0.1.73 → 0.1.75
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/package.json +9 -1
- package/packages/cli/dist/index.js +2 -2
- package/packages/cli/dist/{init-D_OGLUN1.js → init-CuRXmyD9.js} +4 -4
- package/packages/cli/dist/scaffold-WMQ2uQ48.js +2 -0
- package/packages/cli/dist/{templates-DJ7EC5vw.js → templates-ArdAVWoY.js} +13 -3
- package/packages/cli/dist/user-vbJwa7x2.js +5 -0
- package/packages/dashboard/dist/assets/index-C6D-PCp0.js.map +1 -1
- package/packages/flows/dist/index.d.ts +29 -0
- package/packages/flows/dist/index.js +1 -1
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-B9Mx1aK-.js → server-CVhVH5cT.js} +127 -127
- package/packages/tools/dist/index.d.ts +19 -1
- package/packages/tools/dist/index.js +39 -39
- package/scaffold/dist/adapters/claude-code.mjs +4 -0
- package/scaffold/dist/adapters/copilot.mjs +75 -0
- package/scaffold/dist/adapters/flows.mjs +1 -0
- package/scaffold/dist/adapters/skills.mjs +1 -0
- package/scaffold/dist/compiled/flows-data.mjs +1429 -0
- package/scaffold/dist/compiled/skills-data.mjs +9951 -0
- package/scaffold/dist/definitions/agents.mjs +9 -0
- package/scaffold/{definitions → dist/definitions}/bodies.mjs +6 -229
- package/scaffold/dist/definitions/exclusions.mjs +1 -0
- package/scaffold/dist/definitions/hooks.mjs +1 -0
- package/scaffold/dist/definitions/models.mjs +1 -0
- package/scaffold/dist/definitions/plugins.mjs +1 -0
- package/scaffold/{definitions → dist/definitions}/prompts.mjs +9 -149
- package/scaffold/{definitions → dist/definitions}/protocols.mjs +9 -37
- package/scaffold/dist/definitions/tools.mjs +1 -0
- package/packages/cli/dist/scaffold-CJwkHf-q.js +0 -2
- package/packages/cli/dist/user-BEmVW8Tp.js +0 -5
- package/scaffold/adapters/claude-code.mjs +0 -73
- package/scaffold/adapters/copilot.mjs +0 -292
- package/scaffold/definitions/agents.mjs +0 -266
- package/scaffold/definitions/hooks.mjs +0 -43
- package/scaffold/definitions/models.mjs +0 -84
- package/scaffold/definitions/plugins.mjs +0 -147
- package/scaffold/definitions/tools.mjs +0 -250
- package/scaffold/flows/_epilogue/steps/docs-sync/README.md +0 -120
- package/scaffold/flows/aikit-advanced/README.md +0 -70
- package/scaffold/flows/aikit-advanced/flow.json +0 -69
- package/scaffold/flows/aikit-advanced/steps/design/README.md +0 -178
- package/scaffold/flows/aikit-advanced/steps/execute/README.md +0 -145
- package/scaffold/flows/aikit-advanced/steps/plan/README.md +0 -122
- package/scaffold/flows/aikit-advanced/steps/spec/README.md +0 -121
- package/scaffold/flows/aikit-advanced/steps/task/README.md +0 -119
- package/scaffold/flows/aikit-advanced/steps/verify/README.md +0 -145
- package/scaffold/flows/aikit-basic/README.md +0 -51
- package/scaffold/flows/aikit-basic/flow.json +0 -45
- package/scaffold/flows/aikit-basic/steps/assess/README.md +0 -109
- package/scaffold/flows/aikit-basic/steps/design/README.md +0 -116
- package/scaffold/flows/aikit-basic/steps/implement/README.md +0 -131
- package/scaffold/flows/aikit-basic/steps/verify/README.md +0 -123
- package/scaffold/general/agents/Architect-Reviewer-Alpha.agent.md +0 -132
- package/scaffold/general/agents/Architect-Reviewer-Beta.agent.md +0 -132
- package/scaffold/general/agents/Code-Reviewer-Alpha.agent.md +0 -112
- package/scaffold/general/agents/Code-Reviewer-Beta.agent.md +0 -112
- package/scaffold/general/agents/Debugger.agent.md +0 -412
- package/scaffold/general/agents/Documenter.agent.md +0 -468
- package/scaffold/general/agents/Explorer.agent.md +0 -76
- package/scaffold/general/agents/Frontend.agent.md +0 -440
- package/scaffold/general/agents/Implementer.agent.md +0 -425
- package/scaffold/general/agents/Orchestrator.agent.md +0 -452
- package/scaffold/general/agents/Planner.agent.md +0 -481
- package/scaffold/general/agents/README.md +0 -57
- package/scaffold/general/agents/Refactor.agent.md +0 -435
- package/scaffold/general/agents/Researcher-Alpha.agent.md +0 -151
- package/scaffold/general/agents/Researcher-Beta.agent.md +0 -152
- package/scaffold/general/agents/Researcher-Delta.agent.md +0 -153
- package/scaffold/general/agents/Researcher-Gamma.agent.md +0 -152
- package/scaffold/general/agents/Security.agent.md +0 -433
- package/scaffold/general/agents/_shared/architect-reviewer-base.md +0 -104
- package/scaffold/general/agents/_shared/code-agent-base.md +0 -366
- package/scaffold/general/agents/_shared/code-reviewer-base.md +0 -87
- package/scaffold/general/agents/_shared/decision-protocol.md +0 -27
- package/scaffold/general/agents/_shared/forge-protocol.md +0 -90
- package/scaffold/general/agents/_shared/researcher-base.md +0 -114
- package/scaffold/general/agents/templates/adr-template.md +0 -28
- package/scaffold/general/agents/templates/execution-state.md +0 -26
- package/scaffold/general/prompts/aikit-ask.prompt.md +0 -13
- package/scaffold/general/prompts/aikit-debug.prompt.md +0 -15
- package/scaffold/general/prompts/aikit-design.prompt.md +0 -15
- package/scaffold/general/prompts/aikit-flow-add.prompt.md +0 -84
- package/scaffold/general/prompts/aikit-flow-create.prompt.md +0 -80
- package/scaffold/general/prompts/aikit-flow-manage.prompt.md +0 -24
- package/scaffold/general/prompts/aikit-implement.prompt.md +0 -17
- package/scaffold/general/prompts/aikit-plan.prompt.md +0 -15
- package/scaffold/general/prompts/aikit-review.prompt.md +0 -24
- package/scaffold/general/skills/adr-skill/SKILL.md +0 -335
- package/scaffold/general/skills/adr-skill/assets/templates/adr-madr.md +0 -89
- package/scaffold/general/skills/adr-skill/assets/templates/adr-readme.md +0 -20
- package/scaffold/general/skills/adr-skill/assets/templates/adr-simple.md +0 -46
- package/scaffold/general/skills/adr-skill/references/adr-conventions.md +0 -95
- package/scaffold/general/skills/adr-skill/references/examples.md +0 -193
- package/scaffold/general/skills/adr-skill/references/review-checklist.md +0 -77
- package/scaffold/general/skills/adr-skill/references/template-variants.md +0 -52
- package/scaffold/general/skills/adr-skill/scripts/bootstrap_adr.js +0 -259
- package/scaffold/general/skills/adr-skill/scripts/new_adr.js +0 -391
- package/scaffold/general/skills/adr-skill/scripts/set_adr_status.js +0 -169
- package/scaffold/general/skills/aikit/SKILL.md +0 -754
- package/scaffold/general/skills/brainstorming/SKILL.md +0 -265
- package/scaffold/general/skills/brainstorming/spec-document-reviewer-prompt.md +0 -49
- package/scaffold/general/skills/c4-architecture/SKILL.md +0 -389
- package/scaffold/general/skills/c4-architecture/references/advanced-patterns.md +0 -552
- package/scaffold/general/skills/c4-architecture/references/c4-syntax.md +0 -510
- package/scaffold/general/skills/c4-architecture/references/common-mistakes.md +0 -437
- package/scaffold/general/skills/c4-architecture/references/html-design-system.md +0 -337
- package/scaffold/general/skills/c4-architecture/references/html-template.html +0 -627
- package/scaffold/general/skills/docs/SKILL.md +0 -553
- package/scaffold/general/skills/docs/references/diataxis-anti-patterns.md +0 -147
- package/scaffold/general/skills/docs/references/diataxis-compass.md +0 -123
- package/scaffold/general/skills/docs/references/diataxis-quadrants.md +0 -192
- package/scaffold/general/skills/docs/references/diataxis-quality.md +0 -76
- package/scaffold/general/skills/docs/references/diataxis-templates.md +0 -120
- package/scaffold/general/skills/docs/references/flow-artifacts-guide.md +0 -70
- package/scaffold/general/skills/docs/references/project-knowledge-gotchas.md +0 -32
- package/scaffold/general/skills/docs/references/project-knowledge-templates.md +0 -281
- package/scaffold/general/skills/docs/references/project-knowledge-workflow.md +0 -80
- package/scaffold/general/skills/frontend-design/SKILL.md +0 -237
- package/scaffold/general/skills/lesson-learned/SKILL.md +0 -113
- package/scaffold/general/skills/lesson-learned/references/anti-patterns.md +0 -55
- package/scaffold/general/skills/lesson-learned/references/se-principles.md +0 -109
- package/scaffold/general/skills/multi-agents-development/SKILL.md +0 -448
- package/scaffold/general/skills/multi-agents-development/architecture-review-prompt.md +0 -81
- package/scaffold/general/skills/multi-agents-development/code-quality-review-prompt.md +0 -91
- package/scaffold/general/skills/multi-agents-development/implementer-prompt.md +0 -93
- package/scaffold/general/skills/multi-agents-development/parallel-dispatch-example.md +0 -167
- package/scaffold/general/skills/multi-agents-development/spec-review-prompt.md +0 -81
- package/scaffold/general/skills/present/SKILL.md +0 -616
- package/scaffold/general/skills/react/SKILL.md +0 -309
- package/scaffold/general/skills/repo-access/SKILL.md +0 -178
- package/scaffold/general/skills/repo-access/references/error-patterns.md +0 -116
- package/scaffold/general/skills/repo-access/references/platform-matrix.md +0 -142
- package/scaffold/general/skills/requirements-clarity/SKILL.md +0 -333
- package/scaffold/general/skills/session-handoff/SKILL.md +0 -199
- package/scaffold/general/skills/session-handoff/references/handoff-template.md +0 -139
- package/scaffold/general/skills/session-handoff/references/resume-checklist.md +0 -80
- package/scaffold/general/skills/session-handoff/scripts/check_staleness.js +0 -269
- package/scaffold/general/skills/session-handoff/scripts/create_handoff.js +0 -299
- package/scaffold/general/skills/session-handoff/scripts/list_handoffs.js +0 -113
- package/scaffold/general/skills/session-handoff/scripts/validate_handoff.js +0 -241
- package/scaffold/general/skills/typescript/SKILL.md +0 -405
- package/scaffold/generate.mjs +0 -82
|
@@ -38,34 +38,34 @@ import{DependencyAnalyzer as e,DiagramGenerator as t,EntryPointAnalyzer as n,Pat
|
|
|
38
38
|
|
|
39
39
|
`)})}return{text:hn($t(p.map(e=>{let t=c.find(t=>t.id===e.id),n=t?Math.max(0,...t.segments.map(e=>e.score)):0;return{...e,maxScore:n}}))),fields:s,sourceStats:f,totalOriginalChars:l,totalCompressedChars:m,ratio:gn(l,m)}}function vn(){return S(B(process.cwd()),`logs`)}function yn(e={}){let{days:t=7,level:n,component:r,limit:i=50}=e,a=vn(),o=new Date,s=new Date(o.getTime()-t*864e5).toISOString().slice(0,10),c=o.toISOString().slice(0,10),l;try{l=F(a).filter(e=>e.endsWith(`.jsonl`)&&e.slice(0,10)>=s).sort()}catch{return{totalEntries:0,groups:[],recent:[],dateRange:{from:s,to:c}}}let u=[];for(let e of l)try{let t=P(S(a,e),`utf-8`);for(let e of t.trim().split(`
|
|
40
40
|
`))if(e)try{let t=JSON.parse(e);if(n&&t.level!==n||r&&t.component!==r)continue;u.push(t)}catch{}}catch{}let d=new Map;for(let e of u){let t=`${e.component}::${e.msg}`,n=d.get(t);n?(n.count++,e.ts<n.firstSeen&&(n.firstSeen=e.ts),e.ts>n.lastSeen&&(n.lastSeen=e.ts)):d.set(t,{component:e.component,msg:e.msg,level:e.level,count:1,firstSeen:e.ts,lastSeen:e.ts})}let f=[...d.values()].sort((e,t)=>t.count-e.count),p=u.slice(-i);return{totalEntries:u.length,groups:f,recent:p,dateRange:{from:l.length>0?l[0].slice(0,10):s,to:c}}}function bn(e){let{operation:t,input:n}=e,r;switch(t){case`base64_encode`:r=Buffer.from(n).toString(`base64`);break;case`base64_decode`:r=Buffer.from(n,`base64`).toString(`utf8`);break;case`url_encode`:r=encodeURIComponent(n);break;case`url_decode`:r=decodeURIComponent(n);break;case`sha256`:r=V(`sha256`).update(n).digest(`hex`);break;case`md5`:r=V(`md5`).update(n).digest(`hex`);break;case`jwt_decode`:{let e=n.split(`.`);if(e.length!==3)throw Error(`Invalid JWT: expected 3 dot-separated parts`);let t,i;try{t=JSON.parse(Buffer.from(e[0],`base64url`).toString()),i=JSON.parse(Buffer.from(e[1],`base64url`).toString())}catch{throw Error(`Invalid JWT: header or payload is not valid JSON`)}r=JSON.stringify({header:t,payload:i},null,2);break}case`hex_encode`:r=Buffer.from(n).toString(`hex`);break;case`hex_decode`:r=Buffer.from(n,`hex`).toString(`utf8`);break;default:throw Error(`Unknown operation: ${t}`)}return{output:r,operation:t}}const xn=[/key/i,/secret/i,/token/i,/password/i,/passwd/i,/credential/i,/private/i,/certificate/i];function Sn(e={}){let{includeEnv:t=!1,filterEnv:n,showSensitive:r=!1}=e,i={system:{platform:pe(),arch:le(),release:me(),hostname:fe(),type:ge(),cpus:ue().length,memoryTotalGb:Math.round(he()/1024**3*10)/10,memoryFreeGb:Math.round(de()/1024**3*10)/10},runtime:{node:process.versions.node,v8:process.versions.v8},cwd:process.cwd()};if(t){let e={};for(let[t,i]of Object.entries(process.env))i&&(n&&!t.toLowerCase().includes(n.toLowerCase())||(!r&&xn.some(e=>e.test(t))?e[t]=`[REDACTED]`:e[t]=i));i.env=e}return i}function Cn(e){let{code:t,lang:n=`js`,timeout:r=5e3}=e,i=Math.min(Math.max(r,100),1e4),a=Date.now();try{let e=n===`ts`?Tn(t):t,r=[],o={console:{log:(...e)=>r.push(e.map(String).join(` `)),error:(...e)=>r.push(`[error] ${e.map(String).join(` `)}`),warn:(...e)=>r.push(`[warn] ${e.map(String).join(` `)}`)},setTimeout:void 0,setInterval:void 0,setImmediate:void 0,fetch:void 0,process:void 0,require:void 0,JSON,Math,Date,Array,Object,String,Number,Boolean,Map,Set,RegExp,Error,Promise,parseInt,parseFloat,isNaN,isFinite},s=_e.createContext(o,{codeGeneration:{strings:!1,wasm:!1}}),c=_e.runInContext(e,s,{timeout:i});return{success:!0,output:r.length>0?r.join(`
|
|
41
|
-
`)+(c===void 0?``:`\n→ ${wn(c)}`):c===void 0?`(no output)`:wn(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:e.message,durationMs:Date.now()-a}}}function wn(e){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`object`)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}function Tn(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}function En(e){return w(B(e??process.cwd()),`evidence-maps.json`)}function
|
|
42
|
-
`)}function
|
|
43
|
-
`).length,o=U(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=o,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:o,hitCount:a.hitCount,changed:!0}}let o=await p(n,`utf-8`),s=
|
|
44
|
-
`).length,l=U(o);if(this.cache.set(n,{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(w(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function
|
|
45
|
-
`),a=t.split(`.`).pop()??``,o=b(t);return D.get()&&E.has(o)?
|
|
41
|
+
`)+(c===void 0?``:`\n→ ${wn(c)}`):c===void 0?`(no output)`:wn(c),durationMs:Date.now()-a}}catch(e){return{success:!1,output:``,error:e.message,durationMs:Date.now()-a}}}function wn(e){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`object`)try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}function Tn(e){return e.replace(/^\s*import\s+type\s+.*?;\s*$/gm,``).replace(/^\s*(?:export\s+)?interface\s+\w+[^{]*\{[\s\S]*?^\s*}\s*$/gm,``).replace(/^\s*(?:export\s+)?type\s+\w+\s*=.*?;\s*$/gm,``).replace(/([,(]\s*[A-Za-z_$][\w$]*)\s*:\s*[^,)=\n]+/g,`$1`).replace(/\)\s*:\s*[^={\n]+(?=\s*(?:=>|\{))/g,`)`).replace(/\s+as\s+[A-Za-z_$][\w$<>,[\]|&\s.]*/g,``).replace(/<(?:[A-Za-z_$][\w$]*\s*,?\s*)+>(?=\s*\()/g,``)}const En={maxRetries:3,timeoutAction:`manual`};function Dn(e){let t=e?.maxRetries;return{maxRetries:typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.trunc(t):En.maxRetries,timeoutAction:e?.timeoutAction??En.timeoutAction}}function On(e){return{...e,gateConfig:Dn(e.gateConfig),gateAttempts:typeof e.gateAttempts==`number`&&Number.isFinite(e.gateAttempts)?Math.max(0,Math.trunc(e.gateAttempts)):0}}function kn(e){return w(B(e??process.cwd()),`evidence-maps.json`)}function An(e){let t=kn(e);if(!M(t))return{};try{let e=P(t,`utf-8`),n=JSON.parse(e);return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,On(t)]))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function jn(e,t){let n=kn(t),r=y(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Mn(e,t){let n=An(t),r=n[e];if(!r)throw Error(`Evidence map not found: ${e}`);return{maps:n,state:r}}function Nn(e){return e.reduce((e,t)=>Math.max(e,t.id),0)+1}function Pn(e){let t=e.trim();if(!t)throw Error(`Claim is required`);if(/\r?\n/.test(t))throw Error(`Claim must be a single line`);return t}function Fn(e){return(e??``).replace(/\r?\n/g,` `).replace(/\|/g,`\\|`)}function In(e){let t=[`| # | Claim | Status | Receipt | Critical | Type | Safety |`,`|---|-------|--------|---------|----------|------|--------|`];for(let n of e.entries)t.push(`| ${n.id} | ${Fn(n.claim)} | ${n.status} | ${Fn(n.receipt)} | ${n.criticalPath?`yes`:`no`} | ${Fn(n.unknownType)} | ${Fn(n.safetyGate)} |`);return t.join(`
|
|
42
|
+
`)}function Ln(e){return{total:e.length,verified:e.filter(e=>e.status===`V`).length,assumed:e.filter(e=>e.status===`A`).length,unresolved:e.filter(e=>e.status===`U`).length}}function Rn(e){let t=[];for(let n of e.entries)n.status===`V`&&n.receipt.trim()===``&&t.push(`V entry without receipt`),n.status===`A`&&e.tier===`critical`&&n.unknownType===`contract`&&t.push(`Assumed contract at Critical tier — should be Verified`);return t}function zn(e){return`Gate escalation annotation: unresolved entries remain -> ${e.filter(e=>e.status===`U`).map(e=>`#${e.id} ${e.claim}`).join(`; `)}`}function Bn(e){let t=e.entries.filter(e=>e.status===`U`),n=e.entries.filter(e=>e.status===`A`),r=[];return t.length>0&&r.push(`Unresolved: ${t.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),n.length>0&&r.push(`Assumed: ${n.map(e=>`#${e.id} ${e.claim}`).join(`; `)}`),r.length>0?r.join(` | `):void 0}function Vn(e){let t=[],n=e.entries.filter(e=>e.status===`V`&&!e.receipt.trim());n.length>0&&t.push(`Provenance: ${n.length} verified claim(s) lack receipts`);let r=e.entries.filter(e=>e.safetyGate===`commitment`&&e.status!==`V`);r.length>0&&t.push(`Commitment: ${r.length} commitment(s) not verified`);let i=e.entries.some(e=>e.safetyGate===`coverage`&&e.status===`U`);return i&&t.push(`Coverage: unresolved coverage entries remain`),{provenance:n.length>0?`fail`:`pass`,commitment:r.length>0?`fail`:`pass`,coverage:i?`fail`:`pass`,failures:t}}function Hn(e,t,n){let r=e.entries.filter(e=>e.criticalPath&&e.status===`U`),i=Rn(e),a=Ln(e.entries),o=r.find(e=>e.unknownType===`contract`),s=Math.max(t.maxRetries-n,0),c=s>0?`iterate`:t.timeoutAction,l=Bn(e);if(o)return{verdict:`HARD_BLOCK`,action:c,retriesRemaining:s,summary:l,decision:`HARD_BLOCK`,reason:`Unresolved contract unknown on critical path`,unresolvedCritical:r,warnings:i,stats:a};if(r.length>0)return{verdict:`HOLD`,action:c,retriesRemaining:s,summary:l,decision:`HOLD`,reason:s>0?`Unresolved critical-path unknown — retry available`:`Unresolved critical-path unknown — retries exhausted`,unresolvedCritical:r,warnings:i,stats:a,...s===0?{annotation:zn(e.entries)}:{}};let u=Un(e,i,a),d=u.decision===`HOLD`?`HOLD`:`YIELD`;return{verdict:d,...d===`HOLD`?{action:c,retriesRemaining:s,summary:l}:{},decision:u.decision??`YIELD`,reason:u.reason??`All critical-path claims satisfy gate rules`,unresolvedCritical:[],warnings:u.warnings??i,stats:a,...`safetyGates`in u?{safetyGates:u.safetyGates}:{}}}function Un(e,t,n){if(!e.entries.some(e=>e.safetyGate)||e.tier===`floor`)return{};let r=Vn(e);return r.failures.length>0?{safetyGates:r,decision:`HOLD`,reason:`Safety gate failure: ${r.failures.join(`; `)}`,warnings:[...t,...r.failures]}:{safetyGates:r}}function Wn(e,t){switch(e.action){case`create`:{let n=An(t),r=new Date().toISOString(),i={taskId:e.taskId,tier:e.tier,entries:[],gateConfig:{...En},gateAttempts:0,createdAt:r,updatedAt:r};return n[e.taskId]=i,jn(n,t),{state:i,formattedMap:In(i)}}case`add`:{let{maps:n,state:r}=Mn(e.taskId,t),i={id:Nn(r.entries),claim:Pn(e.claim),status:e.status,receipt:e.receipt,criticalPath:e.criticalPath??!1,unknownType:e.unknownType,safetyGate:e.safetyGate};return r.entries.push(i),r.updatedAt=new Date().toISOString(),n[e.taskId]=r,jn(n,t),{state:r,entry:i,formattedMap:In(r)}}case`update`:{let{maps:n,state:r}=Mn(e.taskId,t),i=r.entries.find(t=>t.id===e.id);if(!i)throw Error(`Evidence entry not found: ${e.id}`);return i.status=e.status,i.receipt=e.receipt,r.updatedAt=new Date().toISOString(),n[e.taskId]=r,jn(n,t),{state:r,entry:i,formattedMap:In(r)}}case`get`:{let{state:n}=Mn(e.taskId,t);return{state:n,formattedMap:In(n)}}case`gate`:{let{maps:n,state:r}=Mn(e.taskId,t),i=Dn({...r.gateConfig,...e.maxRetries===void 0?{}:{maxRetries:e.maxRetries},...e.timeoutAction===void 0?{}:{timeoutAction:e.timeoutAction}}),a=e.retryCount===void 0?r.gateAttempts:Math.max(r.gateAttempts,Math.max(0,Math.trunc(e.retryCount))),o={...r,gateConfig:i},s=Hn(o,i,r.entries.some(e=>e.status===`U`||e.status===`A`)?a+1:0),c={...o,gateConfig:i,gateAttempts:s.verdict===`YIELD`?0:a+1,updatedAt:new Date().toISOString()};return n[e.taskId]=c,jn(n,t),{state:c,gate:Hn(c,i,c.gateAttempts),formattedMap:In(c)}}case`list`:return{states:Object.values(An(t)).sort((e,t)=>e.createdAt.localeCompare(t.createdAt))};case`delete`:{let n=An(t);return e.taskId in n?(delete n[e.taskId],jn(n,t),{deleted:!0}):{deleted:!1}}}}function Gn(e,t,n){let r=[];for(let i of t){let t=Wn({action:`add`,taskId:e,claim:`Test failure: ${i}`,status:`U`,receipt:``,criticalPath:!0},n);t.entry&&r.push(t.entry)}return r}var Kn=class e{cache=new Map;totalReads=0;cacheHits=0;static MAX_ENTRIES=500;async get(t){let n=w(t);this.totalReads++;let r=await g(n);if(r.isDirectory())throw Error(`Path is a directory: ${t}. Expected a file path, not a directory. Use analyze_structure or find to explore directories.`);let i=r.mtimeMs,a=this.cache.get(n);if(a){if(a.mtimeMs===i)return this.cacheHits++,a.hitCount++,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let e=await p(n,`utf-8`),t=qn(e);if(t===a.hash)return this.cacheHits++,a.hitCount++,a.mtimeMs=i,{content:a.content,hash:a.hash,lines:a.lines,estimatedTokens:a.estimatedTokens,hitCount:a.hitCount,changed:!1};let r=e.split(`
|
|
43
|
+
`).length,o=U(e);return a.content=e,a.hash=t,a.lines=r,a.estimatedTokens=o,a.hitCount++,a.mtimeMs=i,{content:e,hash:t,lines:r,estimatedTokens:o,hitCount:a.hitCount,changed:!0}}let o=await p(n,`utf-8`),s=qn(o),c=o.split(`
|
|
44
|
+
`).length,l=U(o);if(this.cache.set(n,{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,mtimeMs:i}),this.cache.size>e.MAX_ENTRIES){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}return{content:o,hash:s,lines:c,estimatedTokens:l,hitCount:1,changed:!0}}invalidate(e){return this.cache.delete(w(e))}clear(){let e=this.cache.size;return this.cache.clear(),e}stats(){return{totalReads:this.totalReads,cacheHits:this.cacheHits,filesTracked:this.cache.size}}};function qn(e){return V(`sha256`).update(e).digest(`hex`)}async function Jn(e){let{path:t,previewLines:n=3}=e;if(!e.content){let e;try{e=await g(t)}catch(e){let n=e.code;throw n===`ENOENT`?Error(`File not found: ${t}. Check the path and try again.`):n===`EACCES`||n===`EPERM`?Error(`Permission denied reading ${t}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${t}. file_summary requires a file path, not a directory. Use analyze_structure or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). file_summary supports files up to 10MB. Use search or compact with a query instead.`)}let r=e.content??await p(t,`utf-8`),i=r.split(`
|
|
45
|
+
`),a=t.split(`.`).pop()??``,o=b(t);return D.get()&&E.has(o)?Yn(t,r,i,a,o):Xn(t,r,i,a)}async function Yn(e,t,n,r,i){let[a,o,s]=await Promise.all([k(t,i,e),O(t,i,e),ee(t,i,e).catch(()=>[])]),c=o.map(e=>`import ${e.specifiers.length>0?`{ ${e.specifiers.join(`, `)} }`:`*`} from '${e.source}'`),l=[],u=[],d=[],f=[],p=[];for(let e of a)switch(e.exported&&l.push(e.name),e.kind){case`function`:case`method`:u.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`class`:d.push({name:e.name,line:e.line,exported:e.exported,signature:e.signature});break;case`interface`:f.push({name:e.name,line:e.line,exported:e.exported});break;case`type`:p.push({name:e.name,line:e.line,exported:e.exported});break}let m=o.map(e=>({source:e.source,specifiers:e.specifiers,isExternal:e.isExternal})),h=s.map(e=>({caller:e.callerName,callee:e.calleeName,line:e.line}));return{path:e,lines:n.length,language:Zn(r),imports:c,exports:l,functions:u,classes:d,interfaces:f,types:p,importDetails:m,callEdges:h.length>0?h:void 0,estimatedTokens:Math.ceil(t.length/4)}}function Xn(e,t,n,r){let i=[],a=[],o=[],s=[],c=[],l=[];for(let e=0;e<n.length;e+=1){let t=n[e],r=e+1;if(/^import\s+.+/.test(t)){i.push(t.trim());continue}let u=t.match(/^export\s+(?:async\s+)?function\s+(\w+)/);if(u){o.push({name:u[1],line:r,exported:!0}),a.push(u[1]);continue}let d=t.match(/^(?:async\s+)?function\s+(\w+)/);if(d){o.push({name:d[1],line:r,exported:!1});continue}let f=t.match(/^(export\s+)?const\s+(\w+)\s*=.*(?:=>|\bfunction\b)/);if(f){let e=!!f[1];o.push({name:f[2],line:r,exported:e}),e&&a.push(f[2]);continue}let p=t.match(/^export\s+const\s+(\w+)\s*=/);if(p){a.push(p[1]);continue}let m=t.match(/^(export\s+)?(?:abstract\s+)?class\s+(\w+)/);if(m){let e=!!m[1];s.push({name:m[2],line:r,exported:e}),e&&a.push(m[2]);continue}let h=t.match(/^(export\s+)?interface\s+(\w+)/);if(h){let e=!!h[1];c.push({name:h[2],line:r,exported:e}),e&&a.push(h[2]);continue}let g=t.match(/^(export\s+)?type\s+(\w+)/);if(g){let e=!!g[1];l.push({name:g[2],line:r,exported:e}),e&&a.push(g[2]);continue}let _=t.match(/^export\s+\{(.+)\}/);if(_){let e=_[1].split(`,`).map(e=>e.trim().split(/\s+as\s+/).pop()?.trim()??``).filter(Boolean);a.push(...e)}}return{path:e,lines:n.length,language:Zn(r),imports:i,exports:a,functions:o,classes:s,interfaces:c,types:l,estimatedTokens:Math.ceil(t.length/4)}}function Zn(e){return{ts:`typescript`,tsx:`typescript-jsx`,js:`javascript`,jsx:`javascript-jsx`,py:`python`,rs:`rust`,go:`go`,java:`java`,rb:`ruby`,md:`markdown`,json:`json`,yaml:`yaml`,yml:`yaml`,css:`css`,html:`html`,sh:`shell`,bash:`shell`}[e]??e}async function Qn(e,t,n){let{query:r,glob:i,pattern:a,limit:o=10,contentType:s,cwd:c=process.cwd()}=n,l=[],u=[],d=new Set,f=[];if(r){l.push(`vector`);let n=await e.embed(r),i={limit:o,contentType:s},a=await t.search(n,i);for(let e of a){let t=`${e.record.sourcePath}:${e.record.startLine}`;d.has(t)||(d.add(t),u.push({path:e.record.sourcePath,source:`vector`,score:e.score,lineRange:{start:e.record.startLine,end:e.record.endLine},preview:e.record.content.slice(0,200)}))}}if(r){l.push(`keyword`);try{let e=await t.ftsSearch(r,{limit:o,contentType:s});for(let t of e){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`keyword`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}catch(e){f.push({strategy:`keyword`,reason:e instanceof Error?e.message:String(e)})}}if(i){l.push(`glob`);try{let{globSync:e}=await import(`node:fs`),t=e(i,{cwd:c,withFileTypes:!1}),n=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state,z.data]),r=t.filter(e=>!e.replace(/\\/g,`/`).split(`/`).some(e=>n.has(e)));for(let e of r.slice(0,o)){let t=`glob:${e}`;d.has(t)||(d.add(t),u.push({path:e,source:`glob`,score:1}))}}catch(e){f.push({strategy:`glob`,reason:e instanceof Error?e.message:String(e)})}}if(a){l.push(`pattern`);try{let e=$n(a),n=e?er(a):a,r=new RegExp(n,`i`),i=e?tr(a):a,c=await t.ftsSearch(i,{limit:o*2,contentType:s});for(let t of c){let n=e?t.record.sourcePath:t.record.content;if(r.test(n)){let e=`${t.record.sourcePath}:${t.record.startLine}`;d.has(e)||(d.add(e),u.push({path:t.record.sourcePath,source:`pattern`,score:t.score,lineRange:{start:t.record.startLine,end:t.record.endLine},preview:t.record.content.slice(0,200)}))}}}catch(e){f.push({strategy:`pattern`,reason:e instanceof Error?e.message:String(e)})}}return u.sort((e,t)=>t.score-e.score),{results:u.slice(0,o),strategies:l,totalFound:u.length,...f.length>0&&{failedStrategies:f}}}function $n(e){return/\*\*|^[*?]|\/\*|^\*\./.test(e)}function er(e){let t=`\0DS\0`,n=`\0SS\0`,r=e.replace(/\*\*/g,t).replace(/\*/g,n);return r=r.replace(/[.+^${}()|[\]\\]/g,`\\$&`),r=r.replace(/\?/g,`.`),r=r.replace(new RegExp(t.replace(/\0/g,`\\0`),`g`),`.*`),r=r.replace(new RegExp(n.replace(/\0/g,`\\0`),`g`),`[^/]*`),r}function tr(e){return e.replace(/\*+/g,` `).replace(/[/\\]/g,` `).trim().split(/\s+/).filter(e=>e.length>1).join(` `)||e}async function nr(e,t,n){let{query:r,limit:i=5,contentType:a}=n,o=`usage example of ${r}`,s=await e.embed(o),c=await t.search(s,{limit:i*3,contentType:a}),l=RegExp(`\\b${H(r)}\\b`,`i`),u=c.filter(e=>l.test(e.record.content));return{query:r,examples:u.map(e=>{let t=e.record.content,n=/export\s+(?:async\s+)?(?:function|class|const|interface|type)\s/.test(t),r=/^\s*import\s/m.test(t),i=/(?:^|[\\/])(test|tests|__tests__|spec)(?:[\\/]|$)/i.test(e.record.sourcePath)||/\.(test|spec)\.[jt]sx?$/i.test(e.record.sourcePath),a=0;n||(a+=.1),r||(a+=.05),i&&(a+=.05);let o=t.split(`
|
|
46
46
|
`),s=o.findIndex(e=>l.test(e)),c=Math.max(0,s-2),u=Math.min(o.length,s+5),d=o.slice(c,u).join(`
|
|
47
|
-
`);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const
|
|
48
|
-
`)}catch{return``}}async function
|
|
47
|
+
`);return{path:e.record.sourcePath,startLine:e.record.startLine,endLine:e.record.endLine,content:d||t.slice(0,300),relevance:Math.min(1,e.score+a),context:i?`test`:n?`definition`:`usage`}}).sort((e,t)=>t.relevance-e.relevance).slice(0,i),totalFound:u.length}}const rr=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.cts`,`.mjs`,`.cjs`]),ir=new Set([`.git`,z.data,z.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),ar=/auth|token|permission|acl|encrypt|secret|credential|jwt|oauth|password/i,or=/\b(hash|sign|verify|bcrypt|jwt|decrypt|secret|password)\b/i,sr=/auth|security|permission|encrypt|secret|credential/i,cr=/types\.ts$|schema\.ts$|contract\.ts$|\.proto$|openapi|swagger|\.graphql$/i,lr=/(?:^|\/)(events|contracts|shared)(?:\/|$)/i,ur=/export\s+interface\b|export\s+type\b|export\s+const\s+\w*Schema\w*\s*=\s*z\./i,dr=/schema|contract|migration|breaking.change|api.change/i,fr=/migration|data.?model|multi.?service|breaking|backward.?compat/i,pr={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function mr(e){let t=w(e.rootPath),n=e.task.trim(),r=e.files.map(e=>w(t,e)),i=[],a=!1,o=!1;for(let e of r){let r=gr(e,t),i=vr(e);(ar.test(r)||or.test(i)||sr.test(n))&&(a=!0),(cr.test(r)||lr.test(r)||dr.test(n)||ur.test(i)||await yr(e))&&(o=!0)}a&&hr(i,{rule:`security-path`,detail:`Security/auth path, task, or content matched security heuristics`,source:`security_auth`}),o&&hr(i,{rule:`schema-contract`,detail:`Schema or contract path, task, or export shape matched contract heuristics`,source:`schema_contract`});let s=br(r,t);s.affectedFiles>5&&hr(i,{rule:`blast-radius-importers`,detail:`${s.affectedFiles} affected files via direct import scanning`,source:`blast_radius`});let c=[...new Set(r.map(e=>Tr(e,t)).filter(e=>!!e))].sort();c.length>=2&&hr(i,{rule:`cross-package-boundary`,detail:`Files span ${c.length} packages: ${c.join(`, `)}`,source:`cross_package`}),fr.test(n)&&hr(i,{rule:`task-hint-critical`,detail:`Task description matched migration or compatibility criticality hints`,source:`task_hint`});let l=i.length>0?`critical`:r.length===1?`floor`:`standard`;l===`floor`&&(a||o)&&(l=`standard`);let u=wr(i),d=l===`floor`&&u.some(e=>e.type===`contract`)?{suggestedTier:`standard`,reason:`Contract-type unknowns detected — Floor may be insufficient`}:void 0;return{tier:l,triggers:i,packagesCrossed:c,hasSchemaChange:o,hasSecurityPath:a,typedUnknownSeeds:u,ceremony:pr[l],reclassifyHint:d}}function hr(e,t){e.some(e=>e.rule===t.rule&&e.source===t.source)||e.push(t)}function gr(e,t){let n=w(t,e),r=C(t,n);return(r&&!r.startsWith(`..`)?r:n).replace(/\\/g,`/`)}function _r(e){if(!M(e))return!1;try{return L(e).size<=1e5}catch{return!1}}function vr(e){if(!_r(e))return``;try{return P(e,`utf-8`).split(/\r?\n/).slice(0,200).join(`
|
|
48
|
+
`)}catch{return``}}async function yr(e){if(!_r(e))return!1;try{let t=await Jn({path:e}),n=new Set(t.exports);return t.interfaces.some(e=>n.has(e.name))||t.types.some(e=>n.has(e.name))}catch{return!1}}function br(e,t){let n=new Set(e.filter(e=>M(e)));if(n.size===0)return{affectedFiles:e.length,importers:[]};let r=new Set;for(let e of xr(t)){if(n.has(e)||!_r(e))continue;let t=vr(e);t&&Sr(t).some(t=>Cr(t,e,n))&&r.add(e)}return{affectedFiles:e.length+r.size,importers:[...r].map(e=>C(t,e).replace(/\\/g,`/`))}}function xr(e){let t=[];function n(e){let r=[];try{r=F(e)}catch{return}for(let i of r){if(ir.has(i))continue;let r=w(e,i),a;try{a=L(r)}catch{continue}if(a.isDirectory()){n(r);continue}rr.has(b(i).toLowerCase())&&t.push(r)}}return n(e),t}function Sr(e){let t=new Set;for(let n of e.matchAll(/(?:from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]\s*\))/g)){let e=n[1]??n[2]??n[3];e&&t.add(e)}return[...t]}function Cr(e,t,n){if(!e.startsWith(`.`))return!1;let r=w(y(t),e);return[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.jsx`,`${r}.mts`,`${r}.cts`,`${r}.mjs`,`${r}.cjs`,w(r,`index.ts`),w(r,`index.tsx`),w(r,`index.js`),w(r,`index.jsx`)].some(e=>n.has(e))}function wr(e){return e.map(e=>{switch(e.source){case`security_auth`:return{description:`Verify auth and security assumptions before yielding`,type:`contract`,suggestedTool:`aikit_search`};case`schema_contract`:return{description:`Confirm schema and contract compatibility`,type:`contract`,suggestedTool:`aikit_schema_validate`};case`blast_radius`:return{description:`Inspect affected importers before delivery`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`cross_package`:return{description:`Assess downstream package impact across boundaries`,type:`impact`,suggestedTool:`aikit_blast_radius`};case`task_hint`:return{description:`Check established conventions for migrations or compatibility work`,type:`convention`,suggestedTool:`aikit_find`};default:return{description:`No explicit unknown routing required`,type:`freshness`,suggestedTool:`aikit_lookup`}}})}function Tr(e,t){let n=y(w(t,e)),r=w(t);for(;n.length>=r.length;){let e=w(n,`package.json`);if(M(e))try{return JSON.parse(P(e,`utf-8`)).name??C(r,n).replace(/\\/g,`/`)}catch{return C(r,n).replace(/\\/g,`/`)}let t=y(n);if(t===n)break;n=t}}function Er(e){return Math.ceil(e.length/4)}async function Dr(e,t,n){let{task:r,maxFiles:i=15,contentType:a,origin:o}=n,s=await e.embed(r),c={limit:i*3,contentType:a,origin:o},l=await t.search(s,c),u=new Map;for(let e of l){let t=e.record.sourcePath,n=u.get(t);n?(n.chunks.push(e),n.totalChars+=e.record.content.length,n.maxScore=Math.max(n.maxScore,e.score)):u.set(t,{chunks:[e],totalChars:e.record.content.length,maxScore:e.score})}let d=[...u.entries()].sort(([,e],[,t])=>t.maxScore-e.maxScore).slice(0,i).map(([e,{chunks:t,maxScore:n}])=>{let r=t.sort((e,t)=>e.record.startLine-t.record.startLine).map(e=>({start:e.record.startLine,end:e.record.endLine,heading:e.record.headingPath})),i=t.sort((e,t)=>t.score-e.score)[0];return{path:e,reason:i.record.headingPath?`Matches: ${i.record.headingPath}`:`Contains relevant ${i.record.contentType} content`,estimatedTokens:0,relevance:n,focusRanges:r}});for(let e of d){let t=u.get(e.path);t&&(e.estimatedTokens=Er(t.chunks.map(e=>e.record.content).join(``)))}let f=d.reduce((e,t)=>e+t.estimatedTokens,0),p=[...d].sort((e,t)=>{let n=e.path.includes(`config`)||e.path.includes(`types`)?-1:0,r=t.path.includes(`config`)||t.path.includes(`types`)?-1:0;return n===r?t.relevance-e.relevance:n-r}).map(e=>e.path),m=[];for(let e of d)e.estimatedTokens<=100?m.push(`aikit_file_summary({ path: "${e.path}" }) → ~${e.estimatedTokens} tokens`):m.push(`aikit_compact({ path: "${e.path}", query: "${r}" }) → ~${Math.ceil(e.estimatedTokens/5)} tokens`);return{task:r,files:d,totalEstimatedTokens:f,readingOrder:p,compactCommands:m}}const Or={floor:{ground:`Parasitic — read target file only`,build:`Implement directly`,break:`Skip`,evidenceMap:`Not required`,gate:`Self-certify`},standard:{ground:`Scope map + blast radius + constraint seed`,build:`TDD — test first, then implement`,break:`Error paths + edge cases`,evidenceMap:`3-8 critical-path entries`,gate:`YIELD/HOLD evaluation`},critical:{ground:`Full scope map + blast radius + trace + patterns + constraint pack`,build:`TDD + contract verification + cross-service validation`,break:`Error paths + edge cases + security dimensions + data-flow verification`,evidenceMap:`Comprehensive — all critical-path claims with receipts`,gate:`Strict YIELD/HOLD/HARD_BLOCK evaluation`}};async function kr(e,t,n){let r=n.maxConstraints??3,i=await Ar(n),a=await Nr(n.files);if(i.tier===`floor`)return Br({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:null,typedUnknownSeeds:i.typedUnknownSeeds,constraints:[],fileSummaries:a,evidenceMapTaskId:null,ceremony:i.ceremony});let[o,s,c]=await Promise.all([jr(e,t,n.task,i.tier),Mr(e,t,n.task,r),Fr(n.rootPath,n.taskId??Vr(n.task),i.tier)]);return Br({tier:i.tier,classifyTriggers:i.classifyTriggers,scopeMap:o,typedUnknownSeeds:i.typedUnknownSeeds,constraints:s,fileSummaries:a,evidenceMapTaskId:c,ceremony:i.ceremony})}async function Ar(e){if(e.forceTier)return{tier:e.forceTier,classifyTriggers:[],typedUnknownSeeds:[],ceremony:zr(e.forceTier)};try{let t=await mr({files:e.files,task:e.task,rootPath:e.rootPath});return{tier:t.tier,classifyTriggers:t.triggers,typedUnknownSeeds:t.typedUnknownSeeds,ceremony:t.ceremony}}catch{return{tier:`standard`,classifyTriggers:[],typedUnknownSeeds:[],ceremony:zr(`standard`)}}}async function jr(e,t,n,r){try{return await Dr(e,t,{task:n,maxFiles:r===`critical`?20:10})}catch{return null}}async function Mr(e,t,n,r){try{let i=`decision pattern convention ${n}`,a=typeof e.embedQuery==`function`?await e.embedQuery(i):await e.embed(i);return(await t.search(a,{limit:r,origin:`curated`})).slice(0,r).map(e=>Ir(e))}catch{return[]}}async function Nr(e){return Promise.all(e.map(async e=>Pr(e)))}async function Pr(e){try{return Rr(await Jn({path:e}))}catch(t){return{path:e,exports:[],functions:[],lines:0,error:t instanceof Error?t.message:`Unable to summarize file`}}}async function Fr(e,t,n){try{return Wn({action:`create`,taskId:t,tier:n},e),t}catch{return null}}function Ir(e){return{source:e.record.sourcePath,snippet:Lr(e.record.content),relevance:e.score}}function Lr(e){let t=e.replace(/\s+/g,` `).trim();return t.length<=200?t:`${t.slice(0,197).trimEnd()}...`}function Rr(e){return{path:e.path,exports:e.exports,functions:e.functions.map(e=>e.name),lines:e.lines}}function zr(e){return{...Or[e]}}function Br(e){return{...e,estimatedTokens:U(JSON.stringify(e))}}function Vr(e){let t=e.toLowerCase().replace(/[^a-z0-9\s]/g,` `).split(/\s+/).filter(Boolean).slice(0,5).join(`-`),n=Date.now().toString(36);return`${t||`task`}-${n}`}const Hr=T(l);async function Ur(e,t){try{let{stdout:n}=await Hr(`git`,e,{cwd:t,timeout:15e3});return n.toString().trim()}catch{return``}}async function Wr(e={}){let t=e.cwd??process.cwd(),n=e.commitCount??5,r=await Ur([`rev-parse`,`--show-toplevel`],t);if(!r)return{gitRoot:t,branch:`unknown`,status:{staged:[],modified:[],untracked:[]},recentCommits:[]};let i=r,[a,o,s,c]=await Promise.all([Ur([`rev-parse`,`--abbrev-ref`,`HEAD`],i),Ur([`status`,`--porcelain`],i),Ur([`log`,`--max-count=${n}`,`--format=%h|%s|%an|%ai`],i),e.includeDiff?Ur([`diff`,`--stat`,`--no-color`],i):Promise.resolve(``)]),l=[],u=[],d=[];for(let e of o.split(`
|
|
49
49
|
`).filter(Boolean)){let t=e[0],n=e[1],r=e.slice(3).trim();t!==` `&&t!==`?`&&l.push(r),(n===`M`||n===`D`)&&u.push(r),t===`?`&&d.push(r)}let f=s.split(`
|
|
50
|
-
`).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function Vr(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function Hr(e,t){let{action:n}=t;switch(n){case`find_nodes`:{let r=await e.findNodes({type:t.nodeType,namePattern:t.namePattern,sourcePath:t.sourcePath,limit:t.limit});return{action:n,nodes:r,summary:`Found ${r.length} node(s)${t.nodeType?` of type "${t.nodeType}"`:``}${t.namePattern?` matching "${t.namePattern}"`:``}`}}case`find_edges`:{let r=await e.findEdges({type:t.edgeType,fromId:t.fromId,toId:t.toId,limit:t.limit});return{action:n,edges:r,summary:`Found ${r.length} edge(s)${t.edgeType?` of type "${t.edgeType}"`:``}`}}case`neighbors`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for neighbors action`};let r=await e.getNeighbors(t.nodeId,{edgeType:t.edgeType,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Found ${r.nodes.length} neighbor(s) and ${r.edges.length} edge(s) for node "${t.nodeId}"`}}case`traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for traverse action`};let r=await e.traverse(t.nodeId,{edgeType:t.edgeType,maxDepth:t.maxDepth,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Traversed ${r.nodes.length} node(s) and ${r.edges.length} edge(s) from "${t.nodeId}" (depth=${t.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:n,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`validate`:{let t=await e.validate();return{action:n,validation:t,stats:t.stats,summary:t.valid?`Graph validation passed: ${t.stats.nodeCount} nodes, ${t.stats.edgeCount} edges, ${t.orphanNodes.length} orphan node(s)`:`Graph validation found ${t.danglingEdges.length} dangling edge(s) and ${t.orphanNodes.length} orphan node(s)`}}case`add`:{let r=0,i=0;if(t.nodes&&t.nodes.length>0){let n=t.nodes.map(e=>({id:e.id??Vr(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(n),r=n.length}if(t.edges&&t.edges.length>0){let n=t.edges.map(e=>({id:e.id??Vr(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(n),i=n.length}return{action:n,nodesAdded:r,edgesAdded:i,summary:`Added ${r} node(s) and ${i} edge(s) to the graph`}}case`delete`:if(t.nodeId)return await e.deleteNode(t.nodeId),{action:n,deleted:1,summary:`Deleted node "${t.nodeId}" and its edges`};if(t.sourcePath){let r=await e.deleteBySourcePath(t.sourcePath);return{action:n,deleted:r,summary:`Deleted ${r} node(s) from source "${t.sourcePath}"`}}return{action:n,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:n,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}case`detect_communities`:{let t=await e.detectCommunities(),r=Object.values(t).reduce((e,t)=>e+t.length,0);return{action:n,communities:t,summary:`Detected ${Object.keys(t).length} community/communities covering ${r} node(s)`}}case`set_community`:return!t.nodeId||!t.community?{action:n,summary:`Error: nodeId and community are required for set_community action`}:(await e.setNodeCommunity(t.nodeId,t.community),{action:n,summary:`Set community "${t.community}" on node "${t.nodeId}"`});case`trace_process`:{if(!t.nodeId||!t.label)return{action:n,summary:`Error: nodeId and label are required for trace_process action`};let r=await e.traceProcess(t.nodeId,t.label);return{action:n,process:r,summary:`Traced process "${r.label}" from node "${t.nodeId}": ${r.steps.length} step(s)`}}case`list_processes`:{let r=await e.getProcesses(t.nodeId);return{action:n,processes:r,summary:`Found ${r.length} process(es)${t.nodeId?` involving node "${t.nodeId}"`:``}`}}case`delete_process`:return t.processId?(await e.deleteProcess(t.processId),{action:n,summary:`Deleted process "${t.processId}"`}):{action:n,summary:`Error: processId is required for delete_process action`};case`depth_traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for depth_traverse action`};let r=await e.depthGroupedTraversal(t.nodeId,t.maxDepth,{edgeType:t.edgeType,direction:t.direction,limit:t.limit}),i=Object.values(r).reduce((e,t)=>e+t.length,0);return{action:n,depthGroups:r,summary:`Depth-grouped traversal from "${t.nodeId}": ${i} node(s) across ${Object.keys(r).length} depth level(s)`}}case`cohesion`:{if(!t.community)return{action:n,summary:`Error: community is required for cohesion action`};let r=await e.getCohesionScore(t.community);return{action:n,cohesionScore:r,summary:`Community "${t.community}" cohesion score: ${(r*100).toFixed(1)}%`}}case`symbol360`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for symbol360 action`};let r=await e.getSymbol360(t.nodeId);return{action:n,symbol360:r,nodes:[r.node],edges:[...r.incoming,...r.outgoing],summary:`360° view of "${r.node.name}": ${r.incoming.length} incoming, ${r.outgoing.length} outgoing, community: ${r.community??`none`}, ${r.processes.length} process(es)`}}default:return{action:n,summary:`Unknown action: ${n}`}}}async function Ur(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const Wr=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`summary`}},{tool:`check`,reason:`Typecheck + lint validation`,order:3},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5},{tool:`test_run`,reason:`Re-run tests after fix`,order:6}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`check`,reason:`Validate after implementation`,order:7},{tool:`test_run`,reason:`Run tests to verify`,order:8},{tool:`blast_radius`,reason:`Check impact of changes`,order:9}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7},{tool:`test_run`,reason:`Ensure no regressions`,order:8}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`}},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`}},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`errors`}},{tool:`test_run`,reason:`Run tests with structured output`,order:2},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze_structure`,reason:`Project structure overview`,order:1},{tool:`analyze_dependencies`,reason:`Dependency graph and analysis`,order:2},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze_patterns`,reason:`Detect code patterns and conventions`,order:6},{tool:`analyze_entry_points`,reason:`Find handlers, exports, and entry points`,order:7},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams`,order:8}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow_list`,reason:`List all available flows (builtin + custom)`,order:1},{tool:`flow_status`,reason:`Check current active flow and step`,order:2},{tool:`flow_start`,reason:`Start a named flow`,order:3},{tool:`flow_step`,reason:`Advance to next step, skip, or redo`,order:4},{tool:`flow_read_instruction`,reason:`Read the current step instruction`,order:5},{tool:`flow_info`,reason:`Get detailed info about a specific flow`,order:6},{tool:`flow_add`,reason:`Install a new custom flow`,order:7},{tool:`flow_update`,reason:`Update an existing custom flow`,order:8},{tool:`flow_remove`,reason:`Remove a custom flow`,order:9},{tool:`flow_reset`,reason:`Clear active flow state to start over`,order:10}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`brainstorm`,description:`Interactive ideation and creative exploration for design decisions`,keywords:[`brainstorm`,`ideate`,`ideas`,`explore`,`creative`,`design`,`options`,`approach`,`alternatives`,`think`],tools:[{tool:`brainstorm`,reason:`Interactive structured ideation session`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2,suggestedArgs:{origin:`curated`}},{tool:`remember`,reason:`Persist chosen direction as a decision`,order:3,suggestedArgs:{category:`decisions`}}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams for architecture views`,order:2},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]}];function Gr(e,t=5,n){let r=e.toLowerCase(),i=Wr.map(e=>{let t=0;for(let n of e.keywords)r.includes(n)&&(t+=n.includes(` `)?2:1);return{workflow:e,score:t}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),a=Wr.find(e=>e.name===`search`)??Wr[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}function Kr(e,t,n=.6){if(e.length<=t)return e;let r=Math.max(0,t-120),i=Math.floor(r*n),a=r-i,o=e.slice(0,i),s=o.lastIndexOf(`
|
|
50
|
+
`).filter(Boolean).map(e=>{let[t,n,r,i]=e.split(`|`);return{hash:t,message:n,author:r,date:i}});return{gitRoot:r,branch:a||`unknown`,status:{staged:l,modified:u,untracked:d},recentCommits:f,diff:c||void 0}}function Gr(e,...t){return`${e}_${V(`sha256`).update(t.join(`|`)).digest(`hex`).slice(0,12)}`}async function Kr(e,t){let{action:n}=t;switch(n){case`find_nodes`:{let r=await e.findNodes({type:t.nodeType,namePattern:t.namePattern,sourcePath:t.sourcePath,limit:t.limit});return{action:n,nodes:r,summary:`Found ${r.length} node(s)${t.nodeType?` of type "${t.nodeType}"`:``}${t.namePattern?` matching "${t.namePattern}"`:``}`}}case`find_edges`:{let r=await e.findEdges({type:t.edgeType,fromId:t.fromId,toId:t.toId,limit:t.limit});return{action:n,edges:r,summary:`Found ${r.length} edge(s)${t.edgeType?` of type "${t.edgeType}"`:``}`}}case`neighbors`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for neighbors action`};let r=await e.getNeighbors(t.nodeId,{edgeType:t.edgeType,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Found ${r.nodes.length} neighbor(s) and ${r.edges.length} edge(s) for node "${t.nodeId}"`}}case`traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for traverse action`};let r=await e.traverse(t.nodeId,{edgeType:t.edgeType,maxDepth:t.maxDepth,direction:t.direction,limit:t.limit});return{action:n,nodes:r.nodes,edges:r.edges,summary:`Traversed ${r.nodes.length} node(s) and ${r.edges.length} edge(s) from "${t.nodeId}" (depth=${t.maxDepth??2})`}}case`stats`:{let t=await e.getStats();return{action:n,stats:t,summary:`Graph: ${t.nodeCount} nodes, ${t.edgeCount} edges. Types: ${Object.entries(t.nodeTypes).map(([e,t])=>`${e}(${t})`).join(`, `)||`none`}`}}case`validate`:{let t=await e.validate();return{action:n,validation:t,stats:t.stats,summary:t.valid?`Graph validation passed: ${t.stats.nodeCount} nodes, ${t.stats.edgeCount} edges, ${t.orphanNodes.length} orphan node(s)`:`Graph validation found ${t.danglingEdges.length} dangling edge(s) and ${t.orphanNodes.length} orphan node(s)`}}case`add`:{let r=0,i=0;if(t.nodes&&t.nodes.length>0){let n=t.nodes.map(e=>({id:e.id??Gr(`node`,e.type,e.name),type:e.type,name:e.name,properties:e.properties??{},sourceRecordId:e.sourceRecordId,sourcePath:e.sourcePath,createdAt:new Date().toISOString()}));await e.upsertNodes(n),r=n.length}if(t.edges&&t.edges.length>0){let n=t.edges.map(e=>({id:e.id??Gr(`edge`,e.fromId,e.toId,e.type),fromId:e.fromId,toId:e.toId,type:e.type,weight:e.weight,properties:e.properties}));await e.upsertEdges(n),i=n.length}return{action:n,nodesAdded:r,edgesAdded:i,summary:`Added ${r} node(s) and ${i} edge(s) to the graph`}}case`delete`:if(t.nodeId)return await e.deleteNode(t.nodeId),{action:n,deleted:1,summary:`Deleted node "${t.nodeId}" and its edges`};if(t.sourcePath){let r=await e.deleteBySourcePath(t.sourcePath);return{action:n,deleted:r,summary:`Deleted ${r} node(s) from source "${t.sourcePath}"`}}return{action:n,summary:`Error: nodeId or sourcePath required for delete action`};case`clear`:{let t=await e.getStats();return await e.clear(),{action:n,deleted:t.nodeCount,summary:`Cleared graph: removed ${t.nodeCount} node(s) and ${t.edgeCount} edge(s)`}}case`detect_communities`:{let t=await e.detectCommunities(),r=Object.values(t).reduce((e,t)=>e+t.length,0);return{action:n,communities:t,summary:`Detected ${Object.keys(t).length} community/communities covering ${r} node(s)`}}case`set_community`:return!t.nodeId||!t.community?{action:n,summary:`Error: nodeId and community are required for set_community action`}:(await e.setNodeCommunity(t.nodeId,t.community),{action:n,summary:`Set community "${t.community}" on node "${t.nodeId}"`});case`trace_process`:{if(!t.nodeId||!t.label)return{action:n,summary:`Error: nodeId and label are required for trace_process action`};let r=await e.traceProcess(t.nodeId,t.label);return{action:n,process:r,summary:`Traced process "${r.label}" from node "${t.nodeId}": ${r.steps.length} step(s)`}}case`list_processes`:{let r=await e.getProcesses(t.nodeId);return{action:n,processes:r,summary:`Found ${r.length} process(es)${t.nodeId?` involving node "${t.nodeId}"`:``}`}}case`delete_process`:return t.processId?(await e.deleteProcess(t.processId),{action:n,summary:`Deleted process "${t.processId}"`}):{action:n,summary:`Error: processId is required for delete_process action`};case`depth_traverse`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for depth_traverse action`};let r=await e.depthGroupedTraversal(t.nodeId,t.maxDepth,{edgeType:t.edgeType,direction:t.direction,limit:t.limit}),i=Object.values(r).reduce((e,t)=>e+t.length,0);return{action:n,depthGroups:r,summary:`Depth-grouped traversal from "${t.nodeId}": ${i} node(s) across ${Object.keys(r).length} depth level(s)`}}case`cohesion`:{if(!t.community)return{action:n,summary:`Error: community is required for cohesion action`};let r=await e.getCohesionScore(t.community);return{action:n,cohesionScore:r,summary:`Community "${t.community}" cohesion score: ${(r*100).toFixed(1)}%`}}case`symbol360`:{if(!t.nodeId)return{action:n,summary:`Error: nodeId is required for symbol360 action`};let r=await e.getSymbol360(t.nodeId);return{action:n,symbol360:r,nodes:[r.node],edges:[...r.incoming,...r.outgoing],summary:`360° view of "${r.node.name}": ${r.incoming.length} incoming, ${r.outgoing.length} outgoing, community: ${r.community??`none`}, ${r.processes.length} process(es)`}}default:return{action:n,summary:`Unknown action: ${n}`}}}async function qr(e,t,n){let r=n?.hops??1,i=n?.maxPerHit??5,a=[];for(let o of t)try{let t=await e.findNodes({sourcePath:o.sourcePath}),s=[],c=[],l=new Set,u=new Set;for(let a of t.slice(0,i))if(!l.has(a.id)&&(l.add(a.id),s.push(a),r>0)){let t=await e.traverse(a.id,{maxDepth:r,edgeType:n?.edgeType,limit:i});for(let e of t.nodes)l.has(e.id)||(l.add(e.id),s.push(e));for(let e of t.edges)u.has(e.id)||(u.add(e.id),c.push(e))}a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:s,edges:c}})}catch{a.push({recordId:o.recordId,score:o.score,sourcePath:o.sourcePath,graphContext:{nodes:[],edges:[]}})}return a}const Jr=[{name:`onboard`,description:`First-time codebase exploration and understanding`,keywords:[`onboard`,`new project`,`understand`,`explore`,`first time`,`getting started`,`learn`,`overview`],tools:[{tool:`status`,reason:`Check index health and record count`,order:1},{tool:`onboard`,reason:`Run all analysis tools in one command`,order:2,suggestedArgs:{path:`.`}},{tool:`search`,reason:`Find specific topics of interest`,order:3},{tool:`graph`,reason:`Module & symbol relationship map — stats for overview, neighbors for exploration`,order:4,suggestedArgs:{action:`stats`}}]},{name:`audit`,description:`Assess project health, quality, and structure`,keywords:[`audit`,`health`,`quality`,`assess`,`review project`,`check quality`,`code quality`,`tech debt`],tools:[{tool:`status`,reason:`Check index freshness`,order:1},{tool:`audit`,reason:`Unified audit report with score and recommendations`,order:2,suggestedArgs:{detail:`summary`}},{tool:`check`,reason:`Typecheck + lint validation`,order:3},{tool:`health`,reason:`Detailed health checks on package.json, tsconfig, etc.`,order:4}]},{name:`bugfix`,description:`Diagnose and fix a bug or failing test`,keywords:[`bug`,`fix`,`debug`,`error`,`failing`,`broken`,`crash`,`wrong`,`issue`,`problem`,`not working`],tools:[{tool:`parse_output`,reason:`Parse error output from build tools (tsc, vitest, biome)`,order:1},{tool:`symbol`,reason:`Find definition and all references of the failing symbol`,order:2},{tool:`trace`,reason:`Trace call chain backward from the failure point`,order:3,suggestedArgs:{direction:`backward`}},{tool:`graph`,reason:`Understand module context — what imports the failing module`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`search`,reason:`Search for related patterns or similar fixes`,order:5},{tool:`test_run`,reason:`Re-run tests after fix`,order:6}]},{name:`implement`,description:`Add a new feature or implement a change`,keywords:[`implement`,`add feature`,`new feature`,`build`,`create`,`add`,`develop`,`write code`],tools:[{tool:`scope_map`,reason:`Generate a reading plan for affected files`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2},{tool:`find`,reason:`Find usage examples of similar patterns`,order:3,suggestedArgs:{mode:`examples`}},{tool:`graph`,reason:`Map module dependencies before adding new code`,order:4,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Find existing patterns to follow`,order:5},{tool:`trace`,reason:`Understand call chains to integrate with`,order:6},{tool:`check`,reason:`Validate after implementation`,order:7},{tool:`test_run`,reason:`Run tests to verify`,order:8},{tool:`blast_radius`,reason:`Check impact of changes`,order:9}]},{name:`refactor`,description:`Restructure or clean up existing code`,keywords:[`refactor`,`restructure`,`clean up`,`reorganize`,`rename`,`move`,`extract`,`DRY`,`dead code`],tools:[{tool:`dead_symbols`,reason:`Find unused exports to remove`,order:1},{tool:`graph`,reason:`Map module dependency graph before restructuring`,order:2,suggestedArgs:{action:`neighbors`}},{tool:`trace`,reason:`Understand call chains affected by refactoring`,order:3},{tool:`symbol`,reason:`Find all references before renaming`,order:4},{tool:`blast_radius`,reason:`Assess impact before making changes`,order:5},{tool:`rename`,reason:`Safe cross-file rename`,order:6},{tool:`check`,reason:`Validate after refactoring`,order:7},{tool:`test_run`,reason:`Ensure no regressions`,order:8}]},{name:`search`,description:`Find specific code, patterns, or information`,keywords:[`find`,`search`,`where`,`locate`,`look for`,`grep`,`which file`,`how does`],tools:[{tool:`search`,reason:`Hybrid semantic + keyword search`,order:1},{tool:`find`,reason:`Federated search with glob and regex`,order:2},{tool:`symbol`,reason:`Resolve a specific symbol definition and references`,order:3},{tool:`graph`,reason:`Explore cross-module import relationships and connected symbols`,order:4,suggestedArgs:{action:`neighbors`}}]},{name:`code-navigation`,description:`Understand code structure, module relationships, and cross-package dependencies`,keywords:[`navigate`,`understand`,`module`,`import`,`dependency`,`relationship`,`call chain`,`who calls`,`who uses`,`connected`,`cross-package`],tools:[{tool:`graph`,reason:`Module import graph — see who imports whom across packages`,order:1,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Resolve symbol definitions and all references`,order:2},{tool:`trace`,reason:`Follow call chains forward or backward`,order:3},{tool:`file_summary`,reason:`Structural overview of target files`,order:4}]},{name:`context`,description:`Compress or manage context for efficient LLM interaction`,keywords:[`context`,`compress`,`summarize`,`too long`,`token`,`budget`,`reduce`,`compact`],tools:[{tool:`file_summary`,reason:`Quick structural overview without reading full file`,order:1},{tool:`compact`,reason:`Compress file to relevant sections`,order:2,suggestedArgs:{segmentation:`paragraph`}},{tool:`digest`,reason:`Compress multiple sources into budgeted summary`,order:3},{tool:`stratum_card`,reason:`Generate reusable context cards`,order:4}]},{name:`memory`,description:`Manage persistent knowledge across sessions`,keywords:[`memory`,`remember`,`persist`,`save`,`recall`,`decision`,`convention`,`session`,`checkpoint`],tools:[{tool:`list`,reason:`See all stored knowledge entries`,order:1},{tool:`search`,reason:`Search curated knowledge`,order:2,suggestedArgs:{origin:`curated`}},{tool:`remember`,reason:`Store a new decision or pattern`,order:3},{tool:`checkpoint`,reason:`Save/restore session progress`,order:4},{tool:`stash`,reason:`Temporary key-value storage within session`,order:5}]},{name:`validate`,description:`Run checks, tests, and validation`,keywords:[`validate`,`check`,`test`,`lint`,`typecheck`,`verify`,`CI`,`pass`,`run tests`],tools:[{tool:`check`,reason:`Typecheck + lint in one call`,order:1,suggestedArgs:{detail:`errors`}},{tool:`test_run`,reason:`Run tests with structured output`,order:2},{tool:`health`,reason:`Project health assessment`,order:3}]},{name:`analyze`,description:`Deep analysis of codebase structure, dependencies, or patterns`,keywords:[`analyze`,`dependency`,`structure`,`pattern`,`architecture`,`diagram`,`entry point`,`import`],tools:[{tool:`analyze_structure`,reason:`Project structure overview`,order:1},{tool:`analyze_dependencies`,reason:`Dependency graph and analysis`,order:2},{tool:`graph`,reason:`Traverse module import graph for cross-package relationships`,order:3,suggestedArgs:{action:`neighbors`}},{tool:`symbol`,reason:`Deep-dive into specific symbols`,order:4},{tool:`trace`,reason:`Follow data flow and call chains`,order:5},{tool:`analyze_patterns`,reason:`Detect code patterns and conventions`,order:6},{tool:`analyze_entry_points`,reason:`Find handlers, exports, and entry points`,order:7},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams`,order:8}]},{name:`upgrade`,description:`Update AI Kit agents, prompts, skills, and scaffold to the latest version (user-level and workspace-level)`,keywords:[`upgrade`,`update`,`version`,`scaffold`,`outdated`,`mismatch`,`deploy`,`install`,`refresh`],tools:[{tool:`status`,reason:`Check current versions and detect mismatches — auto-triggers upgrade when a version mismatch is found`,order:1},{tool:`reindex`,reason:`Refresh the index after the upgrade completes`,order:2},{tool:`produce_knowledge`,reason:`Regenerate codebase analysis with updated tooling`,order:3,suggestedArgs:{path:`.`}}]},{name:`flow`,description:`Manage development flows — structured step-by-step processes for tasks`,keywords:[`flow`,`workflow`,`step`,`process`,`pipeline`,`lifecycle`,`sequence`,`start flow`,`flow status`],tools:[{tool:`flow_list`,reason:`List all available flows (builtin + custom)`,order:1},{tool:`flow_status`,reason:`Check current active flow and step`,order:2},{tool:`flow_start`,reason:`Start a named flow`,order:3},{tool:`flow_step`,reason:`Advance to next step, skip, or redo`,order:4},{tool:`flow_read_instruction`,reason:`Read the current step instruction`,order:5},{tool:`flow_info`,reason:`Get detailed info about a specific flow`,order:6},{tool:`flow_add`,reason:`Install a new custom flow`,order:7},{tool:`flow_update`,reason:`Update an existing custom flow`,order:8},{tool:`flow_remove`,reason:`Remove a custom flow`,order:9},{tool:`flow_reset`,reason:`Clear active flow state to start over`,order:10}]},{name:`web`,description:`Fetch web pages, search the web, or make HTTP API calls`,keywords:[`web`,`fetch`,`url`,`website`,`api`,`http`,`request`,`download`,`scrape`,`browse`,`web search`,`online`],tools:[{tool:`web_search`,reason:`Search the web for information`,order:1},{tool:`web_fetch`,reason:`Fetch and extract content from URLs`,order:2},{tool:`http`,reason:`Make raw HTTP requests to APIs`,order:3}]},{name:`brainstorm`,description:`Interactive ideation and creative exploration for design decisions`,keywords:[`brainstorm`,`ideate`,`ideas`,`explore`,`creative`,`design`,`options`,`approach`,`alternatives`,`think`],tools:[{tool:`brainstorm`,reason:`Interactive structured ideation session`,order:1},{tool:`search`,reason:`Find related patterns and prior art`,order:2,suggestedArgs:{origin:`curated`}},{tool:`remember`,reason:`Persist chosen direction as a decision`,order:3,suggestedArgs:{category:`decisions`}}]},{name:`present`,description:`Display rich visual content — dashboards, charts, tables, timelines`,keywords:[`present`,`dashboard`,`chart`,`table`,`visualize`,`display`,`show`,`render`,`report`,`timeline`],tools:[{tool:`present`,reason:`Render rich HTML dashboards, charts, and tables`,order:1},{tool:`analyze_diagram`,reason:`Generate Mermaid diagrams for architecture views`,order:2},{tool:`measure`,reason:`Collect metrics to visualize`,order:3}]},{name:`quality`,description:`FORGE quality gates — classify task complexity, ground requirements, verify evidence`,keywords:[`quality`,`forge`,`evidence`,`gate`,`classify`,`ground`,`tier`,`critical`,`verify`,`proof`],tools:[{tool:`forge_classify`,reason:`Determine task tier (Floor/Standard/Critical)`,order:1},{tool:`forge_ground`,reason:`Ground requirements with evidence criteria`,order:2},{tool:`evidence_map`,reason:`Map evidence and run quality gates`,order:3,suggestedArgs:{action:`gate`}},{tool:`check`,reason:`Typecheck + lint validation`,order:4},{tool:`test_run`,reason:`Run tests for coverage evidence`,order:5}]},{name:`transform`,description:`Automated code transformations — codemods, renames, data transforms`,keywords:[`transform`,`codemod`,`rename`,`replace`,`migrate`,`convert`,`data transform`,`rewrite`,`bulk edit`],tools:[{tool:`rename`,reason:`Safe cross-file symbol rename`,order:1},{tool:`codemod`,reason:`Apply AST-level code transformations`,order:2},{tool:`data_transform`,reason:`Transform data between formats`,order:3},{tool:`diff_parse`,reason:`Parse and analyze diffs`,order:4},{tool:`blast_radius`,reason:`Check impact of transformations`,order:5}]},{name:`git`,description:`Git context, changelogs, and version tracking`,keywords:[`git`,`commit`,`diff`,`changelog`,`history`,`branch`,`version`,`release`,`changes`,`what changed`],tools:[{tool:`git_context`,reason:`Get git status, diff, and branch info`,order:1},{tool:`changelog`,reason:`Generate changelog from git history`,order:2},{tool:`blast_radius`,reason:`Assess impact of changed files`,order:3}]},{name:`indexing`,description:`Manage smart indexing, trickle mode, and index maintenance`,keywords:[`index`,`indexing`,`smart index`,`trickle`,`reindex`,`index mode`,`index status`,`queue`,`stale index`],tools:[{tool:`status`,reason:`Check index mode, queue size, and freshness`,order:1},{tool:`reindex`,reason:`Force a full reindex (only when smart mode cannot keep up)`,order:2,suggestedArgs:{force:!0}},{tool:`produce_knowledge`,reason:`Regenerate curated resource analysis`,order:3,suggestedArgs:{path:`.`}}]}];function Yr(e,t=5,n){let r=e.toLowerCase(),i=Jr.map(e=>{let t=0;for(let n of e.keywords)r.includes(n)&&(t+=n.includes(` `)?2:1);return{workflow:e,score:t}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score),a=Jr.find(e=>e.name===`search`)??Jr[0],o=i[0]?.workflow??a,s=i.slice(1,4).map(e=>e.workflow.name).filter(e=>e!==o.name),c={workflow:o.name,description:o.description,tools:o.tools.slice(0,t),alternativeWorkflows:s};return n===`smart`&&(c.tools=c.tools.map(e=>e.tool===`reindex`?{...e,reason:`Smart indexing is active — files are indexed automatically. Use reindex({ force: true }) only if the index is severely outdated.`,suggestedArgs:{force:!0}}:e)),c}function Xr(e,t,n=.6){if(e.length<=t)return e;let r=Math.max(0,t-120),i=Math.floor(r*n),a=r-i,o=e.slice(0,i),s=o.lastIndexOf(`
|
|
51
51
|
`),c=s>0?o.slice(0,s):o,l=e.length-a,u=e.slice(l),d=u.indexOf(`
|
|
52
52
|
`),f=d>=0?u.slice(d+1):u,p=e.length-c.length-f.length,m=1,h=c.length,g=e.length-f.length;for(let t=h;t<g;t++)e.charCodeAt(t)===10&&m++;return`${c}\n\n[… ${m} lines / ${(p/1024).toFixed(1)}KB truncated — showing first ${c.split(`
|
|
53
53
|
`).length} + last ${f.split(`
|
|
54
|
-
`).length} lines]\n\n${f}`}function
|
|
54
|
+
`).length} lines]\n\n${f}`}function Zr(e,t){if(e.length<=t)return e;let n=Math.max(0,t-200),r=e.slice(n,t).lastIndexOf(`
|
|
55
55
|
|
|
56
|
-
`),i=r>=0?n+r:t,a=e.slice(0,i).trimEnd(),o=Math.round(i/e.length*100);return`${a}\n\n---\n*[Truncated at ${i.toLocaleString()} chars — ${o}% of original content]*`}function
|
|
56
|
+
`),i=r>=0?n+r:t,a=e.slice(0,i).trimEnd(),o=Math.round(i/e.length*100);return`${a}\n\n---\n*[Truncated at ${i.toLocaleString()} chars — ${o}% of original content]*`}function Qr(e,t){let n=t*4;return e.length<=n?e:Xr(e,n)}const $r=5e4;async function ei(e){let{url:t,method:n=`GET`,headers:r={},body:i,timeout:a=15e3}=e,o=new URL(t);if(o.protocol!==`http:`&&o.protocol!==`https:`)throw Error(`Unsupported protocol: ${o.protocol} — only http/https allowed`);let s=o.hostname;if(s===`169.254.169.254`||s===`metadata.google.internal`||s.startsWith(`fd`)||/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(s)||s===`0.0.0.0`||s===`[::]`)throw Error(`Blocked request to private/metadata address: ${s}`);let c=new AbortController,l=setTimeout(()=>c.abort(),a),u=Date.now(),d;try{d=await fetch(t,{method:n,headers:{"User-Agent":`aikit-http/1.0`,...r},body:n!==`GET`&&n!==`HEAD`?i:void 0,signal:c.signal,redirect:`follow`})}finally{clearTimeout(l)}let f=Date.now()-u,p=await d.text(),m=d.headers.get(`content-type`)??``,h=p;if(m.includes(`json`))try{h=JSON.stringify(JSON.parse(p),null,2)}catch{}let g=!1;h.length>$r&&(h=Xr(h,$r),g=!0);let _={};return d.headers.forEach((e,t)=>{_[t]=e}),{status:d.status,statusText:d.statusText,headers:_,body:h,durationMs:f,contentType:m,sizeBytes:p.length,truncated:g}}function ti(e){return w(B(e??process.cwd()),`lanes`)}const ni=`.lane-meta.json`;function ri(e){return ti(e)}function K(e,t){let n=ri(t),r=w(n,e);if(!r.startsWith(w(n)))throw Error(`Invalid lane name: "${e}"`);return r}function ii(e,t){let n=S(K(e,t),ni);if(!M(n))throw Error(`Lane "${e}" does not exist`);try{return JSON.parse(P(n,`utf-8`))}catch{throw Error(`Lane "${e}" has corrupted metadata`)}}function ai(e,t,n){let r=n??process.cwd(),i=K(e,n);if(M(i))throw Error(`Lane "${e}" already exists`);N(i,{recursive:!0});let a=[];for(let e of t){let t=w(r,e);if(!M(t))throw Error(`Source file does not exist: ${e}`);let n=C(r,t).replace(/\\/g,`/`),o=S(i,n);N(S(o,`..`),{recursive:!0}),j(t,o),a.push(n)}let o={name:e,createdAt:new Date().toISOString(),sourceFiles:a,rootPath:r};return R(S(i,ni),`${JSON.stringify(o,null,2)}\n`,`utf-8`),o}function oi(e){let t=ri(e);if(!M(t))return[];let n=F(t),r=[];for(let e of n){let n=S(t,e,ni);if(M(n))try{r.push(JSON.parse(P(n,`utf-8`)))}catch{}}return r}function si(e,t){let n=ii(e,t),r=K(e,t),i=n.rootPath,a=[];for(let e of n.sourceFiles){let t=w(i,e),n=S(r,e);if(!M(n)){a.push({file:e,status:`deleted`});continue}if(!M(t)){a.push({file:e,status:`added`});continue}P(t,`utf-8`)===P(n,`utf-8`)?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`})}let o=di(r);for(let e of o)n.sourceFiles.includes(e)||a.push({file:e,status:`added`});return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function ci(e,t){let n=ii(e,t),r=K(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of di(r))o.add(e);for(let e of o){let t=w(i,e),n=S(r,e),o=M(t),s=M(n);if(!s&&o){a.push({file:e,status:`deleted`});continue}if(s&&!o){let t=P(n,`utf-8`);a.push({file:e,status:`added`,diff:t.split(`
|
|
57
57
|
`).map(e=>`+${e}`).join(`
|
|
58
|
-
`)});continue}if(!s||!o)continue;let c=P(t,`utf-8`),l=P(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:
|
|
58
|
+
`)});continue}if(!s||!o)continue;let c=P(t,`utf-8`),l=P(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:fi(c,l)})}return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function li(e,t){let n=ii(e,t),r=K(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of di(r))o.add(e);for(let e of o){let t=S(r,e);if(!M(t))continue;let n=w(i,e);N(S(n,`..`),{recursive:!0}),j(t,n),a.push(e)}return ne(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function ui(e,t){let n=K(e,t);return M(n)?(ne(n,{recursive:!0,force:!0}),!0):!1}function di(e){let t=[];function n(r){for(let i of F(r)){if(i===ni)continue;let a=S(r,i);L(a).isDirectory()?n(a):t.push(C(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function fi(e,t){let n=e.split(`
|
|
59
59
|
`),r=t.split(`
|
|
60
60
|
`),i=[],a=Math.max(n.length,r.length);for(let e=0;e<a;e++){let t=n[e],a=r[e];t===a?i.push(` ${t??``}`):(t!==void 0&&i.push(`-${t}`),a!==void 0&&i.push(`+${a}`))}return i.join(`
|
|
61
|
-
`)}const
|
|
62
|
-
`),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of
|
|
63
|
-
`)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=
|
|
64
|
-
`)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=
|
|
65
|
-
`)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=
|
|
61
|
+
`)}const pi=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),mi=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function hi(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`]}=e,r=bi(t,n),i=[];for(let e of r){let t=P(e,`utf8`),n=gi(C(process.cwd(),e),t),r=await yi(t,b(e));r!==void 0&&(n.cognitiveComplexity=r),i.push(n)}i.sort((e,t)=>t.complexity-e.complexity);let a=i.reduce((e,t)=>e+t.lines.total,0),o=i.reduce((e,t)=>e+t.lines.code,0),s=i.reduce((e,t)=>e+t.complexity,0),c=i.reduce((e,t)=>e+t.functions,0),l=i[0]??{path:``,complexity:0};return{files:i,summary:{totalFiles:i.length,totalLines:a,totalCodeLines:o,avgComplexity:i.length>0?Math.round(s/i.length*10)/10:0,maxComplexity:{file:l.path,value:l.complexity},totalFunctions:c}}}function gi(e,t){let n=t.split(`
|
|
62
|
+
`),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of mi){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const _i=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),vi=new Set([`if_statement`,`if_expression`,`for_statement`,`for_in_statement`,`enhanced_for_statement`,`for_expression`,`while_statement`,`while_expression`,`do_statement`,`switch_statement`,`match_expression`,`try_statement`,`catch_clause`,`except_clause`,`lambda`,`lambda_expression`,`arrow_function`]);async function yi(e,t){let n=D.get();if(!(!n||!E.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=_i.has(e.type),r=vi.has(e.type);n&&(i+=1+t);let o=r?t+1:t;for(let t=0;t<e.childCount;t++){let n=e.child(t);n&&a(n,o)}}return a(r.rootNode,0),i}catch{return}}function bi(e,t){try{if(L(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let n=[];function r(e){for(let i of F(e)){if(pi.has(i))continue;let a=S(e,i);L(a).isDirectory()?r(a):t.includes(b(i).toLowerCase())&&n.push(a)}}return r(e),n.sort(),n}const xi=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),Si=[{glob:/\.env(?:\.\w+)?$/,type:`env`},{glob:/\.env\.example$/,type:`env`},{glob:/package\.json$/,type:`package-json`},{glob:/^(?:app|config|settings|default)\.(?:json|ya?ml|toml)$/i,type:`config`},{glob:/docker-compose\.ya?ml$/,type:`docker`},{glob:/cdk\.json$/,type:`cdk`},{glob:/turbo\.json$/,type:`tooling`},{glob:/application\.(?:properties|ya?ml)$/i,type:`spring`},{glob:/settings\.py$/,type:`django`},{glob:/\.flaskenv$/,type:`env`},{glob:/appsettings\.(?:\w+\.)?json$/i,type:`dotnet`}];async function Ci(e,t){let n=[],r=await wi(e),i=/aikit\.config\.json$/;for(let t of r)try{let r=C(e,t).replace(/\\/g,`/`);if(i.test(r))continue;let a=await p(t,`utf-8`),o=Ti(t);if(r.split(`/`).length-1>1&&o===`tooling`)continue;let s=Di(a,o);s.length>0&&n.push({file:r,type:o,values:s})}catch{}return ki(n,t)}async function wi(e){let t=[],n=async(e,r)=>{if(!(r>3))try{let i=await m(e,{withFileTypes:!0});for(let a of i){if(xi.has(a.name))continue;let i=S(e,a.name);a.isDirectory()&&!a.name.startsWith(`.`)?await n(i,r+1):a.isFile()&&Si.some(e=>e.glob.test(a.name))&&t.push(i)}}catch{}};return await n(e,0),t}function Ti(e){let t=v(e);for(let e of Si)if(e.glob.test(t))return e.type;return`unknown`}const Ei=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function Di(e,t){let n=[];if(t===`env`)for(let t of e.split(`
|
|
63
|
+
`)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=Ei.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
|
|
64
|
+
`)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=Ei.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{Oi(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
|
|
65
|
+
`)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=Ei.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function Oi(e,t,n,r){if(!(r>3)&&typeof e==`object`&&e&&!Array.isArray(e))for(let[i,a]of Object.entries(e)){let e=t?`${t}.${i}`:i;if(typeof a==`object`&&a&&!Array.isArray(a))Oi(a,e,n,r+1);else{let t=Ei.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function ki(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
|
|
66
66
|
`);n.push(`**${e.length} config files** found\n`);let r=new Map;for(let t of e)r.has(t.type)||r.set(t.type,[]),r.get(t.type)?.push(t);for(let[e,t]of r){if(e===`package-json`&&t.length>2){n.push(`### ${e}\n`);let r=t.find(e=>e.file===`package.json`);if(r){n.push(`#### ${r.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of r.values.slice(0,50)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}let i=t.filter(e=>e.file!==`package.json`);if(i.length>0){let e=new Map;for(let t of i)for(let n of t.values){let t=`${n.key}=${n.value}`;e.set(t,(e.get(t)??0)+1)}let t=Math.max(2,Math.floor(i.length*.5));n.push(`#### Sub-packages (${i.length} packages)\n`);let r=[...e.entries()].filter(([,e])=>e>=t).map(([e])=>{let[t,...n]=e.split(`=`);return{key:t,value:n.join(`=`)}});if(r.length>0){n.push(`**Common scripts** (shared by most sub-packages):
|
|
67
67
|
`),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let e of r)n.push(`| ${e.key} | ${e.value.replace(/\|/g,`\\|`)} |`);n.push(``)}let a=new Map;for(let n of i){let r=n.values.filter(n=>{let r=`${n.key}=${n.value}`;return(e.get(r)??0)<t});if(r.length===0)continue;let i=r.map(e=>`${e.key}=${e.value}`).sort().join(`||`),o=a.get(i);o?o.files.push(n.file):a.set(i,{files:[n.file],entries:r.map(e=>({key:e.key,value:e.value}))})}for(let[,e]of a){e.files.length>1?n.push(`**${e.files.length} packages** (${e.files.map(e=>e.split(`/`).slice(-2,-1)[0]||e).join(`, `)}):`):n.push(`**${e.files[0]}**:`),n.push(`| Key | Value |`),n.push(`|-----|-------|`);for(let t of e.entries)n.push(`| ${t.key} | ${t.value.replace(/\|/g,`\\|`)} |`);n.push(``)}}continue}if(t.length>3){let r=t.map(e=>e.values.map(e=>`${e.key}=${e.value}`).sort().join(`||`)),i=r.sort((e,t)=>r.filter(e=>e===t).length-r.filter(t=>t===e).length)[0];if(r.filter(e=>e===i).length>2){n.push(`### ${e}\n`);let a=t[r.indexOf(i)],o=t.filter((e,t)=>r[t]===i).map(e=>e.file),s=t.filter((e,t)=>r[t]!==i);n.push(`**${o.length} identical files**: ${o.join(`, `)}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let e of a.values.slice(0,30)){let t=e.value.replace(/\|/g,`\\|`);n.push(`| ${e.key} | ${t} | ${e.sensitive?`⚠️ yes`:`no`} |`)}n.push(``);for(let e of s){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,30)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}n.push(``)}continue}}n.push(`### ${e}\n`);for(let e of t){n.push(`#### ${e.file}\n`),n.push(`| Key | Value | Sensitive |`),n.push(`|-----|-------|-----------|`);for(let t of e.values.slice(0,50)){let e=t.value.replace(/\|/g,`\\|`);n.push(`| ${t.key} | ${e} | ${t.sensitive?`⚠️ yes`:`no`} |`)}e.values.length>50&&n.push(`\n_...and ${e.values.length-50} more values._`),n.push(``)}}let i=e.reduce((e,t)=>e+t.values.filter(e=>e.sensitive).length,0);return i>0&&n.push(`\n**⚠️ ${i} sensitive values detected** (values masked).`),n.join(`
|
|
68
|
-
`)}const
|
|
68
|
+
`)}const Ai=new Set([`test`,`tests`,`__tests__`,`spec`,`specs`,`__mocks__`,`__fixtures__`,`fixtures`,`test-utils`]);function q(e){return e.replace(/\\/g,`/`).split(`/`).some(e=>Ai.has(e))||/\.(test|spec)\.[jt]sx?$/.test(e)||/Test\.java$/.test(e)}function J(e){let t=e.split(`/`);if(t.length>=2&&[`packages`,`services`,`providers`,`apps`,`libs`].includes(t[0]))return`${t[0]}/${t[1]}`;let n=t.indexOf(`java`),r=t.indexOf(`kotlin`),i=n>=0?n:r;if(i>=0&&i+2<t.length){let e=t.slice(i+1);return[`com`,`org`,`net`,`io`,`dev`].includes(e[0])&&e.length>=3?e.slice(0,3).join(`/`):e.slice(0,2).join(`/`)}return t[0]===`src`&&t.length>=3?`${t[0]}/${t[1]}`:t[0]}function ji(e,t){if(t.has(e))return e;for(let n of[`.ts`,`.tsx`,`.js`,`.jsx`])if(t.has(`${e}${n}`))return`${e}${n}`;return t.has(`${e}/index.ts`)?`${e}/index.ts`:e}function Mi(e,t,n){let r=t.get(`symbols`),i=t.get(`entry-points`),a=t.get(`dependencies`),o=new Map;for(let[t,n]of e)if(!q(t))for(let[e,r]of n){if(q(e))continue;let n=J(t),i=J(e);if(n===i)continue;let a=`${n}|${i}`;o.set(a,(o.get(a)??0)+r.length)}if(o.size===0)return`## Architecture Diagram
|
|
69
69
|
|
|
70
70
|
No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){let[t,n]=e.split(`|`);s.add(t),s.add(n)}let c=new Map;if(r?.symbols)for(let e of r.symbols){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=J(t);c.set(n,(c.get(n)??0)+1)}let l=new Map;if(i?.entryPoints)for(let e of i.entryPoints){let t=J(e.filePath.replace(/\\/g,`/`)),n=l.get(t);n?(n.count++,e.trigger&&n.triggers.add(e.trigger)):l.set(t,{count:1,triggers:new Set(e.trigger?[e.trigger]:[])})}let u=[];if(a?.external){let e=a.external,t={"client-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"lib-dynamodb":{id:`dynamodb`,name:`DynamoDB`},"client-sqs":{id:`sqs`,name:`SQS`},"client-ses":{id:`ses`,name:`SES`},"client-sesv2":{id:`ses`,name:`SES`},"client-s3":{id:`s3`,name:`S3`},"client-eventbridge":{id:`eventbridge`,name:`EventBridge`},"client-sns":{id:`sns`,name:`SNS`},"client-secrets-manager":{id:`secrets`,name:`Secrets Manager`},"client-scheduler":{id:`scheduler`,name:`EventBridge Scheduler`},"client-apigatewaymanagementapi":{id:`apigw`,name:`API Gateway`},"client-cloudwatch":{id:`cloudwatch`,name:`CloudWatch`}},n=new Set;for(let r of Object.keys(e))for(let[e,i]of Object.entries(t))r.includes(e)&&!n.has(i.id)&&(n.add(i.id),u.push(i));u.sort((e,t)=>e.name.localeCompare(t.name))}let d=new Map;for(let e of[...s].sort()){let t=e.split(`/`)[0],n=d.get(t);n?n.push(e):d.set(t,[e])}let f=new Map;if(r?.symbols){let e=new Map;for(let t of r.symbols){let n=t.filePath.replace(/\\/g,`/`),r=J(n),i=n.match(/\.[^./]+$/)?.[0]||``;e.has(r)||e.set(r,new Map);let a=e.get(r);a.set(i,(a.get(i)??0)+1)}let t={".ts":`TypeScript`,".tsx":`TypeScript`,".js":`JavaScript`,".jsx":`JavaScript`,".java":`Java`,".kt":`Kotlin`,".scala":`Scala`,".py":`Python`,".go":`Go`,".rs":`Rust`,".cs":`C#`,".rb":`Ruby`,".php":`PHP`,".swift":`Swift`};for(let[n,r]of e){let e=``,i=0;for(let[t,n]of r)n>i&&(i=n,e=t);f.set(n,t[e]||`TypeScript`)}}let p=e=>e.replace(/[^a-zA-Z0-9]/g,`_`),m=[];m.push("```mermaid"),m.push(`C4Container`),m.push(` title C4 Container: ${n}`),m.push(``);let h=e=>{let t=[],n=l.get(e);n&&(t.push(`${n.count} handlers`),n.triggers.size>0&&t.push([...n.triggers].join(`, `)));let r=c.get(e);return r&&t.push(`${r} exports`),t.join(` · `)||``},g=e=>{let t=f.get(e)||`TypeScript`;if(e.startsWith(`infra`))return`CDK/${t}`;if(l.has(e)){let n=l.get(e);if(n?.triggers.has(`SQS`)||n?.triggers.has(`SNS`)||n?.triggers.has(`API Gateway`))return`Lambda/${t}`;if(n?.triggers.has(`HTTP Server`)||n?.triggers.has(`HTTP Endpoint`))return`Spring Boot/${t}`}return t};for(let[e,t]of[...d.entries()].sort()){let r=new Set([`com`,`org`,`net`,`io`,`dev`,`src`]).has(e)?n.charAt(0).toUpperCase()+n.slice(1):e.charAt(0).toUpperCase()+e.slice(1);if(t.length===1&&t[0]===e){let e=t[0];m.push(` Container(${p(e)}, "${e}", "${g(e)}", "${h(e)}")`)}else{m.push(` System_Boundary(${p(e)}_boundary, "${r}") {`);for(let e of t){let t=e.split(`/`).slice(1).join(`/`)||e;m.push(` Container(${p(e)}, "${t}", "${g(e)}", "${h(e)}")`)}m.push(` }`)}m.push(``)}if(u.length>0){for(let e of u)m.push(` System_Ext(ext_${e.id}, "${e.name}", "AWS")`);m.push(``)}let _=[...o.entries()].sort((e,t)=>t[1]-e[1]);for(let[e,t]of _.slice(0,30)){let[n,r]=e.split(`|`);m.push(` Rel(${p(n)}, ${p(r)}, "Uses", "${t} calls")`)}m.push("```");let v=`## C4 Container Diagram\n\n${m.join(`
|
|
71
71
|
`)}`,y=[];y.push("```mermaid"),y.push(`graph TB`);let b=new Set;for(let[,e]of l)for(let t of e.triggers)b.add(t);if(b.size>0){y.push(` subgraph Triggers["External Triggers"]`);for(let e of[...b].sort()){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t}(("${e}"))`)}y.push(` end`),y.push(``)}let x=[...s].filter(e=>l.has(e)).sort(),S=[...s].filter(e=>!l.has(e)).sort();if(x.length>0){y.push(` subgraph Services["Service Layer"]`);for(let e of x){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e,r=l.get(e);y.push(` ${t}["${n} (${r?.count??0} handlers)"]`)}y.push(` end`),y.push(``)}if(S.length>0){y.push(` subgraph Libraries["Shared Libraries"]`);for(let e of S){let t=`flow_${p(e)}`,n=e.includes(`/`)?e.split(`/`).pop()??e:e;y.push(` ${t}["${n}"]`)}y.push(` end`),y.push(``)}if(u.length>0){y.push(` subgraph External["AWS Services"]`);for(let e of u)y.push(` flow_ext_${e.id}[("${e.name}")]`);y.push(` end`),y.push(``)}for(let e of x){let t=l.get(e);if(!t)continue;let n=`flow_${p(e)}`;for(let e of t.triggers){let t=`trigger_${e.replace(/[^a-zA-Z0-9]/g,`_`)}`;y.push(` ${t} --> ${n}`)}}let C=_.filter(([e])=>{let[t,n]=e.split(`|`);return l.has(t)&&!l.has(n)});for(let[e,t]of C.slice(0,15)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}let w=_.filter(([e])=>{let[t,n]=e.split(`|`);return!l.has(t)&&!l.has(n)});for(let[e,t]of w.slice(0,10)){let[n,r]=e.split(`|`);y.push(` flow_${p(n)} -->|${t}| flow_${p(r)}`)}y.push("```");let T=`## Architectural Flow\n\n${y.join(`
|
|
@@ -73,12 +73,12 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
|
|
|
73
73
|
|
|
74
74
|
---
|
|
75
75
|
|
|
76
|
-
`)}const
|
|
77
|
-
`);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=
|
|
78
|
-
`)}function
|
|
79
|
-
`);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=
|
|
76
|
+
`)}const Ni={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`};function Pi(e,t,n,r){let i=[`Analysis baselines for **${n}** have been generated.`];t===`generate`?i.push("Individual results are in the sibling `.md` and `.json` files in this directory.",``):i.push(`Results are stored in the AI Kit vector store.`,``);let a=r.get(`symbols`),o=r.get(`dependencies`),s=r.get(`patterns`),c=r.get(`entry-points`),l=a?.totalCount??0,u=a?.exportedCount??0,d=o?.totalImports??0,f=c?.total??0,p=(s?.patterns??[]).map(e=>e.pattern),m=p.some(e=>e.startsWith(`Spring`)),h=p.includes(`AWS CDK`)||p.includes(`CDK IaC`),g=p.includes(`Maven`),_=p.includes(`Serverless`)||f>3,v=o?.external?Object.keys(o.external):[],y=v.some(e=>[`express`,`fastify`,`next`,`react`,`vitest`,`jest`].includes(e))||d>0,b=v.some(e=>[`turbo`,`lerna`,`nx`].includes(e))||p.includes(`Monorepo`);if(i.push(`### Project Profile`,``),i.push(`- **${l} symbols** (${u} exported), **${d} imports**, **${f} entry ${f===1?`point`:`points`}**`),p.length>0&&i.push(`- **Detected**: ${p.slice(0,8).join(`, `)}`),i.push(``),l===0&&d===0&&f===0)return i.push(`> **Note:** This project appears to be empty or contains no analyzable source code.`,`> Run onboard again after adding source files.`),i.join(`
|
|
77
|
+
`);let x=e.filter(e=>e.status===`success`),S=e.filter(e=>e.status===`failed`);i.push(`### Completed Analyses`,``);for(let e of x){let n=Ni[e.name]??e.name,r=e.output.length>1e3?`${Math.round(e.output.length/1024)}KB`:`${e.output.length}B`;t===`generate`?i.push(`- ✓ [${n}](./${e.name}.md) (${r})`):i.push(`- ✓ ${n} (${r})`)}if(S.length>0){i.push(``,`### Failed Analyses`,``);for(let e of S)i.push(`- ✗ ${e.name}: ${e.error}`)}i.push(``,`### Recommended Reading Order`,``,"1. **Start with** `synthesis-guide.md` (this file) → `entry-points.md` → `patterns.md`","2. **Module graph** via `code-map.md` — cross-package call edges with function names","3. **Architecture** via `diagram.md` (C4 Container) → `dependencies.md`","4. **Browse structure** via `structure.md` for file layout","5. **API surface** via `symbols.md` — file paths + exported symbols (capped at 80KB)","6. **Reference**: `config-values.md` (config reference)",``,`> **Size guidance:** Total output is ~`);let C=x.reduce((e,t)=>e+t.output.length,0)/1024;return i[i.length-1]+=`${Math.round(C)}KB. Focus on code-map.md + entry-points.md + diagram.md (~${Math.round((x.find(e=>e.name===`code-map`)?.output.length??0)/1024+(x.find(e=>e.name===`entry-points`)?.output.length??0)/1024+(x.find(e=>e.name===`diagram`)?.output.length??0)/1024)}KB) for maximum signal-to-token ratio.`,i.push(``,`### Synthesize Knowledge`,``,"Produce the following `aikit_remember` entries:",``),i.push("1. **Architecture Summary** (category: `architecture`)"),b?(i.push(` - Package boundaries, dependency graph between packages`),i.push(` - Shared vs service-specific code`)):_?(i.push(` - Lambda functions, triggers, event flow`),i.push(` - Infrastructure patterns (queues, tables, APIs)`)):m?(i.push(` - Controller → Service → Repository layers`),i.push(` - Spring configuration and profiles`)):(i.push(` - Layer structure, dependency flow`),i.push(` - Key design decisions`)),i.push(``),i.push("2. **Domain Model** (category: `architecture`)"),i.push(` - Key entities/types and their relationships`),i.push(` - Data flow from entry points through processing`),i.push(``),i.push("3. **Conventions** (category: `conventions`)"),i.push(` - Naming patterns, file organization, testing approach`),h&&i.push(` - CDK construct patterns and stack organization`),y&&i.push(` - Build tooling, package manager, module system`),g&&i.push(` - Maven module structure, dependency management`),i.push(``,`### Using AI Kit Tools`,``,`This project has an AI Kit MCP server with tools for search, analysis, memory, and more.`,"`aikit init` has already created `.github/copilot-instructions.md` and `AGENTS.md` with the complete tool reference.","If not, run `npx @vpxa/aikit init` to generate them.",``,`**Workflow pattern — use on every task:**`,``,"```",`aikit_search({ query: "your task keywords" }) # Recall prior decisions`,`aikit_scope_map({ task: "what you are doing" }) # Get a reading plan`,`# ... do the work ...`,`aikit_check({}) # Typecheck + lint`,`aikit_test_run({}) # Run tests`,`aikit_remember({ title: "What I learned", category: "decisions" }) # Persist`,"```"),i.join(`
|
|
78
|
+
`)}function Fi(e,t,n){let r=e.get(`dependencies`),i=e.get(`symbols`),a=e.get(`entry-points`),o=[`## Code Map: ${t}\n`];if(!r&&!i)return o.push(`No dependency or symbol data available.`),o.join(`
|
|
79
|
+
`);let s=r?.reverseGraph??{},c=i?.symbols??[],l=a?.entryPoints??[],u=new Map;for(let e of c){if(!e.exported)continue;let t=e.filePath.replace(/\\/g,`/`);if(q(t))continue;let n=u.get(t);n?n.push({name:e.name,kind:e.kind}):u.set(t,[{name:e.name,kind:e.kind}])}let d=new Map;for(let[e,t]of Object.entries(s)){let n=ji(e.replace(/\\/g,`/`),u),r=t.map(e=>e.replace(/\\/g,`/`)).filter(e=>!q(e));if(r.length===0)continue;let i=d.get(n);if(i)for(let e of r)i.add(e);else d.set(n,new Set(r))}let f=new Map;for(let e of l)f.set(e.filePath.replace(/\\/g,`/`),{name:e.name,trigger:e.trigger});let p=new Map,m=new Map;if(n)for(let[e,t]of n){if(q(e))continue;let n=J(e);for(let[r,i]of t){if(q(r)||n===J(r))continue;let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(r,i);let a=m.get(r),o={file:e,symbols:i};a?a.push(o):m.set(r,[o])}}let h=new Set;for(let e of f.keys())h.add(e);for(let e of p.keys())h.add(e);for(let e of m.keys())h.add(e);if(!n)for(let e of u.keys()){let t=d.get(e);t&&t.size>=3&&h.add(e)}let g=new Map;for(let e of h){let t=J(e),n=g.get(t);n?n.push(e):g.set(t,[e])}let _=[...g.entries()].sort((e,t)=>e[0].localeCompare(t[0])),v=n?`AST call graph`:`import analysis`,y=n?`, ${p.size} cross-package callers`:``;o.push(`**${h.size} key modules** (${v}${y})\n`),o.push(`**Legend:** ⚡ Entry point | 📤 Exports | → Calls (outgoing) | ← Called by (incoming) | ➡ Used by (import)
|
|
80
80
|
`);for(let[e,t]of _){t.sort(),o.push(`### ${e}/\n`);for(let r of t){let t=u.get(r),i=f.get(r),a=p.get(r),s=m.get(r),c=d.get(r),l=r.startsWith(`${e}/`)?r.slice(e.length+1):r;if(o.push(`**${l}**`),i&&o.push(` ⚡ Entry: \`${i.name}\`${i.trigger?` (${i.trigger})`:``}`),t&&t.length>0){let e=t.slice(0,8).map(e=>`${e.name}`).join(`, `),n=t.length>8?` (+${t.length-8})`:``;o.push(` 📤 ${e}${n}`)}if(a&&a.size>0){let t=[...a.entries()].sort((e,t)=>t[1].length-e[1].length);for(let[n,r]of t.slice(0,4)){let t=n.startsWith(`${e}/`)?n.slice(e.length+1):n;o.push(` → ${t}: ${r.slice(0,5).join(`, `)}${r.length>5?`…`:``}`)}t.length>4&&o.push(` → +${t.length-4} more targets`)}if(s&&s.length>0){for(let t of s.slice(0,4)){let n=t.file.startsWith(`${e}/`)?t.file.slice(e.length+1):t.file;o.push(` ← ${n}: ${t.symbols.slice(0,4).join(`, `)}${t.symbols.length>4?`…`:``}`)}s.length>4&&o.push(` ← +${s.length-4} more callers`)}else if(!n&&c&&c.size>0){let e=[...c].filter(e=>!q(e));e.length<=3?o.push(` ➡ Used by: ${e.join(`, `)}`):o.push(` ➡ Used by: ${e.slice(0,3).join(`, `)} (+${e.length-3} more)`)}o.push(``)}}return o.join(`
|
|
81
|
-
`)}const
|
|
81
|
+
`)}const Ii={structure:`Project Structure`,dependencies:`Dependencies`,"entry-points":`Entry Points`,symbols:`Symbols`,patterns:`Patterns`,diagram:`C4 Container Diagram`,"code-map":`Code Map (Module Graph)`,"config-values":`Configuration Values`,"synthesis-guide":`Synthesis Guide`,"api-surface":`API Surface`,"type-inventory":`Type Inventory`};function Li(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# API Surface
|
|
82
82
|
|
|
83
83
|
*No symbol data available.*
|
|
84
84
|
`;let n=t.symbols.filter(e=>e.exported);if(n.length===0)return`# API Surface
|
|
@@ -86,7 +86,7 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
|
|
|
86
86
|
*No exported symbols found.*
|
|
87
87
|
`;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# API Surface
|
|
88
88
|
`];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){e.decorators?.length&&i.push(e.decorators.join(` `));let t=e.signature??``,n=e.returnType?`: ${e.returnType}`:``;if(e.kind===`function`||e.kind===`method`)i.push(`### \`${e.name}${t}${n}\``);else if(e.kind===`class`)i.push(`### class \`${e.name}\`${t?` ${t}`:``}`);else if(e.kind===`interface`||e.kind===`type`){let t=e.typeBody?` ${e.typeBody}`:``;i.push(`### ${e.kind} \`${e.name}\`${t}`)}else i.push(`### ${e.kind} \`${e.name}\`${t?`: ${t}`:``}`);e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(``)}}let a=i.join(`
|
|
89
|
-
`);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function
|
|
89
|
+
`);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}function Ri(e){let t=e.get(`symbols`);if(!t?.symbols?.length)return`# Type Inventory
|
|
90
90
|
|
|
91
91
|
*No symbol data available.*
|
|
92
92
|
`;let n=t.symbols.filter(e=>e.exported&&(e.kind===`interface`||e.kind===`type`||e.kind===`enum`));if(n.length===0)return`# Type Inventory
|
|
@@ -94,24 +94,24 @@ No cross-package dependencies detected.`;let s=new Set;for(let e of o.keys()){le
|
|
|
94
94
|
*No exported types/interfaces found.*
|
|
95
95
|
`;let r=new Map;for(let e of n){let t=r.get(e.filePath)??[];t.push(e),r.set(e.filePath,t)}let i=[`# Type Inventory
|
|
96
96
|
`];for(let[e,t]of[...r.entries()].sort(([e],[t])=>e.localeCompare(t))){i.push(`## ${e}\n`);for(let e of t){let t=e.typeBody??`*body not available*`;e.jsdoc&&i.push(`> ${e.jsdoc}`),i.push(`### ${e.kind} \`${e.name}\``),i.push("```"),i.push(t),i.push("```\n")}}let a=i.join(`
|
|
97
|
-
`);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function
|
|
98
|
-
`),`utf-8`)}let V=[];V.push({title:`Onboard: ${d} project overview`,content:ie.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,d]});let ae=O.find(e=>e.name===`patterns`);return ae?.status===`success`&&ae.output&&V.push({title:`Onboard: ${d} detected patterns`,content:ae.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,d]}),L&&V.push({title:`Onboard: ${d} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,d]}),{path:u,mode:p,steps:O,outDir:p===`generate`?g:void 0,totalDurationMs:Date.now()-l,autoRemember:V}}const Y=new Map;function
|
|
99
|
-
`),`utf-8`)))}return!o&&d.length>0&&yt(`rename`,d,`rename: ${t} → ${n}, ${u} files`),{oldName:t,newName:n,changes:l,filesModified:u,dryRun:o}}const
|
|
100
|
-
`).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function
|
|
101
|
-
`).filter(Boolean);if(n.length<=
|
|
102
|
-
`)}\n`,`utf-8`),r}function
|
|
103
|
-
`)}\n`}function
|
|
104
|
-
`)}function
|
|
97
|
+
`);return a.length>1e5?`${a.slice(0,1e5)}\n\n*[truncated]*`:a}async function zi(c){let l=Date.now(),u=w(c.path),d=v(u),p=c.mode??`generate`,g=c.outDir??S(u,z.aiContext),y=new i,b=new e,x=new a,C=new r,T=new n,E=new t,D=[{name:`structure`,fn:()=>y.analyze(u,{format:`markdown`,maxDepth:3,sourceOnly:!0})},{name:`dependencies`,fn:()=>b.analyze(u,{format:`markdown`})},{name:`entry-points`,fn:()=>T.analyze(u)},{name:`symbols`,fn:()=>x.analyze(u,{format:`markdown`})},{name:`patterns`,fn:()=>C.analyze(u)},{name:`diagram`,fn:()=>E.analyze(u,{diagramType:`architecture`})}],ee=await Promise.allSettled(D.map(async e=>{let t=Date.now(),n=await e.fn();return{name:e.name,result:n,durationMs:Date.now()-t}})),O=[],k=new Map,A=new Map;for(let e of ee)if(e.status===`fulfilled`){let{name:t,result:n,durationMs:r}=e.value,i=n;O.push({name:t,status:`success`,output:i.output,durationMs:r}),k.set(t,i.output),A.set(t,i.data)}else{let t=e.reason,n=D[ee.indexOf(e)].name;O.push({name:n,status:`failed`,output:``,durationMs:0,error:t.message})}let te=Date.now(),j=null;try{let e=await s(u);if((!e||e.edges.length===0)&&(e=await o(u)),e&&e.edges.length>0){j=new Map;for(let t of e.edges){let e=j.get(t.from);e||(e=new Map,j.set(t.from,e));let n=e.get(t.to);if(n)for(let e of t.symbols)n.includes(e)||n.push(e);else e.set(t.to,[...t.symbols])}}}catch{}let N=Date.now()-te,P=Date.now(),F=Fi(A,d,j),I=Date.now()-P+N;if(O.push({name:`code-map`,status:`success`,output:F,durationMs:I}),k.set(`code-map`,F),j&&j.size>0){let e=Mi(j,A,d),t=O.find(e=>e.name===`diagram`);t&&(t.output=e,k.set(`diagram`,e))}let ne=Date.now(),L=await Ci(u,d),re=Date.now()-ne;O.push({name:`config-values`,status:`success`,output:L,durationMs:re}),k.set(`config-values`,L);let ie=Pi(O,p,d,A);O.push({name:`synthesis-guide`,status:`success`,output:ie,durationMs:0}),k.set(`synthesis-guide`,ie);let R=Li(A);O.push({name:`api-surface`,status:`success`,output:R,durationMs:0}),k.set(`api-surface`,R);let B=Ri(A);if(O.push({name:`type-inventory`,status:`success`,output:B,durationMs:0}),k.set(`type-inventory`,B),p===`generate`){if(M(g))for(let e of await m(g))(e.endsWith(`.md`)||e.endsWith(`.json`))&&await h(S(g,e),{force:!0});await f(g,{recursive:!0});let e=new Date().toISOString();for(let[t,n]of k){let r=S(g,`${t}.md`),i=n.replaceAll(u,d);await _(r,`<!-- Generated: ${e} -->\n<!-- Project: ${d} -->\n\n`+i,`utf-8`)}let t=[`<!-- Generated: ${e} -->`,`<!-- Project: ${d} -->`,``,`# ${d} — Codebase Knowledge`,``,`## Contents`,``];for(let e of O){let n=`${e.name}.md`,r=Ii[e.name]??e.name,i=e.status===`success`?`✓`:`✗`,a=e.durationMs>0?` (${e.durationMs}ms)`:``;t.push(`- ${i} [${r}](./${n})${a}`)}t.push(``),await _(S(g,`README.md`),t.join(`
|
|
98
|
+
`),`utf-8`)}let V=[];V.push({title:`Onboard: ${d} project overview`,content:ie.slice(0,2e3),category:`conventions`,tags:[`onboard`,`project-overview`,d]});let ae=O.find(e=>e.name===`patterns`);return ae?.status===`success`&&ae.output&&V.push({title:`Onboard: ${d} detected patterns`,content:ae.output.slice(0,1500),category:`patterns`,tags:[`onboard`,`patterns`,d]}),L&&V.push({title:`Onboard: ${d} config and commands`,content:L.slice(0,1500),category:`conventions`,tags:[`onboard`,`config`,`commands`,d]}),{path:u,mode:p,steps:O,outDir:p===`generate`?g:void 0,totalDurationMs:Date.now()-l,autoRemember:V}}const Y=new Map;function Bi(e,t,n=[],r){if(Y.has(e))throw Error(`Process "${e}" is already running. Stop it first.`);if(Y.size>=20)throw Error(`Too many managed processes (max 20). Stop some first.`);let i=/[;|&`$(){}[\]!<>\\]/,a=[t,...n].join(` `);if(i.test(a))throw Error(`Command contains disallowed shell metacharacters`);let o=d(a,{cwd:r?.cwd??process.cwd(),shell:!0,stdio:[`ignore`,`pipe`,`pipe`]}),s={id:e,command:t,args:n,pid:o.pid??void 0,status:`running`,startedAt:new Date().toISOString(),logs:[]},c=e=>{let t=e.toString().split(/\r?\n/).filter(Boolean);s.logs.push(...t),s.logs.length>200&&(s.logs=s.logs.slice(-200))};return o.stdout?.on(`data`,c),o.stderr?.on(`data`,c),o.on(`exit`,t=>{s.status=t===0?`stopped`:`error`,s.exitCode=t??void 0,setTimeout(()=>Y.delete(e),3e4)}),o.on(`error`,e=>{s.status=`error`,s.logs.push(`[error] ${e.message}`)}),Y.set(e,{proc:o,info:s}),s}function Vi(e){let t=Y.get(e);if(!t)return;t.proc.kill(`SIGTERM`);let n=setTimeout(()=>{try{t.proc.kill(`SIGKILL`)}catch{}},5e3);return t.proc.once(`exit`,()=>clearTimeout(n)),t.info.status=`stopped`,Y.delete(e),t.info}function Hi(e){return Y.get(e)?.info}function Ui(){return[...Y.values()].map(e=>e.info)}function Wi(e,t){let n=Y.get(e);return n?t?n.info.logs.slice(-t):n.info.logs:[]}function Gi(e){return w(B(e??process.cwd()),`queue.json`)}function X(e){let t=Gi(e);if(!M(t))return{};try{return JSON.parse(P(t,`utf-8`))}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function Z(e,t){let n=Gi(t),r=y(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Ki(){return`q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function qi(e,t){let n=X(t);if(n[e])throw Error(`Queue "${e}" already exists`);let r={name:e,items:[]};return n[e]=r,Z(n,t),r}function Ji(e,t,n,r){let i=X(r);i[e]||(i[e]={name:e,items:[]});let a=new Date().toISOString(),o={id:Ki(),title:t,status:`pending`,data:n,createdAt:a,updatedAt:a};if(i[e].items.length>=500)throw Error(`Queue "${e}" has reached the maximum of 500 items. Clear completed items with queue({ action: "clear" }) before adding more.`);return i[e].items.push(o),Z(i,r),o}function Yi(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.find(e=>e.status===`pending`);return i?(i.status=`in-progress`,i.updatedAt=new Date().toISOString(),Z(n,t),i):null}function Xi(e,t,n){let r=X(n),i=r[e];if(!i)throw Error(`Queue "${e}" does not exist`);let a=i.items.find(e=>e.id===t);if(!a)throw Error(`Item "${t}" not found in queue "${e}"`);return a.status=`done`,a.updatedAt=new Date().toISOString(),Z(r,n),a}function Zi(e,t,n,r){let i=X(r),a=i[e];if(!a)throw Error(`Queue "${e}" does not exist`);let o=a.items.find(e=>e.id===t);if(!o)throw Error(`Item "${t}" not found in queue "${e}"`);return o.status=`failed`,o.error=n,o.updatedAt=new Date().toISOString(),Z(i,r),o}function Qi(e,t){return X(t)[e]??null}function $i(e){let t=X(e);return Object.values(t).map(e=>({name:e.name,pending:e.items.filter(e=>e.status===`pending`).length,done:e.items.filter(e=>e.status===`done`).length,failed:e.items.filter(e=>e.status===`failed`).length,total:e.items.length}))}function ea(e,t){let n=X(t),r=n[e];if(!r)throw Error(`Queue "${e}" does not exist`);let i=r.items.length;r.items=r.items.filter(e=>e.status===`pending`||e.status===`in-progress`);let a=i-r.items.length;return Z(n,t),a}function ta(e,t){let n=X(t);return n[e]?(delete n[e],Z(n,t),!0):!1}function na(e){let{pattern:t,flags:n=``,testStrings:r,mode:i=`match`,replacement:a=``}=e;try{let e=new RegExp(t,n);return{pattern:t,flags:n,results:r.map(r=>{let o=e.test(r);switch(i){case`match`:{let e=n.includes(`g`)?n:`${n}g`;return{input:r,matched:o,matches:[...r.matchAll(new RegExp(t,e))].map(e=>({full:e[0],groups:[...e.slice(1)],index:e.index??0}))}}case`replace`:return{input:r,matched:o,replaced:r.replace(new RegExp(t,n),a)};default:return{input:r,matched:o,split:r.split(new RegExp(t,n))}}}),valid:!0}}catch(e){return{pattern:t,flags:n,results:[],valid:!1,error:e.message}}}function ra(e){return e.replace(/\\/g,`/`)}function ia(e){return RegExp(`(^|[^A-Za-z0-9_$])(${H(e)})(?=[^A-Za-z0-9_$]|$)`,`g`)}async function aa(e){let{oldName:t,newName:n,rootPath:r,extensions:i=ut,exclude:a=[],dryRun:o=!1}=e;if(!t.trim())throw Error(`oldName must not be empty`);let s=ia(t),c=await gt(r,i,a),l=[],u=0,d=[];for(let e of c){let t=await p(e,`utf-8`),i=t.split(/\r?\n/),a=!1;for(let t=0;t<i.length;t++){let o=i[t];s.lastIndex=0;let c=o.replace(s,(e,t)=>(a=!0,`${t}${n}`));o!==c&&(i[t]=c,l.push({path:ra(C(r,e)),line:t+1,before:o,after:c}))}a&&(u+=1,o||(d.push({path:e,content:t}),await _(e,i.join(`
|
|
99
|
+
`),`utf-8`)))}return!o&&d.length>0&&yt(`rename`,d,`rename: ${t} → ${n}, ${u} files`),{oldName:t,newName:n,changes:l,filesModified:u,dryRun:o}}const oa=5e3;let sa=0;function ca(){return w(B(process.cwd()),`replay.jsonl`)}function la(e,t){return e.length<=t?e:`${e.slice(0,t-1)}…`}function ua(e){let t=ca();N(y(t),{recursive:!0});let n={...e,input:la(e.input,200),output:la(e.output,200)};te(t,`${JSON.stringify(n)}\n`,`utf-8`),sa++,sa>=100&&(sa=0,fa().catch(()=>{}))}function da(e={}){let t=ca(),n;try{n=P(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
|
|
100
|
+
`).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}async function fa(){let e=ca(),t;try{t=await p(e,`utf-8`)}catch{return 0}let n=t.trim().split(`
|
|
101
|
+
`).filter(Boolean);if(n.length<=oa)return 0;let r=n.length-oa;return await _(e,`${n.slice(-oa).join(`
|
|
102
|
+
`)}\n`,`utf-8`),r}function pa(){let e=ca();try{R(e,``,`utf-8`)}catch{}}function ma(e,t,n,r){let i=Date.now();return r().then(r=>(ua({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`ok`,output:typeof r==`string`?r:JSON.stringify(r??``)}),r)).catch(r=>{throw ua({ts:new Date().toISOString(),source:e,tool:t,input:typeof n==`string`?n:JSON.stringify(n),durationMs:Date.now()-i,status:`error`,output:r instanceof Error?r.message:String(r)}),r})}function ha(e){let t=[];return ga(e.data,e.schema,`$`,t),{valid:t.length===0,errors:t}}function ga(e,t,n,r){if(`type`in t){let i=t.type;if(!_a(e,i)){r.push({path:n,message:`Expected type "${i}"`,expected:i,received:va(e)});return}}if(`enum`in t){let i=t.enum;i.some(t=>JSON.stringify(t)===JSON.stringify(e))||r.push({path:n,message:`Must be one of: ${JSON.stringify(i)}`,received:JSON.stringify(e)})}if(`const`in t&&JSON.stringify(e)!==JSON.stringify(t.const)&&r.push({path:n,message:`Must equal ${JSON.stringify(t.const)}`,received:JSON.stringify(e)}),typeof e==`string`&&(`minLength`in t&&e.length<t.minLength&&r.push({path:n,message:`String too short (min: ${t.minLength})`,received:`length ${e.length}`}),`maxLength`in t&&e.length>t.maxLength&&r.push({path:n,message:`String too long (max: ${t.maxLength})`,received:`length ${e.length}`}),`pattern`in t))try{new RegExp(t.pattern).test(e)||r.push({path:n,message:`Does not match pattern: ${t.pattern}`})}catch(e){r.push({path:n,message:`Invalid pattern: ${e instanceof Error?e.message:String(e)}`})}if(typeof e==`number`&&(`minimum`in t&&e<t.minimum&&r.push({path:n,message:`Below minimum (${t.minimum})`,received:String(e)}),`maximum`in t&&e>t.maximum&&r.push({path:n,message:`Above maximum (${t.maximum})`,received:String(e)})),Array.isArray(e)&&(`minItems`in t&&e.length<t.minItems&&r.push({path:n,message:`Too few items (min: ${t.minItems})`,received:`length ${e.length}`}),`maxItems`in t&&e.length>t.maxItems&&r.push({path:n,message:`Too many items (max: ${t.maxItems})`,received:`length ${e.length}`}),`items`in t))for(let i=0;i<e.length;i++)ga(e[i],t.items,`${n}[${i}]`,r);if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e;if(`required`in t)for(let e of t.required)e in i||r.push({path:`${n}.${e}`,message:`Required property missing`});if(`properties`in t){let e=t.properties;for(let[t,a]of Object.entries(e))t in i&&ga(i[t],a,`${n}.${t}`,r)}if(`additionalProperties`in t&&t.additionalProperties===!1){let e=Object.keys(t.properties??{});for(let t of Object.keys(i))e.includes(t)||r.push({path:`${n}.${t}`,message:`Additional property not allowed`})}}}function _a(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&!Number.isNaN(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!0}}function va(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ya(e){return w(B(e??process.cwd()),`stash.json`)}function ba(e){let t=ya(e);if(!M(t))return{};try{let e=P(t,`utf-8`);return JSON.parse(e)}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}function xa(e,t){let n=ya(t),r=y(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Sa(e,t,n){let r=ba(n),i={key:e,value:t,type:typeof t,storedAt:new Date().toISOString()};return r[e]=i,xa(r,n),i}function Ca(e,t){return ba(t)[e]}function wa(e){return Object.values(ba(e))}function Ta(e,t){let n=ba(t);return e in n?(delete n[e],xa(n,t),!0):!1}function Ea(e){let t=ba(e),n=Object.keys(t).length;return xa({},e),n}const Da=`session-digest`;function Oa(e){return{scope:e.scope??`all`,since:e.since??``,last:e.last??50,focus:e.focus??``,mode:e.mode??`deterministic`,tokenBudget:e.tokenBudget??2e3,persist:e.persist??!0}}function ka(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(e=>e.length>0)}function Aa(e,t=96){let n=(typeof e==`string`?e:JSON.stringify(e??``)).replace(/\s+/g,` `).trim();return n.length<=t?n||`n/a`:`${n.slice(0,t-1)}…`}function ja(e){return e.split(`T`)[1]?.split(`.`)[0]??e}function Ma(e,t){return`${e||`session start`} → ${t.toISOString()}`}function Na(e,t){let n=e.tool.toLowerCase(),r=e.input.toLowerCase(),i=e.output.toLowerCase();return t.reduce((e,t)=>{let a=e;return n.includes(t)&&(a+=3),r.includes(t)&&(a+=2),i.includes(t)&&(a+=1),a},0)}function Pa(e,t){let n=ka(t);return n.length===0?[...e].sort((e,t)=>t.ts.localeCompare(e.ts)):[...e].sort((e,t)=>{let r=Na(e,n),i=Na(t,n);return r===i?t.ts.localeCompare(e.ts):i-r})}function Fa(e,t){return[...t.since?e.filter(e=>e.ts>=t.since):[...e]].sort((e,t)=>e.ts.localeCompare(t.ts)).slice(-t.last)}function Ia(e,t){return{replayEntries:t.replayEntries===void 0?da({last:e.last,since:e.since||void 0}):Fa(t.replayEntries,e),stashEntries:t.stashEntries??wa(),checkpoints:t.checkpoints??ct(),now:t.now??new Date,persistEntry:t.persistEntry??Sa}}function La(e,t,n){let r=Array.from(new Set(e.map(e=>e.tool))).sort((e,t)=>e.localeCompare(t));return{replayEntries:e.length,stashKeys:t.length,checkpoints:n.length,errors:e.filter(e=>e.status===`error`).length,toolsUsed:r}}function Ra(e){return e.errors>0?[`Review the failed tool calls before continuing the session.`,`Persist durable outcomes with remember() once the error path is resolved.`]:e.replayEntries===0&&e.stashKeys===0&&e.checkpoints===0?[`Session appears healthy with no recorded activity yet.`]:e.stashKeys>0||e.checkpoints>0?[`Session state is captured; consider converting durable findings into remember() entries.`]:[`Session appears healthy.`]}function za(e){return e.length===0?[`- No replay activity recorded.`]:e.map(e=>{let t=e.status===`ok`?`✓`:`✗`;return`- ${ja(e.ts)} ${t} **${e.tool}** (${e.durationMs}ms) — ${Aa(e.input,80)}`})}function Ba(e,t){return e.length===0?[`- No stash entries recorded.`]:e.map(e=>{let n=t?` — ${Aa(e.value,60)}`:``;return`- **${e.key}** (${e.type}) — stored ${e.storedAt}${n}`})}function Va(e){return e.length===0?[`- No checkpoints recorded.`]:e.map(e=>`- **${e.label}** (${e.id}) — ${e.createdAt}`)}function Ha(e){let t=e.filter(e=>e.status===`error`);return t.length===0?[`- No errors recorded.`]:t.map(e=>`- ${ja(e.ts)} **${e.tool}** — ${Aa(e.output,100)}`)}function Ua(e){let t=[`## Session Digest`,``,`**Window:** ${Ma(e.options.since,e.now)}`,`**Tool Calls:** ${e.stats.replayEntries} (${e.stats.errors} errors)`,`**Tools Used:** ${e.stats.toolsUsed.length>0?e.stats.toolsUsed.join(`, `):`none`}`];return e.options.scope!==`stash`&&t.push(``,`### Activity Timeline`,...e.activityLines),e.options.scope!==`tools`&&t.push(``,`### Stash State`,...e.stashLines,``,`### Checkpoints`,...e.checkpointLines),t.push(``,`### Error Summary`,...e.errorLines,``,`### Recommendations`),t.push(...e.recommendationLines.map(e=>`- ${e}`)),`${t.join(`
|
|
103
|
+
`)}\n`}function Wa(e){let t=e.options.tokenBudget*4,n=[...e.activityLines],r=[...e.stashLinesWithPreview],i=[...e.checkpointLines],a=[...e.errorLines],o=[...e.recommendationLines],s=()=>Ua({options:e.options,stats:e.stats,now:e.now,activityLines:n,stashLines:r,checkpointLines:i,errorLines:a,recommendationLines:o}),c=s();for(;c.length>t&&n.length>1;)n.pop(),c=s();for(c.length>t&&(r=[...e.stashLinesWithoutPreview],c=s());c.length>t&&r.length>1;)r.pop(),c=s();for(;c.length>t&&i.length>1;)i.pop(),c=s();for(;c.length>t&&a.length>1;)a.pop(),c=s();for(;c.length>t&&o.length>1;)o.pop(),c=s();return c.length<=t?c:`${c.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Ga(e,t,n){if(!t.persist)return e;let r={...e,persistedKey:Da};return n(Da,r),r}function Ka(e,t={}){let{replayEntries:n,stashEntries:r,checkpoints:i,now:a,persistEntry:o}=Ia(e,t),s=La(n,r,i);return Ga({digest:Wa({options:e,stats:s,now:a,activityLines:za(Pa(n,e.focus)),stashLinesWithPreview:Ba(r,!0),stashLinesWithoutPreview:Ba(r,!1),checkpointLines:Va(i),errorLines:Ha(n),recommendationLines:Ra(s)}),stats:s},e,o)}function qa(e={},t={}){return Ka(Oa(e),t)}async function Ja(e,t,n={}){let r=Oa(e),{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c}=Ia(r,n),l=La(i,a,o),u=JSON.stringify({window:{since:r.since||`session start`,now:s.toISOString()},scope:r.scope,focus:r.focus||void 0,replayEntries:i,stashEntries:a,checkpoints:o,stats:l},null,2),d=`You are a session summarizer for an AI coding assistant's MCP tool server. Compress the following tool activity log, stash state, and checkpoint information into a focused narrative summary. Highlight key decisions, important results, and potential next steps. Stay within ${r.tokenBudget} tokens.`;try{return Ga({digest:Aa(await t(u,d,r.tokenBudget),r.tokenBudget*4),stats:l},r,c)}catch{return Ka(r,{replayEntries:i,stashEntries:a,checkpoints:o,now:s,persistEntry:c})}}const Ya=()=>S(B(process.cwd()),`snippets`);function Xa(){let e=Ya();return M(e)||N(e,{recursive:!0}),e}function Za(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);if(!t)throw Error(`Invalid snippet name`);return t}function Qa(e){switch(e.action){case`save`:{if(!e.name||!e.code)throw Error(`name and code required for save`);let t=S(Xa(),`${Za(e.name)}.json`),n=null;if(M(t))try{n=JSON.parse(P(t,`utf8`))}catch(e){e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),n=null}let r=new Date().toISOString(),i={name:e.name,language:e.language??`text`,code:e.code,tags:e.tags??[],created:n?.created??r,updated:r},a=`${t}.tmp`;return R(a,JSON.stringify(i,null,2)),I(a,t),i}case`get`:{if(!e.name)throw Error(`name required for get`);let t=S(Ya(),`${Za(e.name)}.json`);if(!M(t))throw Error(`Snippet not found: ${e.name}`);try{return JSON.parse(P(t,`utf8`))}catch(n){throw n?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${n instanceof Error?n.message:String(n)}`),Error(`Snippet corrupted: ${e.name}`)}}case`list`:{let e=Xa();return{snippets:F(e).filter(e=>e.endsWith(`.json`)).flatMap(t=>{let n=S(e,t);try{let e=JSON.parse(P(n,`utf8`));return[{name:e.name,language:e.language,tags:e.tags,updated:e.updated}]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${n}: ${e instanceof Error?e.message:String(e)}`),[]}})}}case`search`:{if(!e.query)throw Error(`query required for search`);let t=e.query.toLowerCase(),n=Xa();return{snippets:F(n).filter(e=>e.endsWith(`.json`)).flatMap(e=>{let t=S(n,e);try{return[JSON.parse(P(t,`utf8`))]}catch(e){return e?.code!==`ENOENT`&&console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),[]}}).filter(e=>e.name.toLowerCase().includes(t)||e.tags.some(e=>e.toLowerCase().includes(t))||e.language.toLowerCase().includes(t)||e.code.toLowerCase().includes(t)).map(e=>({name:e.name,language:e.language,tags:e.tags,updated:e.updated}))}}case`delete`:{if(!e.name)throw Error(`name required for delete`);let t=S(Ya(),`${Za(e.name)}.json`);return M(t)?(re(t),{deleted:!0}):{deleted:!1}}default:throw Error(`Unknown action: ${e.action}`)}}async function $a(e,t){let{files:n,query:r,tier:i=`T1`,maxContentChars:a=800}=t,{cache:o}=t,s=i===`T2`?await e.embedQuery(r):null,c=await Promise.all(n.map(async t=>{try{let n=o?(await o.get(t)).content:await p(t,`utf-8`),r=U(n);if(n.includes(`\0`))return eo(t,i,`binary`,`binary file`,r);if(n.trim().length===0){let e=to({displayPath:no(t),tier:i,role:`empty`,deps:[],exports:[],unknowns:[],riskTier:`low`});return{path:t,tier:i,card:e,unknowns:[],riskTier:`low`,tokenEstimate:U(e),originalTokenEstimate:r}}let c=await Jn({path:t,content:n}),l=io(t,c),u=ao(n,c),d=co(t,c),f=lo(c),m=[...new Set(c.exports)].slice(0,5),h=to({displayPath:no(t),tier:i,role:l,deps:f,exports:m,unknowns:u,riskTier:d});if(i===`T2`&&s){let t=await fo(e,s,n,a);t.length>0&&(h=`${h}\nCONTEXT:\n${t}`)}return{path:t,tier:i,card:h,unknowns:u,riskTier:d,tokenEstimate:U(h),originalTokenEstimate:r}}catch(e){let n=e.code===`ENOENT`?`file missing`:`unreadable file`;return eo(t,i,e.code===`ENOENT`?`missing`:`unreadable`,n,0)}})),l=c.reduce((e,t)=>e+t.tokenEstimate,0),u=c.reduce((e,t)=>e+t.originalTokenEstimate,0);return{cards:c,totalTokenEstimate:l,totalOriginalTokenEstimate:u,compressionRatio:u===0?0:l/u}}function eo(e,t,n,r,i){let a=to({displayPath:no(e),tier:t,role:n,deps:[],exports:[],unknowns:[r],riskTier:`low`});return{path:e,tier:t,card:a,unknowns:[r],riskTier:`low`,tokenEstimate:U(a),originalTokenEstimate:i}}function to(e){let{displayPath:t,tier:n,role:r,deps:i,exports:a,unknowns:o,riskTier:s}=e;return[`[${n}: ${t}]`,`ROLE: ${r}`,`DEPS: ${ro(i)}`,`EXPORTS: ${ro(a)}`,`UNKNOWNS: ${ro(o,`; `)}`,`RISK: ${s}`].join(`
|
|
104
|
+
`)}function no(e){let t=C(process.cwd(),e).replace(/\\/g,`/`);return!t||t.startsWith(`..`)?v(e):t}function ro(e,t=`, `){return e.length>0?e.join(t):`none`}function io(e,t){let n=v(e),r=b(n).toLowerCase();return[`.json`,`.yaml`,`.yml`,`.env`].includes(r)||/config|settings/i.test(n)?`configuration`:/types?\.ts$|\.d\.ts$/i.test(n)?`type-definitions`:/schema/i.test(n)?`schema`:/test|spec/i.test(n)?`test`:/index\.[jt]sx?$/i.test(n)?`barrel-export`:/handler|controller|route/i.test(n)?`entry-point`:/model|entity/i.test(n)?`data-model`:/util|helper/i.test(n)?`utility`:/service|provider/i.test(n)?`service`:t.classes.length>0?`class-module`:t.interfaces.length>2?`type-definitions`:`implementation`}function ao(e,t){let n=[],r=new Set;for(let t of e.matchAll(/\/\/\s*(TODO|FIXME|HACK|XXX)\s*:?\s*(.+)?$/gm))oo(n,r,`${t[1]}: ${(t[2]??``).trim()}`.trim().replace(/:\s*$/,``));so(e)&&oo(n,r,`exported any usage`);for(let e of lo(t))oo(n,r,`cross-package import: ${e}`);return n.slice(0,3)}function oo(e,t,n){e.length>=3||!n||t.has(n)||(t.add(n),e.push(n))}function so(e){return[/export\s+(?:async\s+)?function\s+\w+[^\n{;]*\bany\b/g,/export\s+interface\s+\w+[\s\S]*?\{[\s\S]*?\bany\b[\s\S]*?\}/g,/export\s+type\s+\w+\s*=.*\bany\b/g,/export\s+const\s+\w+[^\n=]*\bany\b/g].some(t=>t.test(e))}function co(e,t){return/auth|token|permission|secret|credential|encrypt/i.test(e)?`high`:/types?\.ts$|schema|contract|\.d\.ts$/i.test(v(e))||t.exports.length>10?`medium`:`low`}function lo(e){return e.imports.map(uo).filter(e=>!!e).filter(e=>!e.startsWith(`./`)&&!e.startsWith(`../`)).slice(0,3)}function uo(e){let t=e.match(/from\s+['"]([^'"]+)['"]/);if(t)return t[1];let n=e.match(/^import\s+['"]([^'"]+)['"]/);return n?n[1]:null}async function fo(e,t,n,r){if(r<=0)return``;let i=qe(n,`paragraph`);if(i.length===0)return``;let a=await Promise.all(i.map(async(n,r)=>({index:r,text:n,score:Je(t,await e.embed(n))}))),o=[],s=0;for(let e of a.sort((e,t)=>t.score-e.score)){let t=r-s;if(t<=0)break;if(e.text.length<=t){o.push({index:e.index,text:e.text}),s+=e.text.length;continue}o.length===0&&(o.push({index:e.index,text:e.text.slice(0,t).trimEnd()}),s=r);break}return o.sort((e,t)=>e.index-t.index).map(e=>e.text).filter(e=>e.length>0).join(`
|
|
105
105
|
|
|
106
|
-
`)}async function
|
|
106
|
+
`)}async function po(e,t,n){let{name:r,limit:i=20,graphStore:a}=n,o=e.embedQuery?.bind(e)??e.embed.bind(e),s=[`export function ${r}`,`export class ${r}`,`export const ${r}`,`export interface ${r}`,`export type ${r}`,`export enum ${r}`].join(` | `),c=await t.search(await o(s),{limit:i*2}),l=RegExp(`^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function|class|const|let|interface|type|enum)\\s+${H(r)}\\b`,`m`),u;for(let e of c){if(!l.test(e.record.content))continue;let t=e.record.content.match(/export\s+(?:default\s+)?(?:async\s+)?(\w+)/)?.[1]??`unknown`;u={path:e.record.sourcePath,line:e.record.startLine,kind:t};let n=b(e.record.sourcePath);if(D.get()&&E.has(n))try{let t=(await k(e.record.content,n,e.record.sourcePath)).find(e=>e.name===r&&e.exported);t&&(u.kind=t.kind,t.signature&&(u.signature=t.signature))}catch{}break}let d=RegExp(`import\\s+.*\\b${H(r)}\\b.*from\\s+`,`m`),f=await t.search(await o(`import ${r} from`),{limit:i*3}),p=[],m=new Set;for(let e of f){let t=e.record.content.split(`
|
|
107
107
|
`);for(let n=0;n<t.length;n++){let r=t[n];if(!d.test(r))continue;let i=`${e.record.sourcePath}:${r.trim()}`;m.has(i)||(m.add(i),p.push({path:e.record.sourcePath,line:e.record.startLine+n,importStatement:r.trim()}))}}let h=RegExp(`\\b${H(r)}\\b`),g=await t.search(await o(r),{limit:i*3}),_=[],v=new Set;for(let e of g){if(_.length>=i)break;if(u&&e.record.sourcePath===u.path)continue;let t=e.record.content.split(`
|
|
108
|
-
`);for(let n=0;n<t.length;n++){let r=t[n];if(!h.test(r)||d.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(v.has(i))continue;v.add(i);let a,o=b(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await A(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}_.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let y;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:u&&(e.definingModule=u.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(y=e)}catch{}return{name:r,definedIn:u,importedBy:p.slice(0,i),referencedIn:_.slice(0,i),graphContext:y}}const
|
|
109
|
-
`).trim()||t.message||`Test run failed`}function
|
|
110
|
-
`);if(u&&!h){let e=await
|
|
108
|
+
`);for(let n=0;n<t.length;n++){let r=t[n];if(!h.test(r)||d.test(r))continue;let i=`${e.record.sourcePath}:${e.record.startLine+n}`;if(v.has(i))continue;v.add(i);let a,o=b(e.record.sourcePath);if(D.get()&&E.has(o))try{let t=await A(e.record.content,o,n+1);t.length>0&&(a=t[0].name)}catch{}_.push({path:e.record.sourcePath,line:e.record.startLine+n,context:r.trim().slice(0,120),scope:a});break}}let y;if(a)try{let e={importedByModules:[],siblingSymbols:[]},t=await a.findNodes({namePattern:r});if(t.length>0){let n=t[0];if(n.sourcePath?e.definingModule=n.sourcePath:u&&(e.definingModule=u.path),n.sourcePath){let t=(await a.findNodes({sourcePath:n.sourcePath,type:`module`}))[0];if(t){let n=await a.getNeighbors(t.id,{direction:`incoming`,edgeType:`imports`});for(let t of n.nodes)e.importedByModules.push(t.sourcePath??t.name)}}if(e.definingModule){let t=await a.findNodes({sourcePath:e.definingModule});for(let n of t)n.name!==r&&n.type!==`module`&&e.siblingSymbols.push(`${n.type}:${n.name}`);e.siblingSymbols=e.siblingSymbols.slice(0,15)}}(e.definingModule||e.importedByModules.length>0||e.siblingSymbols.length>0)&&(y=e)}catch{}return{name:r,definedIn:u,importedBy:p.slice(0,i),referencedIn:_.slice(0,i),graphContext:y}}const mo=T(c);let ho=0;async function go(e={}){if(ho>=2)throw Error(`Too many concurrent test runs (max 2). Try again later.`);ho++;try{return await _o(e)}finally{ho--}}async function _o(e){let t=e.cwd??process.cwd(),n=e.timeout??6e4,r=Date.now(),i=[`vitest`,`run`,`--reporter=verbose`,`--no-color`];e.files?.length&&i.push(...e.files),e.grep&&i.push(`--testNamePattern`,e.grep);try{let{stdout:a}=await mo(`npx ${i.join(` `)}`,{cwd:t,timeout:n}),o=a.toString(),s=xe(o);return{summary:s,passed:s.failed===0,...e.includeRaw&&{raw:o},durationMs:Date.now()-r}}catch(t){let n=vo(t);return{summary:xe(n),passed:!1,...e.includeRaw&&{raw:n},durationMs:Date.now()-r}}}function vo(e){let t=e;return[t.stdout?.toString()??``,t.stderr?.toString()??``].filter(Boolean).join(`
|
|
109
|
+
`).trim()||t.message||`Test run failed`}function yo(e,t,n){if(e===0)return{isError:!1};if(e===1&&n){if(/\b(grep|rg|ripgrep|ag|ack|findstr)\b/i.test(n))return{isError:!1,reason:`grep: no matches (exit 1 is normal)`};if(/\bdiff\b/i.test(n))return{isError:!1,reason:`diff: files differ (exit 1 is normal)`}}return{isError:!0}}function bo(e){let{operation:t,input:n,timezone:r}=e;switch(t){case`now`:return So(new Date,r);case`parse`:if(!n)throw Error(`input required for parse`);return So(xo(n),r);case`convert`:if(!n)throw Error(`input required for convert`);if(!r)throw Error(`timezone required for convert`);return So(xo(n),r);case`diff`:{if(!n)throw Error(`input required for diff (two comma-separated dates)`);let e=n.split(`,`).map(e=>e.trim());if(e.length<2)throw Error(`diff requires two comma-separated dates`);let t=xo(e[0]),r=xo(e[1]),i=Math.abs(r.getTime()-t.getTime());return{output:Co(i),iso:`PT${Math.floor(i/1e3)}S`,unix:i,details:{milliseconds:i,seconds:Math.floor(i/1e3),minutes:Math.floor(i/6e4),hours:Math.floor(i/36e5),days:Math.floor(i/864e5)}}}case`add`:{if(!n)throw Error(`input required for add`);let{duration:t}=e;if(!t)throw Error(`duration required for add (e.g., "2h30m")`);let i=xo(n),a=wo(t);return So(new Date(i.getTime()+a),r)}default:throw Error(`Unknown operation: ${t}`)}}function xo(e){let t=Number(e);if(!Number.isNaN(t))return new Date(t>0xe8d4a51000?t:t*1e3);let n=new Date(e);if(Number.isNaN(n.getTime()))throw Error(`Cannot parse date: ${e}`);return n}function So(e,t){let n=t??`UTC`,r=e.toLocaleString(`en-US`,{timeZone:n,dateStyle:`full`,timeStyle:`long`}),i=new Intl.DateTimeFormat(`en-US`,{timeZone:n,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,hour12:!1}).formatToParts(e).reduce((e,t)=>(t.type!==`literal`&&(e[t.type]=Number.parseInt(t.value,10)),e),{});return{output:r,iso:e.toISOString(),unix:Math.floor(e.getTime()/1e3),details:{timezone:n,year:i.year,month:i.month,day:i.day,hour:i.hour===24?0:i.hour,minute:i.minute,second:i.second}}}function Co(e){let t=[],n=Math.floor(e/864e5);n&&t.push(`${n}d`);let r=Math.floor(e%864e5/36e5);r&&t.push(`${r}h`);let i=Math.floor(e%36e5/6e4);i&&t.push(`${i}m`);let a=Math.floor(e%6e4/1e3);return(a||t.length===0)&&t.push(`${a}s`),t.join(` `)}function wo(e){let t=0,n=e.matchAll(/(\d+)\s*(d|h|m|s|ms)/gi);for(let e of n){let n=Number(e[1]);switch(e[2].toLowerCase()){case`d`:t+=n*864e5;break;case`h`:t+=n*36e5;break;case`m`:t+=n*6e4;break;case`s`:t+=n*1e3;break;case`ms`:t+=n;break}}if(t===0)throw Error(`Cannot parse duration: ${e}`);return t}async function To(e,t,n){let{start:r,direction:i,maxDepth:a=3,graphStore:o}=n,s=[],c=new Set,l=new Set,u=!!D.get(),d=new Map,f=await e.embed(r);if((await t.search(f,{limit:10})).length===0)return{start:r,direction:i,nodes:s,depth:0};let p=[{target:r,depth:0}],m=0;for(;p.length>0;){let n=p.shift();if(!n)break;if(n.depth>=a||c.has(n.target))continue;c.add(n.target);let r=await e.embed(n.target),o=await t.search(r,{limit:20}),f=H(n.target),h=Oo(n.target);for(let e of o){let t=e.record.sourcePath,r=e.record.content.split(`
|
|
110
|
+
`);if(u&&!h){let e=await Do(d,t);for(let r of e)i!==`backward`&&r.callerName===n.target&&(Q(l,s,{path:t,symbol:r.calleeName,line:r.line,relationship:`calls`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.calleeName,depth:n.depth+1})),i!==`forward`&&r.calleeName===n.target&&(Q(l,s,{path:t,symbol:r.callerName,line:r.line,relationship:`called-by`,scope:r.callerName}),m=Math.max(m,n.depth+1),p.push({target:r.callerName,depth:n.depth+1}))}for(let a=0;a<r.length;a+=1){let o=r[a],c=e.record.startLine+a;if(i!==`forward`&&RegExp(h?`from\\s+['"]${f}['"]`:`import\\s+.*\\b${f}\\b.*from\\s+`).test(o)){Q(l,s,{path:t,symbol:n.target,line:c,relationship:`imported-by`}),m=Math.max(m,n.depth+1);let e=o.match(/from\s+['"]([^'"]+)['"]/);!h&&e&&p.push({target:e[1],depth:n.depth+1})}i!==`backward`&&(h?RegExp(`from\\s+['"]${f}['"]`).test(o)&&(Q(l,s,{path:t,symbol:n.target,line:c,relationship:`imports`}),m=Math.max(m,n.depth+1)):u||RegExp(`\\b${f}\\s*\\(`).test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Q(l,s,{path:t,symbol:n.target,line:c,relationship:`calls`}),m=Math.max(m,n.depth+1))),RegExp(h?`['"]${f}['"]`:`\\b${f}\\b`).test(o)&&!/^\s*import\s/.test(o)&&!/^\s*(?:export\s+)?(?:async\s+)?function\s/.test(o)&&(Q(l,s,{path:t,symbol:n.target,line:c,relationship:`references`}),m=Math.max(m,n.depth+1))}}}let h=o?await Eo(r,o):void 0;return{start:r,direction:i,nodes:ko(s),depth:m,graphContext:h}}async function Eo(e,t){try{let n=await t.findNodes({namePattern:e,limit:10}),r=n.find(t=>t.name===e&&t.type!==`module`)??n.find(t=>t.name===e)??n[0];if(!r)return;let i={definingModule:r.sourcePath,community:r.community,importedByModules:[],siblingSymbols:[]};try{let e=await t.getSymbol360(r.id);i.community=e.community??i.community,i.definingModule=e.node.sourcePath??i.definingModule}catch{}if(r.sourcePath){let[e]=await t.findNodes({sourcePath:r.sourcePath,type:`module`});e&&(i.importedByModules=Ao((await t.getNeighbors(e.id,{direction:`incoming`,edgeType:`imports`})).nodes.map(e=>e.sourcePath??e.name)))}return i.definingModule&&(i.siblingSymbols=Ao((await t.findNodes({sourcePath:i.definingModule,limit:50})).filter(e=>e.name!==r.name&&e.type!==`module`).map(e=>`${e.type}:${e.name}`)).slice(0,15)),i.definingModule||i.community||i.importedByModules.length>0||i.siblingSymbols.length>0?i:void 0}catch{return}}async function Do(e,t){let n=e.get(t);if(n)return n;let r=b(t);if(!E.has(r))return e.set(t,[]),[];try{let n=await ee(await p(t,`utf-8`),r,t);return e.set(t,n),n}catch{return e.set(t,[]),[]}}function Q(e,t,n){let r=`${n.path}:${n.line}:${n.relationship}`;e.has(r)||(e.add(r),t.push(n))}function Oo(e){return/[./\\]/.test(e)}function ko(e){let t=new Set;return e.filter(e=>{let n=`${e.path}:${e.line}:${e.relationship}`;return t.has(n)?!1:(t.add(n),!0)})}function Ao(e){return[...new Set(e.filter(e=>e.length>0))]}const $=new Map,jo=[`node_modules`,`.git`,`dist`,`.turbo`,z.data,`cdk.out`];function Mo(e){if($.size>=20)throw Error(`Watcher limit reached (20). Stop existing watchers first.`);let{path:t,maxEvents:n=100}=e,r=e.exclude??jo,i=`watch-${Date.now()}`,a=[],o=e=>r.some(t=>Fo(e).includes(Fo(t))),s=ie(t,{recursive:!0},(e,t)=>{if(t==null)return;let r=String(t);!r||o(r)||(a.push({type:e,path:Fo(r),timestamp:new Date().toISOString()}),a.length>n&&a.shift())});s.on(`error`,()=>{c.status=`stopped`,$.delete(i);try{s.close()}catch{}});let c={id:i,path:t,events:a,status:`watching`,stop:()=>{s.close(),c.status=`stopped`,$.delete(i)},getEvents:e=>e?a.filter(t=>t.timestamp>e):a};return $.set(i,{watcher:s,handle:c}),c}function No(e){let t=$.get(e);return t?(t.handle.stop(),!0):!1}function Po(){return[...$.values()].map(e=>({id:e.handle.id,path:e.handle.path,status:e.handle.status,eventCount:e.handle.events.length}))}function Fo(e){return e.replace(/\\/g,`/`)}const Io=`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`),Lo=[`article`,`[role="main"]`,`main`,`.post-content`,`.article-content`,`.entry-content`,`.content`,`#content`,`.prose`,`.markdown-body`,`.documentation`,`.doc-content`];async function Ro(e){let{url:t,mode:n=`markdown`,selector:r,maxLength:i=15e3,includeMetadata:a=!0,includeLinks:o=!1,includeImages:s=!1,timeout:c=6e4}=e,l=new URL(t);if(l.protocol!==`http:`&&l.protocol!==`https:`)throw Error(`Unsupported protocol: ${l.protocol} — only http/https allowed`);let u=new AbortController,d=setTimeout(()=>u.abort(),c),f,p,m=``,h=!1,g=``;try{if(f=await fetch(t,{signal:u.signal,headers:{"User-Agent":`aikit-web-fetch/1.0 (LLM context tool)`,Accept:`text/html,application/xhtml+xml,text/plain`},redirect:`follow`}),!f.ok)throw Error(`HTTP ${f.status}: ${f.statusText}`);p=await f.text(),m=f.headers.get(`content-type`)??``,h=/text\/html|application\/xhtml\+xml/i.test(m),g=f.url}catch(e){throw e instanceof DOMException&&e.name===`AbortError`?Error(`Request to ${t} timed out after ${c}ms. Try increasing the timeout parameter.`):e}finally{clearTimeout(d)}if(!h){let e=p,t=g.split(`/`).pop()??``;a&&(e=Ho(t,``,g)+e);let n=e.length,r=n>i;return r&&(e=Wo(e,i)),{content:e,title:t,description:``,url:g,originalLength:n,truncated:r}}let{parseHTML:_}=await import(`linkedom`),{document:v}=_(p),y=v.querySelector(`title`)?.textContent?.trim()??v.querySelector(`meta[property="og:title"]`)?.getAttribute(`content`)?.trim()??``,b=v.querySelector(`meta[name="description"]`)?.getAttribute(`content`)?.trim()??v.querySelector(`meta[property="og:description"]`)?.getAttribute(`content`)?.trim()??``;for(let e of Io)for(let t of v.querySelectorAll(e))t.remove();if(!s)for(let e of v.querySelectorAll(`img`))e.remove();let x=null;if(r){if(x=v.querySelector(r),!x)throw Error(`Selector "${r}" matched no elements on the page`)}else{for(let e of Lo)if(x=v.querySelector(e),x)break;x||=v.querySelector(`body`)}if(!x)return{content:`(empty page — no content found)`,title:y,description:b,url:g,originalLength:0,truncated:!1};let S=x.innerHTML,C=[];if(o||n===`links`)for(let e of x.querySelectorAll(`a[href]`)){let t=e.textContent?.trim(),n=e.getAttribute(`href`);t&&n&&!n.startsWith(`#`)&&!n.startsWith(`javascript:`)&&C.push({text:t,href:Uo(n,g)})}let w;switch(n){case`raw`:w=S;break;case`links`:w=Vo(C);break;case`outline`:w=Bo(x);break;default:w=zo(S,s);break}a&&n!==`links`&&(w=Ho(y,b,g)+w),o&&n!==`links`&&C.length>0&&(w+=`\n\n---\n\n## Links\n\n${Vo(C)}`);let T=w.length,E=T>i;return E&&(w=Wo(w,i)),{content:w,title:y,description:b,url:g,originalLength:T,truncated:E}}function zo(e,t){let n=new ve({headingStyle:`atx`,codeBlockStyle:`fenced`,bulletListMarker:`-`});n.addRule(`emptyLinks`,{filter:e=>e.nodeName===`A`&&!e.textContent?.trim(),replacement:()=>``}),t||n.addRule(`removeImages`,{filter:`img`,replacement:()=>``});let r=n.turndown(e);return r=r.replace(/\n{3,}/g,`
|
|
111
111
|
|
|
112
|
-
`).trim(),r}function
|
|
113
|
-
`):`(no headings found)`}function
|
|
114
|
-
`)}function
|
|
112
|
+
`).trim(),r}function Bo(e){let t=e.querySelectorAll(`h1, h2, h3, h4, h5, h6`),n=[];for(let e of t){let t=Number.parseInt(e.tagName.slice(1),10),r=` `.repeat(t-1),i=e.textContent?.trim()??``;i&&n.push(`${r}- ${i}`)}return n.length>0?n.join(`
|
|
113
|
+
`):`(no headings found)`}function Vo(e){if(e.length===0)return`(no links found)`;let t=new Set,n=[];for(let r of e)t.has(r.href)||(t.add(r.href),n.push(r));return n.map(e=>`- [${e.text}](${e.href})`).join(`
|
|
114
|
+
`)}function Ho(e,t,n){let r=[`---`];return e&&r.push(`**${e}**`),r.push(`URL: ${n}`),t&&r.push(`> ${t}`),r.push(`---
|
|
115
115
|
|
|
116
116
|
`),r.join(`
|
|
117
|
-
`)}function
|
|
117
|
+
`)}function Uo(e,t){try{return new URL(e,t).href}catch{return e}}const Wo=Zr;async function Go(e){let{query:t,limit:n=5,site:r}=e;if(!t.trim())throw Error(`Search query cannot be empty`);let i=r?`${t} site:${r}`:t,a=new AbortController,o=setTimeout(()=>a.abort(),15e3),s;try{s=await fetch(`https://html.duckduckgo.com/html/`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"User-Agent":`aikit-web-search/1.0 (LLM developer tool)`},body:`q=${encodeURIComponent(i)}`,signal:a.signal})}finally{clearTimeout(o)}if(!s.ok)throw Error(`Search failed: HTTP ${s.status}`);return Ko(await s.text(),i,n)}function Ko(e,t,n){let r=[],i=/<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a=i.exec(e);for(;a!==null&&r.length<n;){let t=a[1],n=qo(a[2]).trim(),o=qo(a[3]).trim();if(t.includes(`uddg=`)){let e=t.match(/uddg=([^&]+)/)?.[1];e&&(t=decodeURIComponent(e))}n&&t?.startsWith(`http`)&&r.push({title:n,url:t,snippet:o}),a=i.exec(e)}return{results:r,query:t}}function qo(e){return e.replace(/<[^>]+>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Jo(e){return w(B(e??process.cwd()),`worksets.json`)}function Yo(e){let t=Jo(e);if(!M(t))return{worksets:{}};try{let e=P(t,`utf-8`);return JSON.parse(e)}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{worksets:{}}}}function Xo(e,t){let n=Jo(t),r=y(n);M(r)||N(r,{recursive:!0});let i=`${n}.tmp`;R(i,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(i,n)}function Zo(e,t,n){let r=Yo(n?.cwd),i=new Date().toISOString(),a=r.worksets[e],o={name:e,files:t,created:a?.created??i,updated:i,description:n?.description??a?.description};return r.worksets[e]=o,Xo(r,n?.cwd),o}function Qo(e,t){return Yo(t).worksets[e]??null}function $o(e){let t=Yo(e);return Object.values(t.worksets).sort((e,t)=>new Date(t.updated).getTime()-new Date(e.updated).getTime())}function es(e,t){let n=Yo(t);return n.worksets[e]?(delete n.worksets[e],Xo(n,t),!0):!1}function ts(e,t,n){let r=Yo(n).worksets[e]?.files??[];return Zo(e,[...new Set([...r,...t])],{cwd:n})}function ns(e,t,n){let r=Yo(n).worksets[e];if(!r)return null;let i=new Set(t);return Zo(e,r.files.filter(e=>!i.has(e)),{cwd:n})}export{Kn as FileCache,ts as addToWorkset,gi as analyzeFile,$e as audit,Gn as autoClaimTestFailures,tt as batch,Ye as bookendReorder,Ot as bpeSurprise,rt as changelog,Ae as check,lt as checkpointLatest,ct as checkpointList,st as checkpointLoad,ot as checkpointSave,yo as classifyExitCode,Ct as codemod,Mt as compact,Rt as compressOutput,zt as compressTerminalOutput,Je as cosineSimilarity,yt as createRestorePoint,Bt as dataTransform,qt as delegate,Kt as delegateListModels,es as deleteWorkset,Lt as detectOutputTool,Xt as diffParse,_n as digest,yn as dogfoodLog,bn as encode,Sn as envInfo,Ze as errorResponse,H as escapeRegExp,U as estimateTokens,Cn as evaluate,Wn as evidenceMap,Jn as fileSummary,Qn as find,Pe as findDeadSymbols,nr as findExamples,mr as forgeClassify,kr as forgeGround,it as formatChangelog,It as getRegisteredRules,Qo as getWorkset,Wr as gitContext,qr as graphAugmentSearch,Kr as graphQuery,Yr as guide,Xr as headTailTruncate,Le as health,ei as httpRequest,ai as laneCreate,ci as laneDiff,ui as laneDiscard,oi as laneList,li as laneMerge,si as laneStatus,bt as listRestorePoints,$o as listWorksets,hi as measure,Xe as okResponse,zi as onboard,Zr as paragraphTruncate,Se as parseBiome,Ce as parseGitStatus,Te as parseOutput,Ko as parseSearchResults,ye as parseTsc,xe as parseVitest,Ui as processList,Wi as processLogs,Bi as processStart,Hi as processStatus,Vi as processStop,ea as queueClear,qi as queueCreate,ta as queueDelete,Xi as queueDone,Zi as queueFail,Qi as queueGet,$i as queueList,Yi as queueNext,Ji as queuePush,na as regexTest,Pt as registerRule,Ft as registerRules,ns as removeFromWorkset,aa as rename,ua as replayAppend,ma as replayCapture,pa as replayClear,da as replayList,fa as replayTrim,Ke as resolvePath,xt as restoreFromPoint,Zo as saveWorkset,ha as schemaValidate,Dr as scopeMap,jt as scoreLine,kt as scoreLines,qe as segment,qa as sessionDigest,Ja as sessionDigestSampling,At as shannonEntropy,Qa as snippet,Ea as stashClear,Ta as stashDelete,Ca as stashGet,wa as stashList,Sa as stashSet,$a as stratumCard,Me as summarizeCheckResult,po as symbol,go as testRun,bo as timeUtils,To as trace,Qr as truncateToTokenBudget,Po as watchList,Mo as watchStart,No as watchStop,Ro as webFetch,Go as webSearch};
|