agent-runtime-map 0.8.0 → 0.8.2
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/README.md +17 -2
- package/dist/cli.js +41 -41
- package/dist/viewer/assets/index-BYSUKIdb.js +3 -0
- package/dist/viewer/assets/index-oqi3ngbk.css +1 -0
- package/dist/viewer/assets/xyflow-CKwy9Fyu.js +7 -0
- package/dist/viewer/index.html +3 -3
- package/package.json +1 -1
- package/dist/viewer/assets/index-4tql6hvj.js +0 -3
- package/dist/viewer/assets/index-Dvsvzpjt.css +0 -1
- package/dist/viewer/assets/xyflow-NEmtYq4w.js +0 -7
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{parseArgs as rs}from"util";import{mkdir as Go,stat as Ho,writeFile as zo}from"fs/promises";import ke from"path";import{access as bn,readFile as ot}from"fs/promises";import j from"path";import{Node as f,Project as xn,ScriptTarget as Cn,SyntaxKind as S}from"ts-morph";var K="0.1.0";function F(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}import{createHash as gn}from"crypto";import{readdir as pn}from"fs/promises";import ae from"path";var fn=new Set([".git",".next",".logic-map",".turbo",".venv","__mocks__","__pycache__","__tests__","build","coverage","dist","node_modules","out","site-packages","venv"]),mn=/(^|\/)(scripts?|tools?\/dev|examples?|fixtures?|benchmarks?)(\/|$)/i,tt=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),q=new Set(["agent","function","human_gate","route","service","tool","workflow"]),hn=/^(is|has|can|should|must|assert|ensure|validate|to|as|from|parse|stringify|format|normali[sz]e|seriali[sz]e|deseriali[sz]e|encode|decode|escape|unescape|clone|merge|equals|compare|coerce|cast|wrap|unwrap|optional|required|default)[A-Z_]/,wn=/^(boolean|string|number|bigint|symbol|void|null|undefined|unknown|any)(\s*\|\s*(null|undefined))*$/;function yn(e){if(hn.test(e.name))return!0;let n=e.returnType?.trim();return!!(n&&wn.test(n))}function se(e,n){let t=n.exec(e);return t!==null&&t.index>0}function Y(e){let n=e.relativeFile.toLowerCase(),t=e.name.toLowerCase(),i=!mn.test(n)&&!yn(e);return e.routeConvention?{kind:"route",confidence:.95,detail:"Framework route handler convention",method:"framework_convention"}:/(^|\/)(page|layout)\.[jt]sx?$/.test(n)&&/(page|layout)$/.test(t)?{kind:"function",confidence:1,detail:"Declared in source",method:"ast"}:e.internal?{kind:"function",confidence:1,detail:"Private class member, treated as an implementation detail",method:"ast"}:se(t,/(workflow|orchestrator|pipeline|graph|crew)$/)?{kind:"workflow",confidence:.84,detail:"Workflow or orchestrator naming convention",method:"name_heuristic"}:i&&/(^|\/)(workflows?|orchestrators?|pipelines?|graphs?|crews?)(\/|$)/.test(n)?{kind:"workflow",confidence:.72,detail:"Declared under a workflow or orchestrator directory",method:"path_heuristic"}:se(t,/agent$/)?{kind:"agent",confidence:.84,detail:"Agent naming convention",method:"name_heuristic"}:i&&/(^|\/)(agents?)(\/|$)/.test(n)?{kind:"agent",confidence:.72,detail:"Declared under an Agent directory",method:"path_heuristic"}:/(approve|approval|humanreview|human_review|confirm|moderate)/.test(t)?{kind:"human_gate",confidence:.68,detail:"Human approval or review naming convention",method:"name_heuristic"}:se(t,/(tool|action)$/)?{kind:"tool",confidence:.8,detail:"Tool or action naming convention",method:"name_heuristic"}:i&&/(^|\/)(tools?|actions?)(\/|$)/.test(n)?{kind:"tool",confidence:.65,detail:"Declared under a tool or action directory",method:"path_heuristic"}:se(t,/(service|usecase)$/)?{kind:"service",confidence:.8,detail:"Service naming convention",method:"name_heuristic"}:i&&/(^|\/)(services?|use-cases?|commands?)(\/|$)/.test(n)?{kind:"service",confidence:.7,detail:"Declared under a service or use-case directory",method:"path_heuristic"}:e.enclosingClass&&/(service|controller|repository)$/i.test(e.enclosingClass)?{kind:"service",confidence:.6,detail:"Public member of a service, controller, or repository class",method:"name_heuristic"}:/(handler|execute|process|generate|create|build)/.test(t)?{kind:"service",confidence:.5,detail:"Business verb in the declaration name",method:"name_heuristic"}:{kind:"function",confidence:1,detail:"Declared in source",method:"ast"}}function E(e,n,t,i,r,s,o){return{source:{file:e,startLine:n,endLine:o,symbol:s},method:t,detail:i,confidence:r}}function $(e,n,t,i,r={}){return{id:k("edge",`${e}:${t}:${n}:${r.control??"sequential"}:${r.label??""}`),source:e,target:n,kind:t,label:r.label,control:r.control,metadata:r.metadata,evidence:i}}function k(e,n){return`${e}_${gn("sha1").update(n).digest("hex").slice(0,12)}`}function P(e,n){return ae.relative(e,n).split(ae.sep).join("/")}function A(e){return/\.pyi?$/i.test(e)?"python":/\.[cm]?jsx?$/.test(e)?"javascript":"typescript"}function Te(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim()}function M(e){return e.split(/(?<=[.!?])\s/)[0]?.trim().slice(0,240)??e.slice(0,240)}function Z(e){return[...new Set([...e.matchAll(/\{\{?\s*([a-zA-Z0-9_.]+)\s*\}?\}/g)].map(n=>n[1]))]}function U(e){let n=new Set;return e.filter(t=>n.has(t.id)?!1:(n.add(t.id),!0))}async function ce(e,n,t){let i=[];async function r(s){let o;try{o=await pn(s,{withFileTypes:!0})}catch{return}o.sort((a,d)=>a.name.localeCompare(d.name));for(let a of o){let d=ae.join(s,a.name);a.isDirectory()?!fn.has(a.name)&&!a.name.startsWith(".")&&await r(d):a.isFile()&&n.has(ae.extname(a.name))&&!t.test(a.name)&&i.push(d)}}return await r(e),i}var vn=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),En=/(\.(test|spec)\.[cm]?[jt]sx?|\.d\.[cm]?ts)$/i,$n=3,Sn=new Set(["get","post","put","patch","delete","use","all","options","head"]),st=[{pattern:/^(express\.Router|Router|express)$/,name:"express"},{pattern:/^Hono$/,name:"hono"},{pattern:/^Elysia$/,name:"elysia"},{pattern:/^(fastify|Fastify)$/,name:"fastify"},{pattern:/^Koa$/,name:"koa"}],kn=new Set(["aggregate","create","createMany","delete","deleteMany","deleteOne","execute","find","findFirst","findMany","findOne","findUnique","insert","insertMany","insertOne","query","save","select","update","updateMany","updateOne","upsert"]),Rn=new Set(["db","prisma","supabase","drizzle","knex","mongoose","sequelize"]),_n=/^(database|sql|pool|conn|connection|cursor|session|repo|repository|collection|table|store|dao|entityManager|queryRunner)$/i,Nn=new Set(["every","filter","flatmap","foreach","map","reduce","reduceright","some"]);async function at(e,n={}){let t=j.resolve(e),i=[],r=await ce(t,vn,En),s=n.maxFiles??2e3,o=r.slice(0,s);r.length>s&&i.push({level:"warning",code:"FILE_LIMIT_REACHED",message:`Found ${r.length} source files; only the first ${s} were analyzed.`});let a=await Pn(t),d=new xn({...a?{tsConfigFilePath:a}:{},skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0,checkJs:!1,jsx:4,target:Cn.ES2022}});d.addSourceFilesAtPaths(o),await d.resolveSourceFileDependencies();let c=[],g=[],l=new Set(o.map(w=>j.resolve(w))),m=d.getSourceFiles().filter(w=>l.has(j.resolve(w.getFilePath()))),h=new Map,u=new Map;for(let w of m){let v=P(t,w.getFilePath()),R=k("file",v);h.set(w.getFilePath(),R);let _=gi(v)?"entrypoint":"file";c.push({id:R,kind:_,name:v,qualifiedName:v,language:A(v),evidence:[E(v,1,"path_heuristic",_==="entrypoint"?"Framework entrypoint convention":"Source file discovered",_==="entrypoint"?.86:1)]}),An(w,t,R,c,g,u)}for(let w of m){let v=h.get(w.getFilePath());v&&Ln(w,t,v,c,g,u)}let p=Xn(m);for(let w of m){let v=h.get(w.getFilePath());v&&Jn(w,t,v,c,g,u,p)}let y=Bn(m,u);for(let w of m)qn(w,t,u,c,g,y),Fn(w,t,u,c,g);for(let w of m)zn(w,t,h,g),Vn(w,t,u,c,g),jn(w,t,u,c,g),ei(w,t,u,c,g);let b=await hi(t,m.map(w=>P(t,w.getFilePath()))),C=[...new Set(m.map(w=>A(w.getFilePath())))];return m.length===0&&i.push({level:"warning",code:"NO_SOURCE_FILES",message:"No supported TypeScript or JavaScript source files were found."}),{schemaVersion:K,generatedAt:new Date().toISOString(),project:{name:await wi(t),root:t,languages:C,frameworks:b,filesScanned:m.length},nodes:U(c),edges:U(g).filter(w=>w.source!==w.target),diagnostics:i}}async function Pn(e){for(let n of["tsconfig.json","jsconfig.json"]){let t=j.join(e,n);try{return await bn(t),t}catch{}}}function An(e,n,t,i,r,s){let o=P(n,e.getFilePath()),a=[...e.getFunctions(),...e.getClasses().flatMap(d=>d.getMethods()),...e.getVariableDeclarations().filter(d=>{let c=d.getInitializer();return!!(c&&(f.isArrowFunction(c)||f.isFunctionExpression(c)))})];for(let d of a){let c=ai(d);if(!c)continue;let g=d.getStartLineNumber(),{kind:l,confidence:m,detail:h,method:u}=Y(ft(o,c,d)),p=k(l,`${o}:${c}:${g}`),y={id:p,kind:l,name:c,qualifiedName:`${o}#${c}`,language:A(o),evidence:[E(o,g,u,h,m,c,d.getEndLineNumber())],metadata:{...ct(d),...l==="route"?{method:c.toUpperCase(),path:li(o),framework:"nextjs"}:{}}};i.push(y),r.push($(t,p,"contains",y.evidence)),s.set(L(d),{node:y,declaration:d})}for(let d of e.getClasses()){let c=d.getName();if(!c)continue;let g=d.getStartLineNumber(),l=k("class",`${o}:${c}:${g}`),m=[E(o,g,"ast","Class declaration",1,c,d.getEndLineNumber())];i.push({id:l,kind:"class",name:c,qualifiedName:`${o}#${c}`,language:A(o),evidence:m}),r.push($(t,l,"contains",m))}}function de(e){if(f.isArrowFunction(e)||f.isFunctionExpression(e)||f.isFunctionDeclaration(e)||f.isMethodDeclaration(e))return e;let n=f.isExportAssignment(e)?e.getExpression():e.getInitializer();if(n)return f.isArrowFunction(n)||f.isFunctionExpression(n)?n:void 0}function ct(e){let n=de(e);if(!n)return{};let t=n.getParameters().map(r=>({name:r.getName(),type:r.getTypeNode()?.getText()??r.getType().getText(r),optional:r.isOptional()})),i=n.getReturnTypeNode()?.getText()??n.getReturnType().getText(n);return{parameters:t,returnType:i,async:n.hasModifier(S.AsyncKeyword),returnStatements:n.getDescendantsOfKind(S.ReturnStatement).length,throwStatements:n.getDescendantsOfKind(S.ThrowStatement).length,branches:n.getDescendantsOfKind(S.IfStatement).length+n.getDescendantsOfKind(S.SwitchStatement).length+n.getDescendantsOfKind(S.ConditionalExpression).length,loops:n.getDescendantsOfKind(S.ForStatement).length+n.getDescendantsOfKind(S.ForOfStatement).length+n.getDescendantsOfKind(S.ForInStatement).length+n.getDescendantsOfKind(S.WhileStatement).length+n.getDescendantsOfKind(S.DoStatement).length,catches:n.getDescendantsOfKind(S.CatchClause).length}}function Ln(e,n,t,i,r,s){let o=P(n,e.getFilePath());for(let a of e.getVariableDeclarations()){if(s.has(L(a)))continue;let d=a.getInitializer();if(!d)continue;let c=a.getName(),g=Dn(c,d);if(g){let R=k("prompt",`${o}:${c}:${a.getStartLineNumber()}`),_=[E(o,a.getStartLineNumber(),"name_heuristic","Prompt or instructions constant",.88,c,a.getEndLineNumber())],X={id:R,kind:"prompt",name:c,qualifiedName:`${o}#${c}`,description:M(g),language:A(o),metadata:{excerpt:g.slice(0,4e3),variables:Z(g)},evidence:_};i.push(X),r.push($(t,R,"contains",_)),s.set(L(a),{node:X,declaration:a});continue}let l=In(c,d,o);if(!l)continue;let m=a.getStartLineNumber(),h=k(l.kind,`${o}:${c}:${m}`),u=[E(o,m,l.method,l.detail,l.confidence,c,a.getEndLineNumber())],p=dt(d),y=p?z(p,"role"):void 0,b=p?z(p,"description")??z(p,"goal")??y:void 0,C=p?z(p,"instructions")??z(p,"systemPrompt")??z(p,"prompt"):void 0,w=p?z(p,"model"):void 0,v={id:h,kind:l.kind,name:p?z(p,"name")??c:c,qualifiedName:`${o}#${c}`,description:b??(C?M(C):void 0),language:A(o),metadata:{factory:l.factory,role:y,instructions:C?.slice(0,2e3),model:w,toolNames:p?nt(p,"tools"):[],taskNames:p?nt(p,"tasks"):[]},evidence:u};if(i.push(v),r.push($(t,h,"contains",u)),s.set(L(a),{node:v,declaration:a}),w){let R=k("model",w),_=[E(o,m,"framework_convention",`Configured model ${w}`,.94,c)];i.push({id:R,kind:"model",name:w,qualifiedName:`model:${w}`,language:A(o),metadata:{model:w},evidence:_}),r.push($(h,R,"requests",_,{label:"model"}))}if(C&&C.length>=24){let R=k("prompt",`${o}:${c}:inline-instructions`),_=[E(o,m,"framework_convention",`Inline instructions configured for ${c}`,.94,c)];i.push({id:R,kind:"prompt",name:`${c} instructions`,qualifiedName:`${o}#${c}:instructions`,description:M(C),language:A(o),metadata:{excerpt:C.slice(0,4e3),variables:Z(C)},evidence:_}),r.push($(h,R,"data_flow",_,{label:"instructions"}))}}}function In(e,n,t){let i=Tn(n),r=`${i} ${e}`.toLowerCase(),s=/stategraph|messagegraph|create(react)?agent|defineagent|new agent|agent\(|crew\(|crewai|task\(|tool\(|createtool|definetool|chatopenai|chatanthropic/.test(r),o=(a,d,c=s?.96:.82)=>({kind:a,factory:i,confidence:c,detail:d,method:s?"framework_convention":"name_heuristic"});if(/chatopenai|chatanthropic|azurechatopenai|generative(model|ai)|createmodel|language.?model/.test(r))return o("model",`Recognized model construction through ${i}`);if(/stategraph|messagegraph|workflow|orchestrator|pipeline|\bcrew\b/.test(r))return o("workflow",`Recognized workflow construction through ${i||e}`);if(/createtool|definetool|dynamicstructuredtool|\btool\b/.test(r))return o("tool",`Recognized tool construction through ${i||e}`);if(/human.?approval|human.?review|approval.?gate|confirm.?step|interruptbefore/.test(r))return o("human_gate",`Recognized human approval gate through ${i||e}`,.86);if(/create(react)?agent|defineagent|\bagent\b/.test(r))return o("agent",`Recognized Agent construction through ${i||e}`);if(/(^|\/)(agents?|crews?)\//i.test(t))return o("agent","Declared under an Agent directory",.72)}function Tn(e){return f.isCallExpression(e)||f.isNewExpression(e)?e.getExpression().getText():e.getKindName()}function dt(e){if(f.isObjectLiteralExpression(e))return e;if(f.isCallExpression(e)||f.isNewExpression(e))return e.getArguments().find(f.isObjectLiteralExpression)}function z(e,n){let t=e.getProperty(n);if(!t||!f.isPropertyAssignment(t))return;let i=t.getInitializer();if(i&&(f.isStringLiteral(i)||f.isNoSubstitutionTemplateLiteral(i)))return i.getLiteralText()}function nt(e,n){let t=e.getProperty(n);if(!t||!f.isPropertyAssignment(t))return[];let i=t.getInitializer();if(!i)return[];let r=f.isIdentifier(i)?[i]:i.getDescendantsOfKind(S.Identifier);return[...new Set(r.map(s=>s.getText()))]}function Dn(e,n){if(/(prompt|instructions?|system(message|text)?|persona)/i.test(e)){if(f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n))return n.getLiteralText();if(f.isTemplateExpression(n))return n.getText().slice(1,-1)}}function jn(e,n,t,i,r){let s=P(n,e.getFilePath());for(let o of e.getVariableDeclarations()){let a=t.get(L(o)),d=o.getInitializer();if(!a||!d||!["agent","workflow","tool","human_gate"].includes(a.node.kind))continue;if(f.isArrayLiteralExpression(d)){for(let g of d.getElements()){if(!f.isIdentifier(g)&&!f.isPropertyAccessExpression(g))continue;let l=Q(g,t);if(!l||l.node.id===a.node.id||!q.has(l.node.kind))continue;let m=[E(s,g.getStartLineNumber(),"ast",`${a.node.name} lists ${l.node.name} as a step`,.8,o.getName())];r.push($(a.node.id,l.node.id,"calls",m,{label:"step",control:"sequential"}))}continue}let c=dt(d);if(c)for(let g of["tools","agents","tasks","handoffs","instructions","prompt","systemPrompt","model"]){let l=c.getProperty(g);if(!l||!f.isPropertyAssignment(l))continue;let m=l.getInitializer();if(!m)continue;let h=f.isIdentifier(m)?[m]:m.getDescendantsOfKind(S.Identifier);for(let u of h){let p=Q(u,t);if(!p||p.node.id===a.node.id)continue;let y=p.node.kind==="model"?"requests":p.node.kind==="prompt"?"data_flow":"calls",b=[E(s,l.getStartLineNumber(),"framework_convention",`${a.node.name} configures ${g} with ${p.node.name}`,.96,o.getName())];r.push($(a.node.id,p.node.id,y,b,{label:g,control:g==="handoffs"?"conditional":"sequential"}))}}}}function Fn(e,n,t,i,r){let s=P(n,e.getFilePath()),o=new Map,a=e.getDescendantsOfKind(S.CallExpression);for(let d of a){let c=d.getExpression();if(!f.isPropertyAccessExpression(c)||c.getName()!=="addNode")continue;let[g,l]=d.getArguments();if(!g||!f.isStringLiteral(g))continue;let m=g.getLiteralValue(),h=l&&f.isIdentifier(l)?D(l.getSymbol(),t):void 0,u=[E(s,d.getStartLineNumber(),"framework_convention",`Registers workflow node ${m}`,.98,m)],p=h?.node??Mn(m,s,d.getStartLineNumber(),u);h||i.push(p),!h&&l&&(f.isArrowFunction(l)||f.isFunctionExpression(l))&&t.set(L(l),{node:p,declaration:l}),p.metadata={...p.metadata,frameworkNodeName:m},o.set(m,p);let y=D(c.getExpression().getSymbol(),t);y&&y.node.id!==p.id&&r.push($(y.node.id,p.id,"calls",u,{label:"node",control:"sequential"}))}for(let d of a){let c=d.getExpression();if(!f.isPropertyAccessExpression(c))continue;let g=c.getName();if(!["addEdge","addConditionalEdges"].includes(g))continue;let l=D(c.getExpression().getSymbol(),t),[m,h,u]=d.getArguments(),p=it(m);if(!p)continue;let y=Gn(p)?l?.node:o.get(p);if(!y)continue;let b=it(h),C=g==="addConditionalEdges"?On(u):b?[b]:[];for(let w of C){if(Hn(w)){y.metadata={...y.metadata,terminal:!0,terminalReason:"workflow_end"};continue}let v=o.get(w);if(!v||y.id===v.id)continue;let R=g==="addConditionalEdges"?"conditional":"sequential",_=[E(s,d.getStartLineNumber(),"framework_convention",`${g} connects ${p} to ${w}`,.98,p)];r.push($(y.id,v.id,"calls",_,{label:g==="addConditionalEdges"?"branch":void 0,control:R}))}}}function Mn(e,n,t,i){let r=/(agent|research|writer|review|planner)/i.test(e)?"agent":"service";return{id:k(r,`${n}:framework-node:${e}:${t}`),kind:r,name:e,qualifiedName:`${n}#workflow:${e}`,language:A(n),metadata:{frameworkNodeName:e},evidence:i}}function On(e){return!e||!f.isObjectLiteralExpression(e)?[]:e.getProperties().flatMap(n=>{if(!f.isPropertyAssignment(n))return[];let t=n.getInitializer();return t&&f.isStringLiteral(t)?[t.getLiteralValue()]:[]})}function it(e){if(e)return f.isStringLiteral(e)?e.getLiteralValue():f.isIdentifier(e)?e.getText():void 0}function Gn(e){return["__start__","START","start"].includes(e)}function Hn(e){return["__end__","END","end"].includes(e)}function zn(e,n,t,i){let r=t.get(e.getFilePath());if(!r)return;let s=P(n,e.getFilePath());for(let o of e.getImportDeclarations()){let a=o.getModuleSpecifierSourceFile(),d=a?t.get(a.getFilePath()):void 0;if(!d)continue;let c=[E(s,o.getStartLineNumber(),"ast",`Imports ${o.getModuleSpecifierValue()}`,1)];i.push($(r,d,"imports",c))}}function Vn(e,n,t,i,r){let s=P(n,e.getFilePath());for(let o of e.getDescendantsOfKind(S.CallExpression)){let a=gt(o,t);if(!a)continue;let d=pt(o,t)??ii(o,t),c=o.getExpression().getText(),g=ui(o,c,i),l=d?.node.kind==="human_gate"?"human_approval":ri(o,c),m=oi(o,l),h=[E(s,o.getStartLineNumber(),"ast",`${l==="sequential"?"Calls":`${l} call to`} ${c}`,d||g?.96:.8)];d&&r.push($(a.node.id,d.node.id,"calls",h,{control:l,metadata:m})),d&&Kn(o,d,t,s,r),Zn(o,a,d,t,s,l,r),g&&r.push($(a.node.id,g.id,"requests",h,{control:l,metadata:m}));let u=fi(o,c);if(u){let y=k("external_api",u.key),b=[E(s,o.getStartLineNumber(),"name_heuristic",`Outbound request through ${c}`,u.confidence)];i.push({id:y,kind:"external_api",name:u.label,qualifiedName:u.key,language:A(s),metadata:u.metadata,evidence:b}),r.push($(a.node.id,y,"requests",b,{control:l,metadata:m}))}let p=mi(c);if(p){let y=k("database",p.key),b=[E(s,o.getStartLineNumber(),"name_heuristic",`Recognized database operation ${c}`,p.confidence)];i.push({id:y,kind:"database",name:p.label,qualifiedName:p.key,language:A(s),metadata:{operation:p.operation},evidence:b}),r.push($(a.node.id,y,p.edgeKind,b,{control:l,metadata:m}))}}}function Kn(e,n,t,i,r){for(let s of e.getArguments()){let o=f.isIdentifier(s)?[s]:s.getDescendantsOfKind(S.Identifier);for(let a of o)for(let d of a.getSymbol()?.getDeclarations()??[]){if(!f.isVariableDeclaration(d))continue;let c=d.getInitializer(),g=c&&f.isAwaitExpression(c)?c.getExpression():c;if(!g||!f.isCallExpression(g))continue;let l=pt(g,t);if(!l||l.node.id===n.node.id)continue;let m=[E(i,e.getStartLineNumber(),"ast",`${a.getText()} carries the result of ${l.node.name} into ${n.node.name}`,.97)];r.push($(l.node.id,n.node.id,"data_flow",m))}}}function qn(e,n,t,i,r,s){let o=P(n,e.getFilePath());for(let a of e.getDescendantsOfKind(S.CallExpression)){let d=De(a,t);if(!d)continue;let{method:c,owner:g,ownerKey:l,framework:m,confidence:h,evidenceMethod:u,detail:p}=d,y=a.getArguments()[0];if(!y||!f.isStringLiteral(y))continue;let b=a.getArguments().at(-1);if(c==="use"&&b&&f.isIdentifier(b))continue;let C=l?s.get(l):void 0,w=C?Wn(C,y.getLiteralValue()):y.getLiteralValue(),v=k("route",`${c}:${w}:${o}`),R=[E(o,a.getStartLineNumber(),u,C?`${p}, mounted under ${C}`:p,h)],_={id:v,kind:"route",name:`${c.toUpperCase()} ${w}`,qualifiedName:`${c}:${w}`,language:A(o),metadata:{method:c.toUpperCase(),path:w,framework:m,owner:g,mountedUnder:C},evidence:R};if(i.push(_),!!b){if(f.isArrowFunction(b)||f.isFunctionExpression(b)){t.set(L(b),{node:_,declaration:b});continue}if(f.isIdentifier(b)||f.isPropertyAccessExpression(b)){let X=D(b.getSymbol(),t);X&&r.push($(v,X.node.id,"handles",R))}}}}function De(e,n){let t=e.getExpression();if(!f.isPropertyAccessExpression(t))return;let i=t.getName().toLowerCase();if(!Sn.has(i))return;let r=e.getArguments()[0];if(!r||!f.isStringLiteral(r)||!r.getLiteralValue().startsWith("/"))return;let s=ut(t.getExpression(),n);return s?{...s,method:i}:void 0}function ut(e,n){if(f.isCallExpression(e)){let s=e.getExpression();return f.isPropertyAccessExpression(s)?ut(s.getExpression(),n):void 0}if(!f.isIdentifier(e))return;let t=e.getText();if(!/^(app|router|server|api)$/i.test(t)&&!/(router|app|server|routes)$/i.test(t))return Un(e,t);let i=je(e);if(i){let s=i.getInitializer(),o=s&&(f.isCallExpression(s)||f.isNewExpression(s))?s.getExpression().getText():void 0,a=o?st.find(d=>d.pattern.test(o)):void 0;if(a&&o)return{owner:t,ownerKey:L(i),framework:a.name,confidence:.96,evidenceMethod:"framework_convention",detail:`Route registered on a ${a.name} instance built by ${o}`}}let r=i?L(i):void 0;return/^(app|router|server|api)$/i.test(t)?{owner:t,ownerKey:r,framework:"hono_or_express",confidence:.94,evidenceMethod:"framework_convention",detail:`Recognized ${t}.* route registration`}:{owner:t,ownerKey:r,framework:"hono_or_express",confidence:.78,evidenceMethod:"name_heuristic",detail:`Route registered on ${t}, named as a router`}}function Q(e,n){let t=e.getParent();if(f.isShorthandPropertyAssignment(t)){let i=D(t.getValueSymbol(),n);if(i)return i}return D(e.getSymbol(),n)}function Un(e,n){let t=je(e),i=t?.getInitializer();if(!i||!f.isCallExpression(i)&&!f.isNewExpression(i))return;let r=i.getExpression().getText(),s=st.find(o=>o.pattern.test(r));if(!(!s||!t))return{owner:n,ownerKey:L(t),framework:s.name,confidence:.96,evidenceMethod:"framework_convention",detail:`Route registered on a ${s.name} instance built by ${r}`}}function je(e){let n=e.getSymbol();for(let t of[n,n?.getAliasedSymbol()].filter(i=>i!==void 0))for(let i of t.getDeclarations())if(f.isVariableDeclaration(i))return i}function Bn(e,n){let t=new Map;for(let i of e)for(let r of i.getDescendantsOfKind(S.CallExpression)){let s=De(r,n);if(!s||s.method!=="use")continue;let[o,a]=r.getArguments();if(!o||!f.isStringLiteral(o)||!a||!f.isIdentifier(a))continue;let d=je(a);d&&t.set(L(d),o.getLiteralValue())}return t}function Wn(e,n){let t=`${e.replace(/\/+$/,"")}/${n.replace(/^\/+/,"")}`.replace(/\/{2,}/g,"/");return t.length>1?t.replace(/\/$/,""):"/"}function Jn(e,n,t,i,r,s,o){let a=P(n,e.getFilePath()),d=(c,g,l,m=1)=>{if(s.has(L(c)))return;let h=c.getStartLineNumber(),u=Y(ft(a,g,c)),p=k(u.kind,`${a}:${g}:${h}`),y=[E(a,h,u.method,`${l}; ${u.detail.toLowerCase()}`,Math.min(u.confidence,m),g,c.getEndLineNumber())],b={id:p,kind:u.kind,name:g,qualifiedName:`${a}#${g}`,language:A(a),metadata:ct(c),evidence:y};i.push(b),r.push($(t,p,"contains",y)),s.set(L(c),{node:b,declaration:c})};for(let c of e.getVariableDeclarations()){let g=c.getInitializer();if(!g)continue;let l=c.getName();if(f.isObjectLiteralExpression(g)){for(let h of g.getProperties())f.isMethodDeclaration(h)?d(h,`${l}.${h.getName()}`,"Callable member of an object literal"):f.isPropertyAssignment(h)&&de(h)&&d(h,`${l}.${h.getName()}`,"Callable member of an object literal");continue}if(s.has(L(c))||!o.has(l))continue;let m=f.isAwaitExpression(g)?g.getExpression():g;f.isCallExpression(m)&&c.getType().getCallSignatures().length!==0&&d(c,l,`Callable produced by ${m.getExpression().getText()}`,.9)}for(let c of e.getExportAssignments())c.isExportEquals()||!de(c)||d(c,Yn(a),"Default-exported callable")}function Xn(e){let n=new Set;for(let t of e)for(let i of t.getDescendantsOfKind(S.CallExpression)){let r=i.getExpression();f.isIdentifier(r)?n.add(r.getText()):f.isPropertyAccessExpression(r)&&n.add(r.getName());for(let s of lt(i))n.add(f.isIdentifier(s)?s.getText():s.getName())}return n}function Yn(e){let n=j.basename(e).replace(/\.[cm]?[jt]sx?$/i,"");if(!/^(index|route)$/i.test(n))return n;let t=j.basename(j.dirname(e));return t&&t!=="."?`${t} ${n}`:n}function Zn(e,n,t,i,r,s,o){if(De(e,i))return;let a=e.getExpression().getText();for(let d of lt(e)){let c=Q(d,i);if(!c||c.node.id===n.node.id||c.node.id===t?.node.id)continue;let g=d.getStartLineNumber();if(q.has(c.node.kind)){let l=[E(r,g,"ast",`${c.node.name} is handed to ${a} as a callback`,.9)],m=c.node.kind==="human_gate"?"human_approval":ni(a,s);o.push($(n.node.id,c.node.id,"calls",l,{control:m}));continue}if(c.node.kind==="prompt"||c.node.kind==="model"){let l=[E(r,g,"ast",`${c.node.name} is passed into ${a}`,.94)];o.push($(c.node.id,n.node.id,"data_flow",l,{label:c.node.kind}))}}}var Qn=/^(generateText|streamText|generateObject|streamObject|embed|embedMany|create|complete|invoke)$/;function ei(e,n,t,i,r){let s=P(n,e.getFilePath());for(let o of e.getDescendantsOfKind(S.CallExpression)){let a=o.getExpression().getText();if(!Qn.test(a.split(".").at(-1)??""))continue;let d=o.getArguments().find(f.isObjectLiteralExpression);if(!d||!d.getProperty("model"))continue;let c=gt(o,t);if(!c)continue;let g=o.getStartLineNumber(),l=ti(d.getProperty("model"));if(l){let u=k("model",l.name),p=[E(s,g,"framework_convention",`${a} requests model ${l.name}`,.96,c.node.name)];i.push({id:u,kind:"model",name:l.name,qualifiedName:`model:${l.name}`,language:A(s),metadata:{model:l.name,provider:l.provider},evidence:p}),r.push($(c.node.id,u,"requests",p,{label:"model"}))}for(let u of["system","prompt","instructions","messages"]){let p=d.getProperty(u);if(!p||!f.isPropertyAssignment(p))continue;let y=p.getInitializer();if(y)for(let b of f.isIdentifier(y)?[y]:y.getDescendantsOfKind(S.Identifier)){let C=Q(b,t);if(C?.node.kind!=="prompt")continue;let w=[E(s,p.getStartLineNumber(),"framework_convention",`${c.node.name} sends ${C.node.name} as ${u}`,.96,c.node.name)];r.push($(C.node.id,c.node.id,"data_flow",w,{label:u}))}}let m=d.getProperty("tools");if(!m||!f.isPropertyAssignment(m))continue;let h=m.getInitializer();if(h)for(let u of h.getDescendantsOfKind(S.Identifier)){let p=Q(u,t);if(!p||p.node.id===c.node.id||!q.has(p.node.kind))continue;let y=[E(s,m.getStartLineNumber(),"framework_convention",`${c.node.name} offers ${p.node.name} as a tool to the model`,.94,c.node.name)];r.push($(c.node.id,p.node.id,"calls",y,{label:"tool",control:"conditional"}))}}}function ti(e){if(!e||!f.isPropertyAssignment(e))return;let n=e.getInitializer();if(n){if(f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n))return{name:n.getLiteralText()};if(f.isCallExpression(n)){let t=n.getExpression().getText(),i=n.getArguments()[0];return i&&f.isStringLiteral(i)?{name:i.getLiteralValue(),provider:t}:{name:n.getText(),provider:t}}}}function lt(e){let n=[],t=i=>{(f.isIdentifier(i)||f.isPropertyAccessExpression(i))&&n.push(i)};for(let i of e.getArguments())f.isArrayLiteralExpression(i)?i.getElements().forEach(t):t(i);return n}function ni(e,n){if(/^promise\s*\.\s*(all|allsettled|race|any)$/i.test(e))return"parallel";let t=e.split(".").at(-1)?.toLowerCase()??"";return Nn.has(t)?"loop":t==="catch"?"fallback":n}function gt(e,n){let t=e;for(;t;){if(f.isFunctionDeclaration(t)||f.isMethodDeclaration(t)||f.isVariableDeclaration(t)||f.isPropertyAssignment(t)||f.isExportAssignment(t)||f.isArrowFunction(t)||f.isFunctionExpression(t)){let i=n.get(L(t));if(i)return i}t=t.getParent()}}function pt(e,n){let t=e.getExpression(),i=D(t.getSymbol(),n);if(i)return i;if(f.isPropertyAccessExpression(t))return D(t.getExpression().getSymbol(),n)}function ii(e,n){let t=e.getExpression().getText().toLowerCase();if(!/(^|\.)(run|runstreamed|invoke|execute)$/.test(t))return;let i=e.getArguments()[0];if(!i||!f.isIdentifier(i))return;let r=D(i.getSymbol(),n);return r&&["agent","workflow"].includes(r.node.kind)?r:void 0}function ri(e,n){if(/retry|backoff|withretry/i.test(n))return"retry";for(let t of e.getAncestors()){if(f.isFunctionDeclaration(t)||f.isMethodDeclaration(t)||f.isArrowFunction(t)||f.isFunctionExpression(t))break;if(f.isCallExpression(t)&&/^(Promise\.(all|allSettled|race|any)|parallel|all)$/.test(t.getExpression().getText()))return"parallel";if(f.isCatchClause(t))return"fallback";if(f.isForStatement(t)||f.isForOfStatement(t)||f.isForInStatement(t)||f.isWhileStatement(t)||f.isDoStatement(t))return/retry|attempt|backoff/i.test(t.getText().slice(0,240))?"retry":"loop";if(f.isIfStatement(t)||f.isSwitchStatement(t)||f.isConditionalExpression(t))return"conditional"}return"sequential"}function oi(e,n){if(n!=="retry")return;let t=[e.getText().slice(0,600)];for(let s of e.getAncestors())if(f.isFunctionDeclaration(s)||f.isMethodDeclaration(s)||f.isArrowFunction(s)||f.isFunctionExpression(s)||(t.push(s.getText().slice(0,600)),f.isForStatement(s)||f.isWhileStatement(s)||f.isDoStatement(s)))break;let i=t.join(" ");return{retryBounded:/max[A-Z_\s-]?(attempts?|retries)|retryLimit|attempt\s*[<>=!]+\s*\d+|retries\s*:\s*\d+|maxRetries\s*:\s*\d+/i.test(i)}}function D(e,n,t=0){if(!e||t>$n)return;let i=[e,e.getAliasedSymbol()].filter(r=>r!==void 0);for(let r of i.flatMap(s=>s.getDeclarations())){let s=n.get(L(r));if(s)return s;if(f.isBindingElement(r)){let o=si(r,n,t);if(o)return o}if(f.isPropertyAssignment(r)||f.isVariableDeclaration(r)){let o=r.getInitializer();if(o&&(f.isIdentifier(o)||f.isPropertyAccessExpression(o))){let a=D(o.getSymbol(),n,t+1);if(a)return a}}}}function si(e,n,t){let i=e.getParent();if(!f.isObjectBindingPattern(i))return;let r=i.getParent();if(!f.isVariableDeclaration(r))return;let s=r.getInitializer();if(!s)return;let o=e.getPropertyNameNode()?.getText()??e.getName();return D(s.getType().getProperty(o),n,t+1)}function ai(e){return e.getName()}function L(e){return`${e.getSourceFile().getFilePath()}:${e.getStart()}`}function ft(e,n,t){let i=f.isMethodDeclaration(t)?t:void 0,r=f.isFunctionDeclaration(t)||f.isMethodDeclaration(t)?t:f.isVariableDeclaration(t)||f.isPropertyAssignment(t)||f.isExportAssignment(t)?de(t):void 0;return{relativeFile:e,name:n,returnType:r?.getReturnTypeNode()?.getText(),internal:di(t),enclosingClass:i?ci(i):void 0,routeConvention:/\/app\/api\/.+\/route\.[jt]sx?$/.test(`/${e.toLowerCase()}`)&&tt.has(n.toUpperCase())}}function ci(e){let n=e.getParent();return f.isClassDeclaration(n)||f.isClassExpression(n)?n.getName()??"":""}function di(e){return f.isMethodDeclaration(e)?e.getName().startsWith("#")||e.getName().startsWith("_")?!0:e.hasModifier(S.PrivateKeyword)||e.hasModifier(S.ProtectedKeyword):!1}function ui(e,n,t){if(n!=="fetch")return;let[i,r]=e.getArguments();if(!i||!f.isStringLiteral(i))return;let s=i.getLiteralValue();if(!s.startsWith("/"))return;let o="GET";if(r&&f.isObjectLiteralExpression(r)){let a=r.getProperty("method");if(a&&f.isPropertyAssignment(a)){let d=a.getInitializer();d&&f.isStringLiteral(d)&&(o=d.getLiteralValue().toUpperCase())}}return t.find(a=>a.kind==="route"&&a.metadata?.path===s&&a.metadata?.method===o)}function li(e){let n=e.match(/(?:^|\/)app\/(api\/.+)\/route\.[jt]sx?$/);return n?`/${n[1]}`:e}function gi(e){return/(^|\/)(page|layout|route|index|main|server|app)\.[jt]sx?$/.test(e)||/(^|\/)pages\/api\//.test(e)}var pi=/^(fetch|nodeFetch|axios|got|ky|superagent|undici)(\.(get|post|put|patch|delete|head|request))?$/;function fi(e,n){let t=e.getArguments()[0];if(pi.test(n)){let r=n.split(".")[0],s=t&&f.isStringLiteral(t)?t.getLiteralValue():void 0;if(s&&/^https?:\/\//.test(s)){let o=yi(s);return{key:`http:${o}`,label:o,metadata:{provider:r,url:s},confidence:.92}}if(!s)return{key:`http:${r}`,label:`${Te(r)} request`,metadata:{provider:r,url:void 0},confidence:.68}}let i=[{pattern:/(^|\.)openai\.|\.responses\.create$|\.chat\.completions\.create$/,key:"sdk:openai",label:"OpenAI API"},{pattern:/(^|\.)anthropic\.|\.messages\.create$/,key:"sdk:anthropic",label:"Anthropic API"},{pattern:/(^|\.)stripe\./,key:"sdk:stripe",label:"Stripe API"}].find(r=>r.pattern.test(n.toLowerCase()));return i?{key:i.key,label:i.label,metadata:{provider:i.key.slice(4)},confidence:.9}:void 0}function mi(e){let n=e.split(".");if(n.length<2)return;let t=n.at(-1)??"",i=n[0]??"";if(!kn.has(t))return;let r=Rn.has(i.toLowerCase());if(!r&&!_n.test(i))return;let s=n.length>2?n.at(-2)??"data":"data",o=s==="data"?i:s,a=/^(find|select|query|aggregate)/.test(t);return{key:`${i.toLowerCase()}:${s}`,label:`${Te(o)} data`,operation:t,edgeKind:a?"reads":"writes",confidence:r?.88:.7}}async function hi(e,n){let t=new Set;try{let i=JSON.parse(await ot(j.join(e,"package.json"),"utf8")),r={...rt(i.dependencies),...rt(i.devDependencies)},s={next:"Next.js",react:"React",express:"Express",hono:"Hono","@nestjs/core":"NestJS","@langchain/langgraph":"LangGraph",langchain:"LangChain","@openai/agents":"OpenAI Agents SDK","@mastra/core":"Mastra",ai:"Vercel AI SDK",openai:"OpenAI SDK","@anthropic-ai/sdk":"Anthropic SDK","@temporalio/workflow":"Temporal",inngest:"Inngest"};for(let[o,a]of Object.entries(s))o in r&&t.add(a)}catch{}return n.some(i=>/(^|\/)app\/api\/.+\/route\.[jt]s$/.test(i))&&t.add("Next.js"),[...t]}async function wi(e){try{let n=JSON.parse(await ot(j.join(e,"package.json"),"utf8"));if(n.name)return n.name}catch{}return j.basename(e)}function yi(e){try{return new URL(e).hostname}catch{return e}}function rt(e){return e&&typeof e=="object"?e:{}}import{spawn as bi}from"child_process";import{readFile as mt}from"fs/promises";import B from"path";import{fileURLToPath as xi}from"url";var Ci=new Set([".py"]),vi=/(^test_.*\.py$|_test\.py$|^conftest\.py$|\.pyi$)/i,Ei=/^(app|router|api|server|[a-z_]*(?:router|app|api))\.(get|post|put|patch|delete|head|options)$/i,$i=/^(FastAPI|APIRouter|Flask|Blueprint|Quart|Starlette|Sanic)$/,Si=/(^|\.)((responses|chat\.completions|completions|messages|embeddings)\.create|generate_content|invoke|ainvoke)$/;async function ht(e,n={}){let t=B.resolve(e),i=[],r=await ce(t,Ci,vi),s=n.maxFiles??2e3,o=r.slice(0,s);r.length>s&&i.push({level:"warning",code:"FILE_LIMIT_REACHED",message:`Found ${r.length} Python files; only the first ${s} were analyzed.`});let a=[],d=[],c;o.length&&(c=await _i(o,n.pythonPath,i));let g=new Map;for(let l of c?.files??[]){if(l.error){i.push({level:"warning",code:"PYTHON_FILE_UNREADABLE",message:`${P(t,l.path)}: ${l.error}`});continue}ki(l,t,a,d,g)}for(let l of c?.files??[])l.error||Ri(l,t,a,d,g);return{schemaVersion:K,generatedAt:new Date().toISOString(),project:{name:B.basename(t),root:t,languages:o.length?["python"]:[],frameworks:await Hi(t,c),filesScanned:c?.files.filter(l=>!l.error).length??0},nodes:U(a),edges:U(d).filter(l=>l.source!==l.target),diagnostics:i}}function ki(e,n,t,i,r){let s=P(n,e.path),o=k("file",s),a=Gi(s),d=[E(s,1,"path_heuristic",a?"Framework entrypoint convention":"Source file discovered",a?.86:1)];t.push({id:o,kind:a?"entrypoint":"file",name:s,qualifiedName:s,language:"python",evidence:d});for(let c of e.classes){let g=k("class",`${s}:${c.name}:${c.line}`),l=[E(s,c.line,"ast","Class declaration",1,c.name,c.endLine)],m={id:g,kind:"class",name:c.name,qualifiedName:`${s}#${c.name}`,description:c.docstring?M(c.docstring):void 0,language:"python",metadata:{bases:c.bases},evidence:l};t.push(m),i.push($(o,g,"contains",l)),r.set(c.name,m)}for(let c of e.functions){let g=Ai(c.decorators,e),l=Y({relativeFile:s,name:c.name,internal:!!c.enclosingClass&&c.name.startsWith("_"),enclosingClass:c.enclosingClass??void 0,routeConvention:!!g,returnType:c.returns??void 0}),m=k(l.kind,`${s}:${c.name}:${c.line}`),h=[E(s,c.line,l.method,g?`${l.detail} via ${g.decorator}`:l.detail,l.confidence,c.name,c.endLine)],u={id:m,kind:l.kind,name:g?`${g.method} ${g.path}`:c.name,qualifiedName:`${s}#${c.name}`,description:c.docstring?M(c.docstring):void 0,language:"python",metadata:{...g?{method:g.method,path:g.path,framework:g.framework}:{},async:c.isAsync,parameters:c.parameters.filter(p=>p!=="self"&&p!=="cls"),returnType:c.returns??void 0,branches:c.branches,loops:c.loops,catches:c.catches},evidence:h};t.push(u),i.push($(o,m,"contains",h)),r.set(c.name,u)}for(let c of e.assignments){if(c.scope)continue;let g=Di(c.name,c.text);if(g){let C=k("prompt",`${s}:${c.name}:${c.line}`),w=[E(s,c.line,"name_heuristic","Prompt or instructions constant",.88,c.name,c.endLine)],v={id:C,kind:"prompt",name:c.name,qualifiedName:`${s}#${c.name}`,description:M(g),language:"python",metadata:{excerpt:g.slice(0,4e3),variables:Z(g)},evidence:w};t.push(v),i.push($(o,C,"contains",w)),r.set(c.name,v);continue}let l=Ii(c.name,c.factory);if(!l)continue;let m=k(l.kind,`${s}:${c.name}:${c.line}`),h=[E(s,c.line,l.method,l.detail,l.confidence,c.name,c.endLine)],u=c.options??{},p=O(u,"instructions")??O(u,"system_prompt")??O(u,"prompt"),y=O(u,"model"),b={id:m,kind:l.kind,name:O(u,"name")??c.name,qualifiedName:`${s}#${c.name}`,description:O(u,"description")??O(u,"goal")??(p?M(p):void 0),language:"python",metadata:{factory:c.factory??void 0,role:O(u,"role"),instructions:p?.slice(0,2e3),model:y,toolNames:ee(u,"tools"),taskNames:ee(u,"tasks")},evidence:h};t.push(b),i.push($(o,m,"contains",h)),r.set(c.name,b)}}function Ri(e,n,t,i,r){let s=P(n,e.path);for(let o of e.calls){let a=o.enclosingFunction?r.get(o.enclosingFunction):void 0;if(!a)continue;let d=Ti(o),c=[E(s,o.line,"ast",`Calls ${o.callee}`,.96,o.enclosingFunction??void 0)],g=Fe(r,o.callee);g&&g.id!==a.id&&(q.has(g.kind)?i.push($(a.id,g.id,"calls",c,{control:d})):(g.kind==="prompt"||g.kind==="model")&&i.push($(g.id,a.id,"data_flow",[E(s,o.line,"ast",`${g.name} is used by ${a.name}`,.92)],{label:g.kind})));for(let h of o.nameArguments){let u=Fe(r,h);if(!(!u||u.id===a.id||u.id===g?.id)){if(u.kind==="prompt"||u.kind==="model"){i.push($(u.id,a.id,"data_flow",[E(s,o.line,"ast",`${u.name} is passed into ${o.callee}`,.94)],{label:u.kind}));continue}i.push($(a.id,u.id,"calls",[E(s,o.line,"ast",`${u.name} is handed to ${o.callee} as a callback`,.9)],{control:d}))}}if(Si.test(o.callee)){let h=O(o.options,"model");if(h){let u=k("model",h),p=[E(s,o.line,"framework_convention",`${o.callee} requests model ${h}`,.96,o.enclosingFunction??void 0)];t.push({id:u,kind:"model",name:h,qualifiedName:`model:${h}`,language:"python",metadata:{model:h},evidence:p}),i.push($(a.id,u,"requests",p,{label:"model"}))}for(let u of ee(o.options,"input").concat(ee(o.options,"messages"),ee(o.options,"prompt"))){let p=Fe(r,u);p?.kind==="prompt"&&i.push($(p.id,a.id,"data_flow",[E(s,o.line,"framework_convention",`${a.name} sends ${p.name} to the model`,.96)],{label:"prompt"}))}}let l=Fi(o.callee);if(l){let h=k("database",l.key),u=[E(s,o.line,"name_heuristic",`Recognized database operation ${o.callee}`,.88)];t.push({id:h,kind:"database",name:l.label,qualifiedName:l.key,language:"python",metadata:{operation:l.operation},evidence:u}),i.push($(a.id,h,l.edgeKind,u,{control:d}))}let m=Mi(o);if(m){let h=k("external_api",m.key),u=[E(s,o.line,"name_heuristic",`Outbound request through ${o.callee}`,.9)];t.push({id:h,kind:"external_api",name:m.label,qualifiedName:m.key,language:"python",metadata:m.metadata,evidence:u}),i.push($(a.id,h,"requests",u,{control:d}))}}}async function _i(e,n,t){let i;try{i=await Pi()}catch(o){t.push({level:"warning",code:"PYTHON_EXTRACTOR_MISSING",message:o instanceof Error?o.message:String(o)});return}let r=n?[n]:["python3","python"],s="";for(let o of r)try{return await Ni(o,i,e)}catch(a){s=a instanceof Error?a.message:String(a)}t.push({level:"warning",code:"PYTHON_UNAVAILABLE",message:`Python source was found but no interpreter could analyze it (${s}). Install Python 3 or pass a path to analyze these files.`})}function Ni(e,n,t){return new Promise((i,r)=>{let s=bi(e,["-c",n],{stdio:["pipe","pipe","pipe"]}),o="",a="";s.stdout.setEncoding("utf8"),s.stdout.on("data",d=>{o+=d}),s.stderr.setEncoding("utf8"),s.stderr.on("data",d=>{a+=d}),s.on("error",d=>r(new Error(`${e}: ${d.message}`))),s.on("close",d=>{if(d!==0){r(new Error(`${e} exited with ${d}: ${a.trim().slice(0,200)}`));return}try{i(JSON.parse(o))}catch{r(new Error(`${e} returned output that was not valid JSON`))}}),s.stdin.end(JSON.stringify(t))})}async function Pi(){let e=B.dirname(xi(import.meta.url)),n=[B.join(e,"..","scripts","extract.py"),B.join(e,"python","extract.py")];for(let t of n)try{return await mt(t,"utf8")}catch{}throw new Error("the bundled Python extractor is missing from this installation")}function Ai(e,n){for(let t of e){let i=Ei.exec(t);if(!i)continue;let r=i[1],s=i[2].toUpperCase(),a=n.calls.find(d=>d.callee===t&&d.stringArguments.length)?.stringArguments[0]??"/";return{method:s,path:a,framework:Li(r,n),decorator:t}}}function Li(e,n){let t=n.assignments.find(i=>i.name===e&&i.factory&&$i.test(i.factory));return t?.factory?t.factory==="Flask"||t.factory==="Blueprint"?"flask":t.factory.toLowerCase():"python_http"}function Ii(e,n){let t=`${n??""} ${e}`.toLowerCase(),i=/stategraph|messagegraph|create_react_agent|createagent|\bagent\(|\bcrew\(|crewai|\btask\(|\btool\(|chatopenai|chatanthropic|assistant/.test(t),r=(s,o,a=i?.96:.82)=>({kind:s,confidence:a,detail:o,method:i?"framework_convention":"name_heuristic"});if(/chatopenai|chatanthropic|azurechatopenai|generativemodel|language_?model/.test(t))return r("model",`Recognized model construction through ${n}`);if(/stategraph|messagegraph|workflow|orchestrator|pipeline|\bcrew\b/.test(t))return r("workflow",`Recognized workflow construction through ${n??e}`);if(/structuredtool|\btool\b/.test(t))return r("tool",`Recognized tool construction through ${n??e}`);if(/human_?approval|human_?review|approval_?gate|interrupt_before/.test(t))return r("human_gate",`Recognized human approval gate through ${n??e}`,.86);if(/create_react_agent|createagent|\bagent\b/.test(t))return r("agent",`Recognized Agent construction through ${n??e}`)}function Ti(e){return/retry|backoff/i.test(e.callee)?"retry":"sequential"}function Di(e,n){if(!(!n||n.length<24))return/prompt|instruction|system|template|persona/i.test(e)?n:void 0}function O(e,n){let t=e?.[n];return t?.kind==="string"?t.value:void 0}function ee(e,n){let t=e?.[n];return t?.kind==="names"?t.value:[]}function ji(e){return e.split(".").at(-1)??e}function Fe(e,n){let t=n.split(".");return e.get(n)??e.get(t.at(-1)??n)??e.get(t[0]??n)}function Fi(e){let n=ji(e).toLowerCase(),t=["all","filter","first","get","query","scalar","select","fetchall","fetchone","find","find_one"],i=["add","bulk_save_objects","commit","create","delete","insert","save","update","upsert","insert_one","update_one"];if(!t.includes(n)&&!i.includes(n))return;let r=e.split(".").slice(0,-1).join(".")||"database";if(/session|db|database|repo|repository|table|collection|cursor|conn/i.test(r))return{key:`db:${r}`,label:`${r} data`,operation:n,edgeKind:i.includes(n)?"writes":"reads"}}function Mi(e){if(!/^(requests|httpx|aiohttp|urllib\.request)\.[a-z]+$/i.test(e.callee))return;let n=e.stringArguments.find(i=>/^https?:\/\//.test(i)),t=n?Oi(n):e.callee.split(".")[0];return{key:`http:${t}`,label:t,metadata:{host:t,url:n,client:e.callee.split(".")[0]}}}function Oi(e){try{return new URL(e).hostname}catch{return e}}function Gi(e){return/(^|\/)(main|app|__main__|server|asgi|wsgi|manage)\.py$/i.test(e)}async function Hi(e,n){let t=new Set,i={fastapi:"FastAPI",flask:"Flask",django:"Django",starlette:"Starlette",langgraph:"LangGraph",langchain:"LangChain",crewai:"CrewAI",llama_index:"LlamaIndex",autogen:"AutoGen",openai:"OpenAI SDK",anthropic:"Anthropic SDK",pydantic_ai:"Pydantic AI"};for(let r of n?.files??[])for(let s of r.imports??[]){let o=s.module.split(".")[0]?.toLowerCase()??"",a=i[o];a&&t.add(a)}for(let r of["requirements.txt","pyproject.toml"])try{let s=(await mt(B.join(e,r),"utf8")).toLowerCase();for(let[o,a]of Object.entries(i))(s.includes(o.replace("_","-"))||s.includes(o))&&t.add(a)}catch{}return[...t]}import{createHash as ir}from"crypto";import{createHash as zi}from"crypto";var bt=new Set(["data","external_system","model"]),ue=120,Ge=12,Oe=48;function He(e,n,t=[]){let i=new Map(e.map(l=>[l.id,l])),r=le(n),s=er(n),o=e.filter(l=>l.type==="user_action"),a=new Set(o.flatMap(l=>[...xt(l.id,r)])),d=e.filter(l=>l.type==="entrypoint"&&!a.has(l.id)),c=e.filter(l=>["ai_process","process"].includes(l.type)&&(s.get(l.id)?.length??0)===0&&(r.get(l.id)?.length??0)>0);return nr([...o,...d,...o.length||d.length?[]:c]).map(l=>Vi(l,n,i,r,t)).sort((l,m)=>yt(m.health)-yt(l.health)||l.label.localeCompare(m.label))}function Vi(e,n,t,i,r){let s=xt(e.id,i),o=[...s].slice(0,ue),a=new Set(o),d=n.filter(w=>a.has(w.source)&&a.has(w.target)),c=o.flatMap(w=>t.get(w)?[t.get(w)]:[]),g=c.filter(w=>!d.some(v=>v.source===w.id)),l=Xi(e.id,a,d,t),m=Bi(e,c,d,n,t,s.size,l.truncated),h=Wi(e.id,c,d,l,t),u=Zi(e.id,i,t),p=qi(c,r),y=c.length?F(Math.min(...c.map(w=>w.confidence))):e.confidence,b=tr(m),C=p?.capability.label??u?.label??e.label;return{id:`feature_${I(`${e.id}:${C}`)}`,label:C,description:p?.capability.description??`Simulates the code-backed execution chain that starts at ${C}.`,entryNodeIds:[e.id],resultNodeIds:g.map(w=>w.id),nodeIds:o,edgeIds:d.map(w=>w.id),variants:h,diagnostics:m,health:b,confidence:y,product:Ki(p)}}function Ki(e){if(e)return{capabilityId:e.capability.id,label:e.capability.label,origin:e.capability.origin,sources:e.capability.sources,match:F(Math.min(.95,.35+Math.min(e.score,24)*.025)*e.capability.confidence),matchedOn:e.matchedOn,matchedTerms:e.matchedTerms}}function qi(e,n){let t=Me(e.map(o=>`${o.label} ${o.metadata?.rawName??""}`).join(" ")),i=Me(e.filter(o=>o.type==="entrypoint"||o.type==="user_action").map(o=>`${o.label} ${o.metadata?.rawName??""}`).join(" ")),r=new Map;for(let o of e){let a=typeof o.metadata?.documentedCapabilityId=="string"?o.metadata.documentedCapabilityId:void 0;a&&r.set(a,(r.get(a)??0)+1)}let s;for(let o of n){let a=Me(`${o.label} ${o.keywords.join(" ")}`),d=[...a].filter(l=>i.has(l)).length,c=[...a].filter(l=>t.has(l)).length,g=d*8+c+(r.get(o.id)??0)*.5;g>0&&(!s||g>s.score||g===s.score&&o.confidence>s.capability.confidence)&&(s={capability:o,score:g,matchedOn:d>0?"entry_terms":"step_terms",matchedTerms:[...a].filter(l=>i.has(l)||t.has(l)).slice(0,4)})}return s}function Me(e){let n=e.toLowerCase().match(/[a-z][a-z0-9-]{2,}|[\u3400-\u9fff]{2,8}/g)??[];return new Set(n.map(t=>Ui(t).replace(/^(post|get|put|patch|delete)$/,"")).filter(t=>t.length>=3))}function Ui(e){return/(ations?|tion)$/.test(e)?e.replace(/ations?$/,"ate").replace(/tion$/,"te"):e.replace(/(ing|ed|es|s)$/i,"")}function Bi(e,n,t,i,r,s,o){let a=[],d=new Set(n.map(u=>u.id)),c=i.filter(u=>d.has(u.source)&&(!r.has(u.source)||!r.has(u.target)));for(let u of c)a.push({id:`diagnostic_${I(`broken:${u.id}`)}`,code:"CHAIN_BROKEN_REFERENCE",severity:"error",message:"The chain references a logic node that does not exist in the graph.",suggestion:"Check the unresolved call, import, or generated edge at this point.",edgeId:u.id,nodeId:u.source,sources:r.get(u.source)?.sources??[],confidence:1});t.length===0&&a.push({id:`diagnostic_${I(`downstream:${e.id}`)}`,code:"CHAIN_NO_DOWNSTREAM",severity:"error",message:"The feature entry has no resolvable downstream execution step.",suggestion:"Check whether the entry calls a workflow, agent, service, or tool that the analyzer can resolve.",nodeId:e.id,sources:e.sources,confidence:1});let g=Qi(n,t),l=n.filter(u=>!t.some(p=>p.source===u.id)).length;g&&a.push({id:`diagnostic_${I(`cycle:${g.id}`)}`,code:"CHAIN_CYCLE",severity:l===0?"error":"warning",message:l===0?"The feature chain contains a cycle with no resolvable exit.":"The feature chain contains a cycle; verify that its runtime exit condition is intentional.",suggestion:"Inspect the loop guard or add an explicit terminal path.",nodeId:g.id,sources:g.sources,confidence:l===0?.95:.75}),n.length>1&&l===0&&a.push({id:`diagnostic_${I(`result:${e.id}`)}`,code:"CHAIN_NO_RESULT",severity:"error",message:"The analyzer could not find a terminal result for this feature.",suggestion:"Add or expose a return, persistence, response, or handoff that completes the chain.",nodeId:e.id,sources:e.sources,confidence:.9});let m=n.filter(u=>u.confidence<.6);for(let u of m.slice(0,6))a.push({id:`diagnostic_${I(`confidence:${u.id}`)}`,code:"CHAIN_LOW_CONFIDENCE",severity:"warning",message:`The step \u201C${u.label}\u201D is inferred with ${Math.round(u.confidence*100)}% confidence.`,suggestion:"Confirm the call relationship or add a clearer workflow, agent, tool, or service name.",nodeId:u.id,sources:u.sources,confidence:u.confidence});for(let u of t.filter(p=>p.control==="retry"&&p.metadata?.retryBounded!==!0)){let p=r.get(u.source);a.push({id:`diagnostic_${I(`retry:${u.id}`)}`,code:"CHAIN_RETRY_WITHOUT_LIMIT",severity:"warning",message:"A retry path was detected without a statically resolvable attempt limit.",suggestion:"Set a maximum retry count, backoff policy, and explicit failure exit.",nodeId:u.source,edgeId:u.id,sources:p?.sources??[],confidence:.82})}let h=le(t);for(let u of n.filter(p=>p.type==="external_system")){let p=t.filter(b=>b.target===u.id).flatMap(b=>r.get(b.source)??[]),y=p.some(b=>Number(b.metadata?.catches??0)>0||(h.get(b.id)??[]).some(C=>C.control==="fallback"));p.length&&!y&&a.push({id:`diagnostic_${I(`fallback:${u.id}`)}`,code:"CHAIN_EXTERNAL_NO_FALLBACK",severity:"info",message:`The external call to ${u.label} has no statically resolvable fallback path.`,suggestion:"Add error handling, a bounded retry, or a degraded response for this dependency.",nodeId:u.id,sources:u.sources,confidence:.72})}for(let u of n.filter(p=>p.type==="ai_process")){let p=(h.get(u.id)??[]).filter(b=>{let C=r.get(b.target);return C&&!["data","external_system","model"].includes(C.type)}),y=typeof u.metadata?.returnType=="string"?u.metadata.returnType:"";!p.length&&/(^|<)(void|undefined)(>|$)/i.test(y)&&u.metadata?.terminal!==!0&&a.push({id:`diagnostic_${I(`agent-output:${u.id}`)}`,code:"CHAIN_AGENT_NO_OUTPUT",severity:"warning",message:`The Agent step \u201C${u.label}\u201D has no structured output or downstream handoff.`,suggestion:"Declare an output type or schema, persist a result, or connect the Agent to its next step.",nodeId:u.id,sources:u.sources,confidence:.86})}return(s>ue||o)&&a.push({id:`diagnostic_${I(`limit:${e.id}`)}`,code:"CHAIN_PATH_LIMIT",severity:"warning",message:o?`The feature has more than ${Ge} branches or exceeds ${Oe} steps; simulation uses a bounded path set.`:`The feature reaches ${s} nodes; simulation is limited to ${ue}.`,suggestion:"Increase graph compression or split the feature into explicit workflows.",nodeId:e.id,sources:e.sources,confidence:1}),a}function Wi(e,n,t,i,r){let s=n.map(d=>d.id),o=wt(`variant_${I(`${e}:all`)}`,i.paths.length>1?"All paths":"Default path",i.paths.length>1?"Checks every inferred branch in the feature.":"Checks the inferred execution path.",e,s,t.map(d=>d.id),t,r);if(i.paths.length<=1)return[o];let a=i.paths.slice(0,Ge).map((d,c)=>{let g=Yi(d.nodeIds,t,r),l=new Set(g),m=t.filter(u=>l.has(u.source)&&l.has(u.target)).map(u=>u.id),h=r.get(d.nodeIds.at(-1)??"");return wt(`variant_${I(`${e}:${d.edgeIds.join(":")}`)}`,`Path ${c+1}${h?` \xB7 ${h.label}`:""}`,`Checks the branch that reaches ${h?.label??"its terminal step"}.`,e,g,m,t,r)});return[o,...a]}function wt(e,n,t,i,r,s,o,a){let d=new Set(r),c=o.filter(u=>s.includes(u.id)),g=Ji(i,d,c),l=[...d].map(u=>a.get(u)).find(u=>u?.type==="result")??[...d].map(u=>a.get(u)).find(u=>u&&!c.some(p=>p.source===u.id)),m=[...d].flatMap(u=>a.get(u)?[a.get(u).confidence]:[]),h=m.length?F(Math.min(...m)):0;return{id:e,label:n,description:t,nodeIds:[...d],edgeIds:s,steps:g,resultNodeId:l?.id,confidence:h}}function Ji(e,n,t){let i=new Map([[e,0]]),r=[e];for(;r.length;){let o=r.shift();if(!o)continue;let a=i.get(o)??0;for(let d of t.filter(c=>c.source===o)){if(!n.has(d.target))continue;let c=a+1;(!i.has(d.target)||c<i.get(d.target))&&(i.set(d.target,c),r.push(d.target))}}let s=Math.max(0,...i.values());return Array.from({length:s+1},(o,a)=>{let d=[...n].filter(c=>i.get(c)===a);return{order:a,nodeIds:d,incomingEdgeIds:t.filter(c=>d.includes(c.target)&&i.has(c.source)).map(c=>c.id)}}).filter(o=>o.nodeIds.length>0)}function Xi(e,n,t,i){let r=[],s=!1,o=t.filter(c=>{let g=i.get(c.target);return g&&!bt.has(g.type)}),a=le(o);function d(c,g,l,m){if(r.length>=Ge){s=!0;return}let h=(a.get(c)??[]).filter(u=>n.has(u.target)&&!m.has(u.target));if(!h.length||g.length>=Oe){r.push({nodeIds:g,edgeIds:l}),g.length>=Oe&&(s=!0);return}for(let u of h)d(u.target,[...g,u.target],[...l,u.id],new Set([...m,u.target]))}return d(e,[e],[],new Set([e])),{paths:r.length?r:[{nodeIds:[e],edgeIds:[]}],truncated:s}}function Yi(e,n,t){let i=new Set(e);for(let r of n){let s=t.get(r.target);i.has(r.source)&&s&&bt.has(s.type)&&i.add(s.id)}return[...i]}function Zi(e,n,t){let i=[e],r=new Set;for(;i.length;){let s=i.shift();if(!s||r.has(s))continue;r.add(s);let o=t.get(s);if(o?.type==="entrypoint")return o;i.push(...(n.get(s)??[]).map(a=>a.target))}}function xt(e,n){let t=new Set,i=[e];for(;i.length&&t.size<ue+1;){let r=i.shift();!r||t.has(r)||(t.add(r),i.push(...(n.get(r)??[]).map(s=>s.target)))}return t}function Qi(e,n){let t=new Map(e.map(a=>[a.id,a])),i=le(n),r=new Set,s=new Set;function o(a){if(r.has(a))return t.get(a);if(!s.has(a)){r.add(a);for(let d of i.get(a)??[]){let c=o(d.target);if(c)return c}r.delete(a),s.add(a)}}for(let a of e){let d=o(a.id);if(d)return d}}function le(e){let n=new Map;for(let t of e)n.set(t.source,[...n.get(t.source)??[],t]);return n}function er(e){let n=new Map;for(let t of e)n.set(t.target,[...n.get(t.target)??[],t]);return n}function tr(e){return e.some(n=>n.severity==="error")?"error":e.some(n=>n.severity==="warning")?"warning":"healthy"}function yt(e){return e==="error"?2:e==="warning"?1:0}function nr(e){let n=new Set;return e.filter(t=>!n.has(t.id)&&!!n.add(t.id))}function I(e){return zi("sha1").update(e).digest("hex").slice(0,12)}var Ct=new Set(["calls","data_flow","handles","reads","writes","requests"]);function vt(e,n={}){let t=Math.max(4,n.maxNodes??40),i=[...e.diagnostics],r=ar(e.edges),s=e.nodes.filter(u=>sr(u,r.get(u.id)??0)),o=cr(s,r),a=o.slice(0,t),d=new Set(a.map(u=>u.id));o.length>a.length&&i.push({level:"info",code:"LOGIC_GRAPH_COMPRESSED",message:`Compressed ${o.length} business-relevant code nodes to the ${a.length} highest-signal logic nodes.`});let c=a.map(u=>dr(u,e.context?.capabilityHints??[])),g=new Map(c.map(u=>[u.rawNodeIds[0],u.id])),l=Sr(wr(e,d,g),c);kr(c,l),pr(c,l);let m=He(c,l,e.context?.capabilityHints??[]),h=n.graphType??"runtime_logic";return h==="product_logic"&&i.push({level:"info",code:"PRODUCT_LOGIC_CONTEXTUAL_INFERENCE",message:"Product logic combines code structure with README, docs, PRD, prompt, and configuration evidence when available; uncertain matches retain confidence scores."}),{schemaVersion:K,generatedAt:new Date().toISOString(),graphType:h,title:`${e.project.name} ${h==="runtime_logic"?"runtime logic":"product logic"}`,description:n.productDescription??e.context?.description??e.context?.documents.find(u=>u.kind==="readme")?.summary??(h==="runtime_logic"?"A static, evidence-backed view of how work flows through the codebase.":"A code-informed view of how user actions become product value."),project:e.project,understanding:Cr(e,c,n.productDescription),nodes:c,edges:l,features:m,diagnostics:i}}var rr=/^(assert|audit|cap|clamp|clone|debug|dedupe|ensure|equals|error|format|from|get|has|hash|id|is|log|map|merge|noop|normali[sz]e|now|parse|pick|print|require|serialize|set|sleep|sort|to|trace|trim|truncate|unique|validate|warn|wrap)([A-Z_]|$)/;function or(e){let n=e&&`${e[0].toLowerCase()}${e.slice(1)}`;return rr.test(n)}function sr(e,n){return e.kind==="route"||e.kind==="database"||e.kind==="external_api"?!0:["service","agent","workflow","tool","human_gate"].includes(e.kind)?n===0&&ge(e)<=.5?!1:n>0||!or(e.name):e.kind==="function"?/^(handle|on)(submit|click|upload|save|create|generate)|submit|upload/i.test(e.name):["model","prompt"].includes(e.kind)?n>0:!1}function ar(e){let n=new Map;for(let t of e)Ct.has(t.kind)&&(n.set(t.source,(n.get(t.source)??0)+1),n.set(t.target,(n.get(t.target)??0)+1));return n}function cr(e,n){let t={route:100,agent:95,workflow:98,tool:85,model:81,prompt:64,human_gate:92,database:82,external_api:80,service:75,function:60,entrypoint:30,class:20,file:0};return[...e].sort((i,r)=>{let s=t[i.kind]+(n.get(i.id)??0)*4+ge(i)*20;return t[r.kind]+(n.get(r.id)??0)*4+ge(r)*20-s||i.name.localeCompare(r.name)})}function dr(e,n){let t=ur(e),i=ge(e),r=e.evidence.some(a=>a.method.includes("heuristic")||a.method==="framework_convention"),s=Er(`${e.name} ${e.qualifiedName??""} ${e.description??""}`,n),o=$r(s);return{id:`logic_${e.id}`,type:t,label:lr(e),description:hr(e,t),sources:_r(e.evidence.map(a=>a.source)),confidence:F(i),inference:{method:r?"heuristic":"deterministic",explanation:e.evidence.map(a=>a.detail).join("; ")},rawNodeIds:[e.id],product:o,metadata:{rawKind:e.kind,rawName:e.name,documentedCapabilityId:s?.capability.id,documentedCapabilityLabel:s?.capability.label,generatedDescription:!e.description,...e.metadata}}}function ur(e){return e.kind==="function"&&/submit|click|upload/i.test(e.name)?"user_action":e.kind==="route"?"entrypoint":e.kind==="workflow"?"workflow":e.kind==="agent"?"ai_process":e.kind==="tool"?"tool":e.kind==="model"?"model":e.kind==="human_gate"?"human_gate":e.kind==="prompt"||e.kind==="database"?"data":e.kind==="external_api"?"external_system":"process"}function lr(e){if(e.kind==="route"){let n=typeof e.metadata?.method=="string"?e.metadata.method:void 0,t=typeof e.metadata?.path=="string"?e.metadata.path:void 0;if(n&&t)return`${n.toUpperCase()} ${t}`}return e.kind==="external_api"?e.name:Rr(pe(e.name).replace(/\b(agent|service|handler|controller|workflow|orchestrator)\b/gi,"").trim()||pe(e.name))}var gr=4;function pr(e,n){let t=new Map(e.map(i=>[i.id,i]));for(let i of e){let r={calls:[],branches:[],requests:[],data:[],feeds:[]};for(let o of n){if(o.source!==i.id)continue;let a=t.get(o.target);a&&(a.type==="model"||a.type==="external_system"?te(r.requests,a.id):a.type==="data"?te(r.data,a.id):o.control==="conditional"||o.control==="fallback"?te(r.branches,a.id):o.type==="data_flow"?te(r.feeds,a.id):te(r.calls,a.id))}if(i.behavior=r,i.metadata?.generatedDescription!==!0)continue;let s=fr(r,o=>t.get(o)?.label??o);s&&(i.description=s)}}function te(e,n){e.includes(n)||e.push(n)}function fr(e,n){let t=(a,d)=>mr(a.map(n),d),i=[e.calls.length?`calls ${t(e.calls,"and")}`:void 0,e.branches.length?`branches to ${t(e.branches,"or")}`:void 0,e.requests.length?`requests ${t(e.requests,"and")}`:void 0,e.data.length?`reads or writes ${t(e.data,"and")}`:void 0,e.feeds.length?`passes its result to ${t(e.feeds,"and")}`:void 0].filter(a=>!!a);if(!i.length)return;let[r,...s]=i,o=r.charAt(0).toUpperCase()+r.slice(1);return s.length?`${[o,...s.slice(0,-1)].join(", ")}, and ${s.at(-1)}.`:`${o}.`}function mr(e,n){let t=e.slice(0,gr),i=e.length>t.length?` and ${e.length-t.length} more`:"";return t.length===1?`${t[0]}${i}`:t.length===2&&!i?`${t[0]} ${n} ${t[1]}`:`${t.slice(0,-1).join(", ")}, ${n} ${t.at(-1)}${i}`}function hr(e,n){if(e.description)return e.description;let t=pe(e.name).replace(/\b(agent|service|handler|controller)\b/gi,"").replace(/\s+/g," ").trim().toLowerCase();return{user_action:`The user initiates ${t}.`,entrypoint:`The system receives work through ${e.name}.`,process:`The system runs ${t}.`,workflow:`The workflow coordinates ${t}.`,ai_process:`An AI workflow performs ${t}.`,tool:`An Agent uses the tool ${t}.`,model:`The Agent uses the model ${e.name}.`,human_gate:`A person reviews or approves ${t}.`,decision:`The system evaluates ${t}.`,data:`The system reads or changes ${t}.`,external_system:`The flow communicates with ${e.name}.`,result:`The flow produces ${t}.`}[n]}function wr(e,n,t){let i=new Map;for(let s of e.edges){if(!Ct.has(s.kind))continue;let o=i.get(s.source)??[];o.push(s),i.set(s.source,o)}let r=[];for(let s of n){let o=[...i.get(s)??[]].map(d=>({nodeId:d.target,path:[d]})),a=new Set;for(;o.length;){let d=o.shift();if(!(!d||a.has(d.nodeId))){if(a.add(d.nodeId),n.has(d.nodeId)){let c=t.get(s),g=t.get(d.nodeId);c&&g&&c!==g&&r.push(yr(c,g,d.path));continue}if(!(d.path.length>=8))for(let c of i.get(d.nodeId)??[])o.push({nodeId:c.target,path:[...d.path,c]})}}}return Nr(r)}function yr(e,n,t){let i=new Set(t.map(o=>o.kind)),r=br(t.map(o=>o.control)),s=i.has("data_flow")||i.has("reads")||i.has("writes")?"data_flow":r==="conditional"||r==="fallback"||r==="human_approval"?"branch":"flow";return{id:`logic_edge_${Pr(`${e}:${s}:${r??"sequential"}:${n}`)}`,source:e,target:n,type:s,label:t.find(o=>o.label)?.label??xr(r),control:r,metadata:r?{retryBounded:r==="retry"?t.some(o=>o.metadata?.retryBounded===!0):void 0,rawControls:[...new Set(t.flatMap(o=>o.control?[o.control]:[]))]}:void 0,confidence:F(Math.min(...t.flatMap(o=>o.evidence.map(a=>a.confidence)))),rawEdgeIds:t.map(o=>o.id)}}function br(e){return["human_approval","fallback","retry","loop","parallel","conditional","sequential"].find(t=>e.includes(t))}function xr(e){return e&&e!=="sequential"?e.replace("_"," "):void 0}function Cr(e,n,t){let i=e.context,r=t??i?.description??i?.documents.find(a=>a.kind==="readme")?.summary??`An evidence-backed understanding of ${e.project.name}.`,s=i?.capabilityHints??[],o=s.length?Math.min(1,s.reduce((a,d)=>a+d.confidence,0)/s.length):i?.documents.length?.7:.55;return{summary:r,capabilities:s,agentNodeIds:n.filter(a=>a.type==="ai_process").map(a=>a.id),workflowNodeIds:n.filter(a=>a.type==="workflow").map(a=>a.id),toolNodeIds:n.filter(a=>a.type==="tool").map(a=>a.id),modelNodeIds:n.filter(a=>a.type==="model").map(a=>a.id),documentsUsed:i?.documents.map(a=>a.path)??[],confidence:F(o)}}var vr=2;function Er(e,n){let t=ze(e),i;for(let r of n){let s=ze(r.label),o=r.keywords.filter(c=>t.includes(ze(c))),a=s.length>=3&&t.includes(s)?3:0,d=a+o.length;d>0&&(!i||d>i.score||d===i.score&&r.confidence>i.capability.confidence)&&(i={capability:r,score:d,matchedOn:a?"documented_name":"documented_terms",matchedTerms:a?[r.label]:o.slice(0,4)})}return i}function $r(e){if(!(!e||e.score<vr))return{capabilityId:e.capability.id,label:e.capability.label,origin:e.capability.origin,sources:e.capability.sources,match:F(Math.min(.95,.4+e.score*.15)*e.capability.confidence),matchedOn:e.matchedOn,matchedTerms:e.matchedTerms}}function ze(e){return pe(e).toLowerCase().replace(/\b(agent|api|handler|route|service|workflow)\b/g," ").replace(/\s+/g," ").trim()}function Sr(e,n){let t=new Map(n.map(i=>[i.id,i.type]));return e.filter(i=>{if(i.type!=="flow"||["external_system","data"].includes(t.get(i.target)??""))return!0;let r=new Map;for(let a of e){if(a.id===i.id)continue;let d=r.get(a.source)??[];d.push(a.target),r.set(a.source,d)}let s=[...r.get(i.source)??[]],o=new Set;for(;s.length;){let a=s.shift();if(!(!a||o.has(a))){if(a===i.target)return!1;o.add(a),s.push(...r.get(a)??[])}}return!0})}function kr(e,n){let t=new Set(n.map(i=>i.source));for(let i of e)!t.has(i.id)&&i.type==="process"&&!/save|store|persist/i.test(i.label)&&(i.type="result",i.description=`The flow produces ${i.label.toLowerCase()}.`)}function ge(e){return e.evidence.length?Math.max(...e.evidence.map(n=>n.confidence)):.5}function pe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_/.]+/g," ").replace(/\s+/g," ").trim()}function Rr(e){return e.replace(/\b\w/g,n=>n.toUpperCase())}function _r(e){let n=new Set;return e.filter(t=>{let i=`${t.file}:${t.startLine}`;return n.has(i)?!1:(n.add(i),!0)})}function Nr(e){let n=new Set;return e.filter(t=>{let i=`${t.source}:${t.target}:${t.type}:${t.control??"sequential"}`;return n.has(i)?!1:(n.add(i),!0)})}function Pr(e){return ir("sha1").update(e).digest("hex").slice(0,12)}import{createHash as Ar}from"crypto";import{access as Lr,open as Ir,readFile as St,readdir as kt}from"fs/promises";import T from"path";var Tr=new Set([".git",".next",".logic-map",".turbo","build","coverage","dist","node_modules","out"]),Ve=new Set([".md",".mdx",".txt",".rst"]),Dr=new Set([".md",".mdx",".txt",".yaml",".yml",".json"]),jr=new Set(["agent-runtime-map.config.json","package.json","tsconfig.json","jsconfig.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.ts","wrangler.json","wrangler.toml"]),Fr=/(^|\/)(?:\.env(?:\.[^\/]*)?|[^\/]*\.(?:pem|key|p12|pfx)|(?:credentials?|secrets?)(?:[._-][^\/]*)?)(?:\/|$)/i,Rt=/^(about|api|architecture|configuration|contents?|contributing|development|docs?|features?|getting started|installation|license|overview|quick ?start|roadmap|setup|tests?|usage|关于|功能|功能列表|安装|开始|开发|架构|概览|目录|配置|使用|路线图)$/i;async function _t(e,n={}){let t=T.resolve(e),i=[],r=n.maxDocuments??80,s=n.maxDocumentBytes??96e3,o=n.maxTotalBytes??75e4,a=await Yr(t,i),d=await Zr(t,i),c=(await Mr(t)).slice(0,r),g=[],l=[],m=0;for(let u of c){if(m>=o)break;let p=Math.min(s,o-m),y=await Gr(u.absolute,p);if(!y)continue;m+=y.bytesRead;let b=Wr(u.relative,y.text),C=Pt(y.text);g.push({path:u.relative,kind:u.kind,title:b,summary:Jr(y.text,b),headings:C.map(w=>w.label).slice(0,32),excerpt:$t(y.text,6e3),truncated:y.truncated}),u.kind==="prompt"&&l.push({path:u.relative,name:b,excerpt:$t(y.text,6e3),variables:Xr(y.text),source:"file"})}c.length>=r&&i.push({level:"warning",code:"PROJECT_CONTEXT_FILE_LIMIT",message:`Project context reading was limited to ${r} documentation and prompt files.`}),m>=o&&i.push({level:"warning",code:"PROJECT_CONTEXT_BYTE_LIMIT",message:`Project context reading reached the ${o}-byte safety limit.`});let h=Ur([...Kr(n.productDescription),...qr(d),...g.flatMap(Hr),...l.flatMap(Vr)]).slice(0,48);return{description:d.description??fe(a.description,600),packageManager:await to(t),scripts:Object.keys(W(a.scripts)).sort(),dependencies:Qr(a),documents:g,prompts:l,configurationFiles:await eo(t),capabilityHints:h,diagnostics:i}}async function Mr(e){let n=[];async function t(i,r){if(r>5)return;let s;try{s=await kt(i,{withFileTypes:!0})}catch{return}s.sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){let a=T.join(i,o.name),d=io(e,a);if(o.isDirectory()){!Tr.has(o.name)&&!o.name.startsWith(".")&&await t(a,r+1);continue}if(!o.isFile()||Fr.test(d))continue;let c=Or(d);c&&n.push({absolute:a,relative:d,kind:c})}}return await t(e,0),n.sort((i,r)=>Et(i)-Et(r)||i.relative.localeCompare(r.relative))}function Or(e){let n=e.toLowerCase(),t=T.posix.basename(n),i=T.posix.extname(t);if(/^readme(?:\.|$)/.test(t)&&Ve.has(i))return"readme";if(/(^|\/)(prd|product[-_ ]?requirements?)(\.|\/)/.test(n)&&Ve.has(i))return"prd";if(/(^|\/)(prompts?|instructions?|system-prompts?)(\/|\.|$)/.test(n)&&Dr.has(i))return"prompt";if((n.startsWith("docs/")||n.includes("/docs/"))&&Ve.has(i))return"documentation"}function Et(e){return e.kind==="readme"?0:e.kind==="prd"?1:e.kind==="prompt"?2:3}async function Gr(e,n){let t;try{t=await Ir(e,"r");let i=await t.stat(),r=Math.min(i.size,Math.max(0,n)),s=Buffer.alloc(r),o=await t.read(s,0,r,0),a=s.subarray(0,o.bytesRead);return a.includes(0)?void 0:{text:a.toString("utf8"),bytesRead:o.bytesRead,truncated:i.size>o.bytesRead}}catch{return}finally{await t?.close().catch(()=>{})}}function Hr(e){let n=e.excerpt.split(/\r?\n/),t=[];for(let i=0;i<n.length;i+=1){let r=n[i]??"",s=/^(#{2,4})\s+(.+?)\s*$/.exec(r),o=/^\s*[-*+]\s+\*\*(.+?)\*\*\s*[::-]?\s*(.*)$/.exec(r),a=V(s?.[2]??o?.[1]??"");if(!Nt(a))continue;let d=V(o?.[2]||Br(n,i+1));t.push({id:`capability_${we(`${e.path}:${i+1}:${a}`)}`,label:a,description:d||`Project documentation describes ${a}.`,keywords:me(`${a} ${d}`),origin:zr(e.kind),sources:[{file:e.path,startLine:i+1}],confidence:e.kind==="prd"?.9:e.kind==="readme"?.8:.74})}return t}function zr(e){return e==="readme"?"readme":e==="prd"?"prd":e==="prompt"?"prompt":"docs"}function Vr(e){let n=V(e.name);if(!Nt(n))return[];let t=At(e.excerpt);return t?[{id:`capability_${we(`prompt:${e.path}:${n}`)}`,label:n,description:t,keywords:me(`${n} ${t}`),origin:"prompt",sources:[{file:e.path,startLine:1,symbol:e.name}],confidence:.7}]:[]}function Kr(e){let n=e?.trim();return n?[{id:`capability_${we(`user:${n}`)}`,label:V(At(n))||n.slice(0,80),description:n.slice(0,600),keywords:me(n),origin:"user",sources:[],confidence:1}]:[]}function qr(e){return Object.entries(e.features??{}).map(([n,t])=>{let i=t.label?.trim()||qe(n);return{id:`capability_${we(`config:${n}`)}`,label:i,description:t.description?.trim()||`Configured project capability ${i}.`,keywords:he([...t.keywords??[],...me(`${n} ${i} ${t.description??""}`)]),origin:"config",sources:[{file:"agent-runtime-map.config.json",startLine:1,symbol:n}],confidence:1}})}function Ur(e){let n=new Map;for(let t of e){let i=no(t.label),r=n.get(i);if(!r){n.set(i,t);continue}n.set(i,{...r,description:r.description.length>=t.description.length?r.description:t.description,keywords:he([...r.keywords,...t.keywords]),sources:oo([...r.sources,...t.sources]),confidence:Math.max(r.confidence,t.confidence)})}return[...n.values()]}function Nt(e){return!e||e.length<3||e.length>80||Rt.test(e)?!1:!/^(v?\d+(\.\d+)+|https?:|npm |pnpm |yarn )/i.test(e)}function Pt(e){return e.split(/\r?\n/).flatMap((n,t)=>{let i=/^(#{1,4})\s+(.+?)\s*$/.exec(n);return i?[{label:V(i[2]??""),line:t+1}]:[]})}function Br(e,n){for(let t=n;t<Math.min(e.length,n+5);t+=1){let i=e[t]?.trim()??"";if(i&&!i.startsWith("#")&&!i.startsWith("```")&&!/^[-*_]{3,}$/.test(i))return i}return""}function Wr(e,n){return Pt(n)[0]?.label||qe(T.posix.basename(e,T.posix.extname(e)))}function Jr(e,n){return(e.split(/\r?\n/).map(r=>V(r)).find(r=>r&&r!==n&&!Rt.test(r)&&!r.startsWith("```"))||n).slice(0,320)}function Xr(e){let n=[...e.matchAll(/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g),...e.matchAll(/\$\{\s*([A-Za-z_][\w.-]*)\s*\}/g)].map(t=>t[1]).filter(t=>!!t);return he(n).slice(0,40)}function $t(e,n){return e.replace(/\r\n/g,`
|
|
2
|
+
import{parseArgs as ba}from"util";import{mkdir as na,stat as ia,writeFile as ra}from"fs/promises";import Ue from"path";import{access as gi,readFile as Ft}from"fs/promises";import F from"path";import{Node as p,Project as pi,ScriptTarget as fi,SyntaxKind as z}from"ts-morph";var ne="0.1.0";function V(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}import{createHash as oi}from"crypto";import{readdir as si}from"fs/promises";import Ee from"path";var ti={add:{zhCN:"\u6DFB\u52A0"},aggregate:{zhCN:"\u6C47\u603B"},analyze:{zhCN:"\u5206\u6790"},append:{zhCN:"\u8FFD\u52A0"},apply:{zhCN:"\u5E94\u7528"},approve:{zhCN:"\u6279\u51C6"},archive:{zhCN:"\u5F52\u6863"},assess:{zhCN:"\u8BC4\u4F30"},assign:{zhCN:"\u5206\u914D"},attach:{zhCN:"\u9644\u52A0"},authorize:{zhCN:"\u6388\u6743"},build:{zhCN:"\u7EC4\u88C5"},calculate:{zhCN:"\u8BA1\u7B97"},cancel:{zhCN:"\u53D6\u6D88"},capture:{zhCN:"\u91C7\u96C6"},check:{zhCN:"\u68C0\u67E5"},classify:{zhCN:"\u5206\u7C7B"},clean:{zhCN:"\u6E05\u7406"},collect:{zhCN:"\u6536\u96C6"},compile:{zhCN:"\u7F16\u8BD1"},compose:{zhCN:"\u7F16\u6392"},compute:{zhCN:"\u8BA1\u7B97"},confirm:{zhCN:"\u786E\u8BA4"},convert:{zhCN:"\u8F6C\u6362"},create:{zhCN:"\u521B\u5EFA"},delete:{zhCN:"\u5220\u9664"},deliver:{zhCN:"\u6295\u9012"},detect:{zhCN:"\u68C0\u6D4B"},dispatch:{zhCN:"\u6D3E\u53D1"},download:{zhCN:"\u4E0B\u8F7D"},draft:{zhCN:"\u8D77\u8349"},enrich:{zhCN:"\u8865\u5168"},evaluate:{zhCN:"\u8BC4\u4F30"},execute:{zhCN:"\u6267\u884C"},export:{zhCN:"\u5BFC\u51FA"},extract:{zhCN:"\u63D0\u53D6"},fetch:{zhCN:"\u83B7\u53D6"},filter:{zhCN:"\u7B5B\u9009"},finalize:{zhCN:"\u5B9A\u7A3F"},find:{zhCN:"\u67E5\u627E"},generate:{zhCN:"\u751F\u6210"},get:{zhCN:"\u8BFB\u53D6"},grade:{zhCN:"\u8BC4\u7EA7"},handle:{zhCN:"\u5904\u7406"},import:{zhCN:"\u5BFC\u5165"},index:{zhCN:"\u7D22\u5F15"},ingest:{zhCN:"\u63A5\u5165"},initialize:{zhCN:"\u521D\u59CB\u5316"},invoke:{zhCN:"\u8C03\u7528"},list:{zhCN:"\u5217\u51FA"},load:{zhCN:"\u52A0\u8F7D"},lock:{zhCN:"\u9501\u5B9A"},match:{zhCN:"\u5339\u914D"},merge:{zhCN:"\u5408\u5E76"},moderate:{zhCN:"\u5BA1\u6838"},notify:{zhCN:"\u901A\u77E5"},parse:{zhCN:"\u89E3\u6790"},persist:{zhCN:"\u6301\u4E45\u5316"},plan:{zhCN:"\u89C4\u5212"},poll:{zhCN:"\u8F6E\u8BE2"},prepare:{zhCN:"\u51C6\u5907"},process:{zhCN:"\u5904\u7406"},publish:{zhCN:"\u53D1\u5E03"},purge:{zhCN:"\u6E05\u9664"},query:{zhCN:"\u67E5\u8BE2"},queue:{zhCN:"\u6392\u961F"},rank:{zhCN:"\u6392\u5E8F"},read:{zhCN:"\u8BFB\u53D6"},rebuild:{zhCN:"\u91CD\u5EFA"},receive:{zhCN:"\u63A5\u6536"},record:{zhCN:"\u8BB0\u5F55"},refresh:{zhCN:"\u5237\u65B0"},register:{zhCN:"\u6CE8\u518C"},reject:{zhCN:"\u62D2\u7EDD"},release:{zhCN:"\u53D1\u5E03"},remove:{zhCN:"\u79FB\u9664"},render:{zhCN:"\u6E32\u67D3"},resolve:{zhCN:"\u89E3\u6790"},retrieve:{zhCN:"\u68C0\u7D22"},retry:{zhCN:"\u91CD\u8BD5"},review:{zhCN:"\u5BA1\u6838"},revise:{zhCN:"\u4FEE\u6539"},run:{zhCN:"\u8FD0\u884C"},save:{zhCN:"\u4FDD\u5B58"},schedule:{zhCN:"\u8C03\u5EA6"},score:{zhCN:"\u8BC4\u5206"},search:{zhCN:"\u641C\u7D22"},select:{zhCN:"\u9009\u62E9"},send:{zhCN:"\u53D1\u9001"},split:{zhCN:"\u62C6\u5206"},store:{zhCN:"\u5B58\u50A8"},stream:{zhCN:"\u4F20\u8F93"},submit:{zhCN:"\u63D0\u4EA4"},summarize:{zhCN:"\u603B\u7ED3"},sync:{zhCN:"\u540C\u6B65"},track:{zhCN:"\u8DDF\u8E2A"},transcribe:{zhCN:"\u8F6C\u5199"},transform:{zhCN:"\u8F6C\u6362"},translate:{zhCN:"\u7FFB\u8BD1"},trigger:{zhCN:"\u89E6\u53D1"},update:{zhCN:"\u66F4\u65B0"},upload:{zhCN:"\u4E0A\u4F20"},upsert:{zhCN:"\u5199\u5165"},validate:{zhCN:"\u6821\u9A8C"},verify:{zhCN:"\u9A8C\u8BC1"},write:{zhCN:"\u5199\u5165"},lookup:{zhCN:"\u67E5\u8BE2"},probe:{zhCN:"\u63A2\u6D4B"},seed:{zhCN:"\u521D\u59CB\u5316"},serve:{zhCN:"\u670D\u52A1"},start:{zhCN:"\u542F\u52A8"},stop:{zhCN:"\u505C\u6B62"},subscribe:{zhCN:"\u8BA2\u9605"},test:{zhCN:"\u6D4B\u8BD5"},toggle:{zhCN:"\u5207\u6362"},unlock:{zhCN:"\u89E3\u9501"},watch:{zhCN:"\u76D1\u542C"}},ni={account:{zhCN:"\u8D26\u6237"},action:{zhCN:"\u52A8\u4F5C"},agent:{zhCN:"\u667A\u80FD\u4F53"},answer:{zhCN:"\u56DE\u7B54"},api:{zhCN:"\u63A5\u53E3",enUS:"API"},approval:{zhCN:"\u5BA1\u6279"},article:{zhCN:"\u6587\u7AE0"},attempt:{zhCN:"\u5C1D\u8BD5"},audio:{zhCN:"\u97F3\u9891"},batch:{zhCN:"\u6279\u6B21"},billing:{zhCN:"\u8BA1\u8D39"},cache:{zhCN:"\u7F13\u5B58"},campaign:{zhCN:"\u6D3B\u52A8"},cart:{zhCN:"\u8D2D\u7269\u8F66"},category:{zhCN:"\u5206\u7C7B"},chat:{zhCN:"\u5BF9\u8BDD"},checkout:{zhCN:"\u7ED3\u7B97"},chunk:{zhCN:"\u5206\u5757"},comment:{zhCN:"\u8BC4\u8BBA"},config:{zhCN:"\u914D\u7F6E"},content:{zhCN:"\u5185\u5BB9"},context:{zhCN:"\u4E0A\u4E0B\u6587"},conversation:{zhCN:"\u4F1A\u8BDD"},customer:{zhCN:"\u5BA2\u6237"},data:{zhCN:"\u6570\u636E"},database:{zhCN:"\u6570\u636E\u5E93"},decision:{zhCN:"\u51B3\u7B56"},detail:{zhCN:"\u8BE6\u60C5"},digest:{zhCN:"\u6458\u8981"},document:{zhCN:"\u6587\u6863"},draft:{zhCN:"\u8349\u7A3F"},email:{zhCN:"\u90AE\u4EF6"},embedding:{zhCN:"\u5411\u91CF"},entry:{zhCN:"\u6761\u76EE"},error:{zhCN:"\u9519\u8BEF"},event:{zhCN:"\u4E8B\u4EF6"},evidence:{zhCN:"\u8BC1\u636E"},feedback:{zhCN:"\u53CD\u9988"},file:{zhCN:"\u6587\u4EF6"},gate:{zhCN:"\u5173\u5361"},idea:{zhCN:"\u521B\u610F"},image:{zhCN:"\u56FE\u7247"},input:{zhCN:"\u8F93\u5165"},instruction:{zhCN:"\u6307\u4EE4"},intent:{zhCN:"\u610F\u56FE"},invoice:{zhCN:"\u8D26\u5355"},item:{zhCN:"\u6761\u76EE"},job:{zhCN:"\u4F5C\u4E1A"},knowledge:{zhCN:"\u77E5\u8BC6"},label:{zhCN:"\u6807\u7B7E"},language:{zhCN:"\u8BED\u8A00"},layout:{zhCN:"\u5E03\u5C40"},lead:{zhCN:"\u7EBF\u7D22"},log:{zhCN:"\u65E5\u5FD7"},message:{zhCN:"\u6D88\u606F"},meta:{zhCN:"\u5143\u4FE1\u606F"},metric:{zhCN:"\u6307\u6807"},model:{zhCN:"\u6A21\u578B"},notification:{zhCN:"\u901A\u77E5"},order:{zhCN:"\u8BA2\u5355"},output:{zhCN:"\u8F93\u51FA"},page:{zhCN:"\u9875\u9762"},payment:{zhCN:"\u652F\u4ED8"},permission:{zhCN:"\u6743\u9650"},photo:{zhCN:"\u7167\u7247"},pipeline:{zhCN:"\u6D41\u6C34\u7EBF"},plan:{zhCN:"\u8BA1\u5212"},policy:{zhCN:"\u7B56\u7565"},price:{zhCN:"\u4EF7\u683C"},product:{zhCN:"\u5546\u54C1"},profile:{zhCN:"\u6863\u6848"},project:{zhCN:"\u9879\u76EE"},prompt:{zhCN:"\u63D0\u793A\u8BCD"},quality:{zhCN:"\u8D28\u91CF"},query:{zhCN:"\u67E5\u8BE2"},question:{zhCN:"\u95EE\u9898"},quote:{zhCN:"\u62A5\u4EF7"},rating:{zhCN:"\u8BC4\u5206"},record:{zhCN:"\u8BB0\u5F55"},refund:{zhCN:"\u9000\u6B3E"},reply:{zhCN:"\u56DE\u590D"},report:{zhCN:"\u62A5\u544A"},request:{zhCN:"\u8BF7\u6C42"},response:{zhCN:"\u54CD\u5E94"},result:{zhCN:"\u7ED3\u679C"},review:{zhCN:"\u5BA1\u6838"},role:{zhCN:"\u89D2\u8272"},route:{zhCN:"\u8DEF\u7531"},rule:{zhCN:"\u89C4\u5219"},schedule:{zhCN:"\u6392\u671F"},scope:{zhCN:"\u8303\u56F4"},search:{zhCN:"\u641C\u7D22"},section:{zhCN:"\u7AE0\u8282"},session:{zhCN:"\u4F1A\u8BDD"},setting:{zhCN:"\u8BBE\u7F6E"},shipment:{zhCN:"\u7269\u6D41"},source:{zhCN:"\u6765\u6E90"},state:{zhCN:"\u72B6\u6001"},status:{zhCN:"\u72B6\u6001"},step:{zhCN:"\u6B65\u9AA4"},story:{zhCN:"\u6545\u4E8B"},stream:{zhCN:"\u6D41"},subscription:{zhCN:"\u8BA2\u9605"},summary:{zhCN:"\u6458\u8981"},task:{zhCN:"\u4EFB\u52A1"},template:{zhCN:"\u6A21\u677F"},text:{zhCN:"\u6587\u672C"},ticket:{zhCN:"\u5DE5\u5355"},tool:{zhCN:"\u5DE5\u5177"},topic:{zhCN:"\u4E3B\u9898"},transcript:{zhCN:"\u6587\u5B57\u8BB0\u5F55"},usage:{zhCN:"\u7528\u91CF"},user:{zhCN:"\u7528\u6237"},version:{zhCN:"\u7248\u672C"},video:{zhCN:"\u89C6\u9891"},voice:{zhCN:"\u8BED\u97F3"},webhook:{zhCN:"\u56DE\u8C03"},workflow:{zhCN:"\u5DE5\u4F5C\u6D41"},workspace:{zhCN:"\u5DE5\u4F5C\u533A"},attachment:{zhCN:"\u9644\u4EF6"},author:{zhCN:"\u4F5C\u8005"},balance:{zhCN:"\u4F59\u989D"},brief:{zhCN:"\u9700\u6C42\u8BF4\u660E"},budget:{zhCN:"\u9884\u7B97"},channel:{zhCN:"\u6E20\u9053"},client:{zhCN:"\u5BA2\u6237\u7AEF"},cost:{zhCN:"\u6210\u672C"},editor:{zhCN:"\u7F16\u8F91\u5668"},form:{zhCN:"\u8868\u5355"},history:{zhCN:"\u5386\u53F2"},ledger:{zhCN:"\u53F0\u8D26"},limit:{zhCN:"\u4E0A\u9650"},link:{zhCN:"\u94FE\u63A5"},member:{zhCN:"\u6210\u5458"},owner:{zhCN:"\u8D1F\u8D23\u4EBA"},parameter:{zhCN:"\u53C2\u6570"},reader:{zhCN:"\u8BFB\u53D6\u5668"},reviewer:{zhCN:"\u5BA1\u6838\u4EBA"},schema:{zhCN:"\u7ED3\u6784"},score:{zhCN:"\u8BC4\u5206"},segment:{zhCN:"\u7247\u6BB5"},server:{zhCN:"\u670D\u52A1\u7AEF"},slot:{zhCN:"\u6863\u4F4D"},snapshot:{zhCN:"\u5FEB\u7167"},team:{zhCN:"\u56E2\u961F"},thumbnail:{zhCN:"\u7F29\u7565\u56FE"},title:{zhCN:"\u6807\u9898"},track:{zhCN:"\u8F68\u9053"},writer:{zhCN:"\u5199\u5165\u5668"}},ii={active:{zhCN:"\u751F\u6548"},all:{zhCN:"\u5168\u90E8"},auto:{zhCN:"\u81EA\u52A8"},bulk:{zhCN:"\u6279\u91CF"},current:{zhCN:"\u5F53\u524D"},daily:{zhCN:"\u6BCF\u65E5"},default:{zhCN:"\u9ED8\u8BA4"},draft:{zhCN:"\u8349\u7A3F"},external:{zhCN:"\u5916\u90E8"},fallback:{zhCN:"\u515C\u5E95"},fast:{zhCN:"\u5FEB\u901F"},final:{zhCN:"\u6700\u7EC8"},full:{zhCN:"\u5B8C\u6574"},human:{zhCN:"\u4EBA\u5DE5"},initial:{zhCN:"\u521D\u59CB"},internal:{zhCN:"\u5185\u90E8"},latest:{zhCN:"\u6700\u65B0"},local:{zhCN:"\u672C\u5730"},manual:{zhCN:"\u624B\u52A8"},new:{zhCN:"\u65B0"},next:{zhCN:"\u4E0B\u4E00\u4E2A"},pending:{zhCN:"\u5F85\u5904\u7406"},primary:{zhCN:"\u4E3B\u8981"},private:{zhCN:"\u79C1\u6709"},public:{zhCN:"\u516C\u5F00"},raw:{zhCN:"\u539F\u59CB"},remote:{zhCN:"\u8FDC\u7A0B"},shared:{zhCN:"\u5171\u4EAB"},single:{zhCN:"\u5355\u4E2A"},static:{zhCN:"\u9759\u6001"},total:{zhCN:"\u603B\u8BA1"}},Pt={draft:{verb:{zhCN:"\u8D77\u8349"},noun:{zhCN:"\u8349\u7A3F"}},plan:{verb:{zhCN:"\u89C4\u5212"},noun:{zhCN:"\u8BA1\u5212"}},schedule:{verb:{zhCN:"\u8C03\u5EA6"},noun:{zhCN:"\u6392\u671F"}},stream:{verb:{zhCN:"\u4F20\u8F93"},noun:{zhCN:"\u6D41"}},track:{verb:{zhCN:"\u8DDF\u8E2A"},noun:{zhCN:"\u8F68\u9053"}},record:{verb:{zhCN:"\u8BB0\u5F55"},noun:{zhCN:"\u8BB0\u5F55"}},list:{verb:{zhCN:"\u5217\u51FA"},noun:{zhCN:"\u5217\u8868"}},post:{verb:{zhCN:"\u53D1\u5E03"},noun:{zhCN:"\u5E16\u5B50"}},review:{verb:{zhCN:"\u5BA1\u6838"},noun:{zhCN:"\u5BA1\u6838"}},score:{verb:{zhCN:"\u8BC4\u5206"},noun:{zhCN:"\u5206\u6570"}},process:{verb:{zhCN:"\u5904\u7406"},noun:{zhCN:"\u6D41\u7A0B"}},request:{verb:{zhCN:"\u8BF7\u6C42"},noun:{zhCN:"\u8BF7\u6C42"}},search:{verb:{zhCN:"\u641C\u7D22"},noun:{zhCN:"\u641C\u7D22"}},refund:{verb:{zhCN:"\u9000\u6B3E"},noun:{zhCN:"\u9000\u6B3E"}},query:{verb:{zhCN:"\u67E5\u8BE2"},noun:{zhCN:"\u67E5\u8BE2"}},index:{verb:{zhCN:"\u7D22\u5F15"},noun:{zhCN:"\u7D22\u5F15"}}},it=Object.assign(Object.create(null),ni,ii,ti);function It(e,n){let t=Object.prototype.hasOwnProperty.call(Pt,e)?Pt[e]:void 0;return t?n==="head"?t.verb:t.noun:Object.prototype.hasOwnProperty.call(it,e)?it[e]:void 0}var rt=new Set(["controller","handler","impl","middleware","provider","repository","service","usecase","util","utils","helper","helpers","wrapper"]),ri=new Set(["news","address","business","process","access","progress","status","class","balancing","bed","led","red","wed","fed","ted","sting","king","ring","thing","spring","string","during","ceiling","meeting","series","species"]),nt=e=>Object.prototype.hasOwnProperty.call(it,e);function Y(e){let n=e.toLowerCase();if(nt(n)||ri.has(n))return n;for(let[t,i]of[["ies","y"],["ses","s"],["es",""],["s",""],["ing",""],["ed",""]])if(n.length>t.length+2&&n.endsWith(t)){let r=n.slice(0,-t.length)+i;if(nt(r))return r;if(t==="ing"&&nt(`${r}e`))return`${r}e`}return n}function xe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[-_./]+/g," ").trim().split(/\s+/).filter(Boolean)}var ai=new Set([".git",".next",".logic-map",".turbo",".venv","__mocks__","__pycache__","__tests__","build","coverage","dist","node_modules","out","site-packages","venv"]),ci=/(^|\/)(scripts?|tools?\/dev|examples?|fixtures?|benchmarks?)(\/|$)/i,Dt=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]),ie=new Set(["agent","function","human_gate","route","service","tool","workflow"]),di=/^(is|has|can|should|must|assert|ensure|validate|to|as|from|parse|stringify|format|normali[sz]e|seriali[sz]e|deseriali[sz]e|encode|decode|escape|unescape|clone|merge|equals|compare|coerce|cast|wrap|unwrap|optional|required|default)[A-Z_]/,li=/^(boolean|string|number|bigint|symbol|void|null|undefined|unknown|any)(\s*\|\s*(null|undefined))*$/;function ui(e){if(di.test(e.name))return!0;let n=e.returnType?.trim();return!!(n&&li.test(n))}function ve(e,n){let t=n.exec(e);return t!==null&&t.index>0}function X(e){let n=e.relativeFile.toLowerCase(),t=e.name.toLowerCase(),i=/^(make|create|build|new|init)[A-Z]/.test(e.name),r=!ci.test(n)&&!ui(e);return e.routeConvention?{kind:"route",confidence:.95,detail:"Framework route handler convention",method:"framework_convention"}:/(^|\/)(page|layout)\.[jt]sx?$/.test(n)&&/(page|layout)$/.test(t)?{kind:"function",confidence:1,detail:"Declared in source",method:"ast"}:e.internal?{kind:"function",confidence:1,detail:"Private class member, treated as an implementation detail",method:"ast"}:!i&&ve(t,/(workflow|orchestrator|pipeline|graph|crew)$/)?{kind:"workflow",confidence:.84,detail:"Workflow or orchestrator naming convention",method:"name_heuristic"}:/(approve|approval|humanreview|human_review|humandecision|human_decision|confirm|moderate)/.test(t)?{kind:"human_gate",confidence:.68,detail:"Human approval or review naming convention",method:"name_heuristic"}:r&&/(^|\/)(workflows?|orchestrators?|pipelines?|graphs?|crews?)(\/|$)/.test(n)?{kind:"workflow",confidence:.72,detail:"Declared under a workflow or orchestrator directory",method:"path_heuristic"}:!i&&ve(t,/agent$/)?{kind:"agent",confidence:.84,detail:"Agent naming convention",method:"name_heuristic"}:r&&/(^|\/)(agents?)(\/|$)/.test(n)?{kind:"agent",confidence:.72,detail:"Declared under an Agent directory",method:"path_heuristic"}:!i&&ve(t,/(tool|action)$/)?{kind:"tool",confidence:.8,detail:"Tool or action naming convention",method:"name_heuristic"}:r&&/(^|\/)(tools?|actions?)(\/|$)/.test(n)?{kind:"tool",confidence:.65,detail:"Declared under a tool or action directory",method:"path_heuristic"}:!i&&ve(t,/(service|usecase)$/)?{kind:"service",confidence:.8,detail:"Service naming convention",method:"name_heuristic"}:r&&/(^|\/)(services?|use-cases?|commands?)(\/|$)/.test(n)?{kind:"service",confidence:.7,detail:"Declared under a service or use-case directory",method:"path_heuristic"}:e.enclosingClass&&/(service|controller|repository)$/i.test(e.enclosingClass)?{kind:"service",confidence:.6,detail:"Public member of a service, controller, or repository class",method:"name_heuristic"}:/(handler|execute|process|generate|create|build)/.test(t)?{kind:"service",confidence:.5,detail:"Business verb in the declaration name",method:"name_heuristic"}:{kind:"function",confidence:1,detail:"Declared in source",method:"ast"}}function E(e,n,t,i,r,o,s){return{source:{file:e,startLine:n,endLine:s,symbol:o},method:t,detail:i,confidence:r}}function $(e,n,t,i,r={}){return{id:k("edge",`${e}:${t}:${n}:${r.control??"sequential"}:${r.label??""}`),source:e,target:n,kind:t,label:r.label,control:r.control,metadata:r.metadata,evidence:i}}function k(e,n){return`${e}_${oi("sha1").update(n).digest("hex").slice(0,12)}`}function T(e,n){return Ee.relative(e,n).split(Ee.sep).join("/")}function P(e){return/\.pyi?$/i.test(e)?"python":/\.[cm]?jsx?$/.test(e)?"javascript":"typescript"}function de(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim()}function K(e){return e.split(/(?<=[.!?])\s/)[0]?.trim().slice(0,240)??e.slice(0,240)}function le(e){return[...new Set([...e.matchAll(/\{\{?\s*([a-zA-Z0-9_.]+)\s*\}?\}/g)].map(n=>n[1]))]}function re(e){let n=new Set;return e.filter(t=>n.has(t.id)?!1:(n.add(t.id),!0))}async function $e(e,n,t){let i=[];async function r(o){let s;try{s=await si(o,{withFileTypes:!0})}catch{return}s.sort((a,d)=>a.name.localeCompare(d.name));for(let a of s){let d=Ee.join(o,a.name);a.isDirectory()?!ai.has(a.name)&&!a.name.startsWith(".")&&await r(d):a.isFile()&&n.has(Ee.extname(a.name))&&!t.test(a.name)&&i.push(d)}}return await r(e),i}var mi=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),hi=/(\.(test|spec)\.[cm]?[jt]sx?|\.d\.[cm]?ts)$/i,wi=3,yi=new Set(["get","post","put","patch","delete","use","all","options","head"]),Gt=[{pattern:/^(express\.Router|Router|express)$/,name:"express"},{pattern:/^Hono$/,name:"hono"},{pattern:/^Elysia$/,name:"elysia"},{pattern:/^(fastify|Fastify)$/,name:"fastify"},{pattern:/^Koa$/,name:"koa"}],Ci=new Set(["aggregate","create","createMany","delete","deleteMany","deleteOne","execute","find","findFirst","findMany","findOne","findUnique","insert","insertMany","insertOne","query","save","select","update","updateMany","updateOne","upsert"]),bi=new Set(["db","prisma","supabase","drizzle","knex","mongoose","sequelize"]),Ni=/^(database|sql|pool|conn|connection|cursor|session|repo|repository|collection|table|store|dao|entityManager|queryRunner|index|cache|db)$|[a-z0-9][_-]?(Index|Store|Cache|Db|Repo)$/,xi=new Set(["every","filter","flatmap","foreach","map","reduce","reduceright","some"]);async function Ht(e,n={}){let t=F.resolve(e),i=[],r=await $e(t,mi,hi),o=n.maxFiles??2e3,s=r.slice(0,o);r.length>o&&i.push({level:"warning",code:"FILE_LIMIT_REACHED",message:`Found ${r.length} source files; only the first ${o} were analyzed.`});let a=await vi(t),d=new pi({...a?{tsConfigFilePath:a}:{},skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!0,checkJs:!1,jsx:4,target:fi.ES2022}});d.addSourceFilesAtPaths(s),await d.resolveSourceFileDependencies();let c=[],g=[],u=new Set(s.map(x=>F.resolve(x))),m=d.getSourceFiles().filter(x=>u.has(F.resolve(x.getFilePath()))),h=new Map,l=new Map;for(let x of m){let S=T(t,x.getFilePath()),A=k("file",S);h.set(x.getFilePath(),A);let L=ur(S)?"entrypoint":"file";c.push({id:A,kind:L,name:S,qualifiedName:S,language:P(S),evidence:[E(S,1,"path_heuristic",L==="entrypoint"?"Framework entrypoint convention":"Source file discovered",L==="entrypoint"?.86:1)]}),Ei(x,t,A,c,g,l)}for(let x of m){let S=h.get(x.getFilePath());S&&$i(x,t,S,c,g,l)}let f=Ki(m);for(let x of m){let S=h.get(x.getFilePath());S&&Vi(x,t,S,c,g,l,f)}let w=Gi(m,l);for(let x of m)Oi(x,t,l,c,g,w),Li(x,t,l,c,g);let y=er(m,l),N=new Set;for(let x of m)Ii(x,t,h,g),Di(x,t,l,c,g,y,i,N),Ri(x,t,l,c,g),Wi(x,t,l,c,g);let C=await hr(t,m.map(x=>T(t,x.getFilePath()))),b=[...new Set(m.map(x=>P(x.getFilePath())))];return m.length===0&&i.push({level:"warning",code:"NO_SOURCE_FILES",message:"No supported TypeScript or JavaScript source files were found."}),{schemaVersion:ne,generatedAt:new Date().toISOString(),project:{name:await wr(t),root:t,languages:b,frameworks:C,filesScanned:m.length},nodes:re(c),edges:re(g).filter(x=>x.source!==x.target),diagnostics:i}}async function vi(e){for(let n of["tsconfig.json","jsconfig.json"]){let t=F.join(e,n);try{return await gi(t),t}catch{}}}function Ei(e,n,t,i,r,o){let s=T(n,e.getFilePath()),a=[...e.getFunctions(),...e.getClasses().flatMap(d=>d.getMethods()),...e.getVariableDeclarations().filter(d=>{let c=d.getInitializer();return!!(c&&(p.isArrowFunction(c)||p.isFunctionExpression(c)))})];for(let d of a){let c=sr(d);if(!c)continue;let g=d.getStartLineNumber(),{kind:u,confidence:m,detail:h,method:l}=X(Se(s,c,d)),f=k(u,`${s}:${c}:${g}`),w={id:f,kind:u,name:c,qualifiedName:`${s}#${c}`,language:P(s),evidence:[E(s,g,l,h,m,c,d.getEndLineNumber())],metadata:{...Vt(d),...u==="route"?{method:c.toUpperCase(),path:lr(s),framework:"nextjs"}:{}}};i.push(w),r.push($(t,f,"contains",w.evidence)),o.set(R(d),{node:w,declaration:d})}for(let d of e.getClasses()){let c=d.getName();if(!c)continue;let g=d.getStartLineNumber(),u=k("class",`${s}:${c}:${g}`),m=[E(s,g,"ast","Class declaration",1,c,d.getEndLineNumber())];i.push({id:u,kind:"class",name:c,qualifiedName:`${s}#${c}`,language:P(s),evidence:m}),r.push($(t,u,"contains",m))}}function ze(e){if(p.isArrowFunction(e)||p.isFunctionExpression(e)||p.isFunctionDeclaration(e)||p.isMethodDeclaration(e))return e;let n=p.isExportAssignment(e)?e.getExpression():e.getInitializer();if(n)return p.isArrowFunction(n)||p.isFunctionExpression(n)?n:void 0}function Vt(e){let n=ze(e);if(!n)return{};let t=n.getParameters().map(r=>({name:r.getName(),type:r.getTypeNode()?.getText()??r.getType().getText(r),optional:r.isOptional()})),i=n.getReturnTypeNode()?.getText()??n.getReturnType().getText(n);return{parameters:t,returnType:i,async:n.hasModifier(z.AsyncKeyword),returnStatements:n.getDescendantsOfKind(z.ReturnStatement).length,throwStatements:n.getDescendantsOfKind(z.ThrowStatement).length,branches:n.getDescendantsOfKind(z.IfStatement).length+n.getDescendantsOfKind(z.SwitchStatement).length+n.getDescendantsOfKind(z.ConditionalExpression).length,loops:n.getDescendantsOfKind(z.ForStatement).length+n.getDescendantsOfKind(z.ForOfStatement).length+n.getDescendantsOfKind(z.ForInStatement).length+n.getDescendantsOfKind(z.WhileStatement).length+n.getDescendantsOfKind(z.DoStatement).length,catches:n.getDescendantsOfKind(z.CatchClause).length}}function $i(e,n,t,i,r,o){let s=T(n,e.getFilePath());for(let a of e.getDescendantsOfKind(z.VariableDeclaration)){if(o.has(R(a)))continue;let d=a.getInitializer();if(!d)continue;let c=a.getName(),g=ki(c,d);if(a.getFirstAncestorByKind(z.Block)!==void 0&&!g)continue;if(g){let S=k("prompt",`${s}:${c}:${a.getStartLineNumber()}`),A=[E(s,a.getStartLineNumber(),"name_heuristic","Prompt or instructions constant",.88,c,a.getEndLineNumber())],L={id:S,kind:"prompt",name:c,qualifiedName:`${s}#${c}`,description:K(g),language:P(s),metadata:{excerpt:g.slice(0,4e3),variables:le(g)},evidence:A};i.push(L),r.push($(t,S,"contains",A)),o.set(R(a),{node:L,declaration:a});continue}let m=Si(c,d,s);if(!m)continue;let h=a.getStartLineNumber(),l=k(m.kind,`${s}:${c}:${h}`),f=[E(s,h,m.method,m.detail,m.confidence,c,a.getEndLineNumber())],w=Kt(d),y=w?W(w,"role"):void 0,N=w?W(w,"description")??W(w,"goal")??y:void 0,C=w?W(w,"instructions")??W(w,"systemPrompt")??W(w,"prompt"):void 0,b=w?W(w,"model"):void 0,x={id:l,kind:m.kind,name:w?W(w,"name")??c:c,qualifiedName:`${s}#${c}`,description:N??(C?K(C):void 0),language:P(s),metadata:{factory:m.factory,role:y,instructions:C?.slice(0,2e3),model:b,toolNames:w?jt(w,"tools"):[],taskNames:w?jt(w,"tasks"):[]},evidence:f};if(i.push(x),r.push($(t,l,"contains",f)),o.set(R(a),{node:x,declaration:a}),b){let S=k("model",b),A=[E(s,h,"framework_convention",`Configured model ${b}`,.94,c)];i.push({id:S,kind:"model",name:b,qualifiedName:`model:${b}`,language:P(s),metadata:{model:b},evidence:A}),r.push($(l,S,"requests",A,{label:"model"}))}if(C&&C.length>=24){let S=k("prompt",`${s}:${c}:inline-instructions`),A=[E(s,h,"framework_convention",`Inline instructions configured for ${c}`,.94,c)];i.push({id:S,kind:"prompt",name:`${c} instructions`,qualifiedName:`${s}#${c}:instructions`,description:K(C),language:P(s),metadata:{excerpt:C.slice(0,4e3),variables:le(C)},evidence:A}),r.push($(l,S,"data_flow",A,{label:"instructions"}))}}}function Si(e,n,t){let i=zi(n),r=`${i} ${e}`.toLowerCase(),o=/stategraph|messagegraph|create(react)?agent|defineagent|new agent|agent\(|crew\(|crewai|task\(|tool\(|createtool|definetool|chatopenai|chatanthropic/.test(r),s=(a,d,c=o?.96:.82)=>({kind:a,factory:i,confidence:c,detail:d,method:o?"framework_convention":"name_heuristic"});if(/chatopenai|chatanthropic|azurechatopenai|generative(model|ai)|createmodel|language.?model/.test(r))return s("model",`Recognized model construction through ${i}`);if(/stategraph|messagegraph|workflow|orchestrator|pipeline|\bcrew\b/.test(r))return s("workflow",`Recognized workflow construction through ${i||e}`);if(/createtool|definetool|dynamicstructuredtool|\btool\b/.test(r))return s("tool",`Recognized tool construction through ${i||e}`);if(/human.?approval|human.?review|approval.?gate|confirm.?step|interruptbefore/.test(r))return s("human_gate",`Recognized human approval gate through ${i||e}`,.86);if(/create(react)?agent|defineagent|\bagent\b/.test(r))return s("agent",`Recognized Agent construction through ${i||e}`);if(/(^|\/)(agents?|crews?)\//i.test(t))return s("agent","Declared under an Agent directory",.72)}function zi(e){return p.isCallExpression(e)||p.isNewExpression(e)?e.getExpression().getText():e.getKindName()}function Kt(e){if(p.isObjectLiteralExpression(e))return e;if(p.isCallExpression(e)||p.isNewExpression(e))return e.getArguments().find(p.isObjectLiteralExpression)}function W(e,n){let t=e.getProperty(n);if(!t||!p.isPropertyAssignment(t))return;let i=t.getInitializer();if(i&&(p.isStringLiteral(i)||p.isNoSubstitutionTemplateLiteral(i)))return i.getLiteralText()}function jt(e,n){let t=e.getProperty(n);if(!t||!p.isPropertyAssignment(t))return[];let i=t.getInitializer();if(!i)return[];let r=p.isIdentifier(i)?[i]:i.getDescendantsOfKind(z.Identifier);return[...new Set(r.map(o=>o.getText()))]}function ki(e,n){if(/(prompt|instructions?|system(message|text)?|persona)/i.test(e)){if(p.isStringLiteral(n)||p.isNoSubstitutionTemplateLiteral(n))return n.getLiteralText();if(p.isTemplateExpression(n))return n.getText().slice(1,-1)}}function Ri(e,n,t,i,r){let o=T(n,e.getFilePath());for(let s of e.getVariableDeclarations()){let a=t.get(R(s)),d=s.getInitializer();if(!a||!d||!["agent","workflow","tool","human_gate"].includes(a.node.kind))continue;if(p.isArrayLiteralExpression(d)){for(let g of d.getElements()){if(!p.isIdentifier(g)&&!p.isPropertyAccessExpression(g))continue;let u=ge(g,t);if(!u||u.node.id===a.node.id||!ie.has(u.node.kind))continue;let m=[E(o,g.getStartLineNumber(),"ast",`${a.node.name} lists ${u.node.name} as a step`,.8,s.getName())];r.push($(a.node.id,u.node.id,"calls",m,{label:"step",control:"sequential"}))}continue}let c=Kt(d);if(c)for(let g of["tools","agents","tasks","handoffs","instructions","prompt","systemPrompt","model"]){let u=c.getProperty(g);if(!u||!p.isPropertyAssignment(u))continue;let m=u.getInitializer();if(!m)continue;let h=p.isIdentifier(m)?[m]:m.getDescendantsOfKind(z.Identifier);for(let l of h){let f=ge(l,t);if(!f||f.node.id===a.node.id)continue;let w=f.node.kind==="model"?"requests":f.node.kind==="prompt"?"data_flow":"calls",y=[E(o,u.getStartLineNumber(),"framework_convention",`${a.node.name} configures ${g} with ${f.node.name}`,.96,s.getName())];r.push($(a.node.id,f.node.id,w,y,{label:g,control:g==="handoffs"?"conditional":"sequential"}))}}}}function Li(e,n,t,i,r){let o=T(n,e.getFilePath()),s=new Map,a=e.getDescendantsOfKind(z.CallExpression);for(let d of a){let c=d.getExpression();if(!p.isPropertyAccessExpression(c)||c.getName()!=="addNode")continue;let[g,u]=d.getArguments();if(!g||!p.isStringLiteral(g))continue;let m=g.getLiteralValue(),h=u&&p.isIdentifier(u)?I(u.getSymbol(),t):void 0,l=[E(o,d.getStartLineNumber(),"framework_convention",`Registers workflow node ${m}`,.98,m)],f=h?.node??_i(m,o,d.getStartLineNumber(),l);h||i.push(f),!h&&u&&(p.isArrowFunction(u)||p.isFunctionExpression(u))&&t.set(R(u),{node:f,declaration:u}),f.metadata={...f.metadata,frameworkNodeName:m},s.set(m,f);let w=I(c.getExpression().getSymbol(),t);w&&w.node.id!==f.id&&r.push($(w.node.id,f.id,"calls",l,{label:"node",control:"sequential"}))}for(let d of a){let c=d.getExpression();if(!p.isPropertyAccessExpression(c))continue;let g=c.getName();if(!["addEdge","addConditionalEdges"].includes(g))continue;let u=I(c.getExpression().getSymbol(),t),[m,h,l]=d.getArguments(),f=Mt(m);if(!f)continue;let w=Ti(f)?u?.node:s.get(f);if(!w)continue;let y=Mt(h),N=g==="addConditionalEdges"?Ai(l):y?[y]:[];for(let C of N){if(Pi(C)){w.metadata={...w.metadata,terminal:!0,terminalReason:"workflow_end"};continue}let b=s.get(C);if(!b||w.id===b.id)continue;let x=g==="addConditionalEdges"?"conditional":"sequential",S=[E(o,d.getStartLineNumber(),"framework_convention",`${g} connects ${f} to ${C}`,.98,f)];r.push($(w.id,b.id,"calls",S,{label:g==="addConditionalEdges"?"branch":void 0,control:x}))}}}function _i(e,n,t,i){let r=/(agent|research|writer|review|planner)/i.test(e)?"agent":"service";return{id:k(r,`${n}:framework-node:${e}:${t}`),kind:r,name:e,qualifiedName:`${n}#workflow:${e}`,language:P(n),metadata:{frameworkNodeName:e},evidence:i}}function Ai(e){return!e||!p.isObjectLiteralExpression(e)?[]:e.getProperties().flatMap(n=>{if(!p.isPropertyAssignment(n))return[];let t=n.getInitializer();return t&&p.isStringLiteral(t)?[t.getLiteralValue()]:[]})}function Mt(e){if(e)return p.isStringLiteral(e)?e.getLiteralValue():p.isIdentifier(e)?e.getText():void 0}function Ti(e){return["__start__","START","start"].includes(e)}function Pi(e){return["__end__","END","end"].includes(e)}function Ii(e,n,t,i){let r=t.get(e.getFilePath());if(!r)return;let o=T(n,e.getFilePath());for(let s of e.getImportDeclarations()){let a=s.getModuleSpecifierSourceFile(),d=a?t.get(a.getFilePath()):void 0;if(!d)continue;let c=[E(o,s.getStartLineNumber(),"ast",`Imports ${s.getModuleSpecifierValue()}`,1)];i.push($(r,d,"imports",c))}}function Di(e,n,t,i,r,o,s,a){let d=T(n,e.getFilePath());for(let c of e.getDescendantsOfKind(z.CallExpression)){let g=Bt(c,t);if(!g||g.node.kind!=="function"&&p.isVariableDeclaration(g.declaration)&&ji(c,g.declaration))continue;let u=c.getExpression().getText(),m,h=Wt(c,t)??nr(c,t);if(!h){let b=tr(c,t,o);if(b?.target)h=b.target,m=b.detail;else if(b?.unresolved){let x=`${d}:${c.getStartLineNumber()}:${b.unresolved.expression}`;a.has(x)||(a.add(x),s.push({level:"info",code:"CALL_UNRESOLVED_DYNAMIC",message:`The target of \`${b.unresolved.expression}\` is decided at runtime (${b.unresolved.reason}); no edge was drawn.`,source:{file:d,startLine:c.getStartLineNumber()},metadata:{reason:b.unresolved.reason,expression:b.unresolved.expression,method:"ast",confidence:1,caller:g.node.name}}))}}let l=dr(c,u,i),f=h?.node.kind==="human_gate"?"human_approval":ir(c,u),w=rr(c,f),y=[E(d,c.getStartLineNumber(),"ast",`${f==="sequential"?"Calls":`${f} call to`} ${u}${m?` \u2014 ${m.toLowerCase()}`:""}`,m?.92:h||l?.96:.8)];h&&r.push($(g.node.id,h.node.id,"calls",y,{control:f,metadata:w})),h&&Mi(c,h,t,d,r),Ui(c,g,h,t,d,f,r),l&&r.push($(g.node.id,l.id,"requests",y,{control:f,metadata:w}));let N=fr(c,u)??pr(c);if(N){let b=k("external_api",N.key),x=[E(d,c.getStartLineNumber(),"name_heuristic",`Outbound request through ${u}`,N.confidence)];i.push({id:b,kind:"external_api",name:N.label,qualifiedName:N.key,language:P(d),metadata:N.metadata,evidence:x}),r.push($(g.node.id,b,"requests",x,{control:f,metadata:w}))}let C=mr(u);if(C){let b=k("database",C.key),x=[E(d,c.getStartLineNumber(),"name_heuristic",`Recognized database operation ${u}`,C.confidence)];i.push({id:b,kind:"database",name:C.label,qualifiedName:C.key,language:P(d),metadata:{operation:C.operation},evidence:x}),r.push($(g.node.id,b,C.edgeKind,x,{control:f,metadata:w}))}}}function ji(e,n){let t=e.getParent();for(;t;){if(t===n)return!0;if(p.isArrowFunction(t)||p.isFunctionExpression(t)||p.isMethodDeclaration(t)||p.isFunctionDeclaration(t))return!1;t=t.getParent()}return!1}function Mi(e,n,t,i,r){for(let o of e.getArguments()){let s=p.isIdentifier(o)?[o]:o.getDescendantsOfKind(z.Identifier);for(let a of s)for(let d of a.getSymbol()?.getDeclarations()??[]){if(!p.isVariableDeclaration(d))continue;let c=d.getInitializer(),g=c&&p.isAwaitExpression(c)?c.getExpression():c;if(!g||!p.isCallExpression(g))continue;let u=Wt(g,t);if(!u||u.node.id===n.node.id)continue;let m=[E(i,e.getStartLineNumber(),"ast",`${a.getText()} carries the result of ${u.node.name} into ${n.node.name}`,.97)];r.push($(u.node.id,n.node.id,"data_flow",m))}}}function Oi(e,n,t,i,r,o){let s=T(n,e.getFilePath());for(let a of e.getDescendantsOfKind(z.CallExpression)){let d=st(a,t);if(!d)continue;let{method:c,owner:g,ownerKey:u,framework:m,confidence:h,evidenceMethod:l,detail:f}=d,w=a.getArguments()[0];if(!w||!p.isStringLiteral(w))continue;let y=a.getArguments().at(-1);if(c==="use"&&y&&p.isIdentifier(y))continue;let N=u?o.get(u):void 0,C=N?Hi(N,w.getLiteralValue()):w.getLiteralValue(),b=k("route",`${c}:${C}:${s}`),x=[E(s,a.getStartLineNumber(),l,N?`${f}, mounted under ${N}`:f,h)],S={id:b,kind:"route",name:`${c.toUpperCase()} ${C}`,qualifiedName:`${c}:${C}`,language:P(s),metadata:{method:c.toUpperCase(),path:C,framework:m,owner:g,mountedUnder:N},evidence:x};if(i.push(S),!!y){if(p.isArrowFunction(y)||p.isFunctionExpression(y)){t.set(R(y),{node:S,declaration:y});continue}if(p.isIdentifier(y)||p.isPropertyAccessExpression(y)){let A=I(y.getSymbol(),t);A&&r.push($(b,A.node.id,"handles",x))}}}}function st(e,n){let t=e.getExpression();if(!p.isPropertyAccessExpression(t))return;let i=t.getName().toLowerCase();if(!yi.has(i))return;let r=e.getArguments()[0];if(!r||!p.isStringLiteral(r)||!r.getLiteralValue().startsWith("/"))return;let o=qt(t.getExpression(),n);return o?{...o,method:i}:void 0}function qt(e,n){if(p.isCallExpression(e)){let o=e.getExpression();return p.isPropertyAccessExpression(o)?qt(o.getExpression(),n):void 0}if(!p.isIdentifier(e))return;let t=e.getText();if(!/^(app|router|server|api)$/i.test(t)&&!/(router|app|server|routes)$/i.test(t))return Fi(e,t);let i=at(e);if(i){let o=i.getInitializer(),s=o&&(p.isCallExpression(o)||p.isNewExpression(o))?o.getExpression().getText():void 0,a=s?Gt.find(d=>d.pattern.test(s)):void 0;if(a&&s)return{owner:t,ownerKey:R(i),framework:a.name,confidence:.96,evidenceMethod:"framework_convention",detail:`Route registered on a ${a.name} instance built by ${s}`}}let r=i?R(i):void 0;return/^(app|router|server|api)$/i.test(t)?{owner:t,ownerKey:r,framework:"hono_or_express",confidence:.94,evidenceMethod:"framework_convention",detail:`Recognized ${t}.* route registration`}:{owner:t,ownerKey:r,framework:"hono_or_express",confidence:.78,evidenceMethod:"name_heuristic",detail:`Route registered on ${t}, named as a router`}}function ge(e,n){let t=e.getParent();if(p.isShorthandPropertyAssignment(t)){let i=I(t.getValueSymbol(),n);if(i)return i}return I(e.getSymbol(),n)}function Fi(e,n){let t=at(e),i=t?.getInitializer();if(!i||!p.isCallExpression(i)&&!p.isNewExpression(i))return;let r=i.getExpression().getText(),o=Gt.find(s=>s.pattern.test(r));if(!(!o||!t))return{owner:n,ownerKey:R(t),framework:o.name,confidence:.96,evidenceMethod:"framework_convention",detail:`Route registered on a ${o.name} instance built by ${r}`}}function at(e){let n=e.getSymbol();for(let t of[n,n?.getAliasedSymbol()].filter(i=>i!==void 0))for(let i of t.getDeclarations())if(p.isVariableDeclaration(i))return i}function Gi(e,n){let t=new Map;for(let i of e)for(let r of i.getDescendantsOfKind(z.CallExpression)){let o=st(r,n);if(!o||o.method!=="use")continue;let[s,a]=r.getArguments();if(!s||!p.isStringLiteral(s)||!a||!p.isIdentifier(a))continue;let d=at(a);d&&t.set(R(d),s.getLiteralValue())}return t}function Hi(e,n){let t=`${e.replace(/\/+$/,"")}/${n.replace(/^\/+/,"")}`.replace(/\/{2,}/g,"/");return t.length>1?t.replace(/\/$/,""):"/"}function Vi(e,n,t,i,r,o,s){let a=T(n,e.getFilePath()),d=(c,g,u,m=1)=>{if(o.has(R(c)))return;let h=c.getStartLineNumber(),l=X(Se(a,g,c)),f=k(l.kind,`${a}:${g}:${h}`),w=[E(a,h,l.method,`${u}; ${l.detail.toLowerCase()}`,Math.min(l.confidence,m),g,c.getEndLineNumber())],y={id:f,kind:l.kind,name:g,qualifiedName:`${a}#${g}`,language:P(a),metadata:Vt(c),evidence:w};i.push(y),r.push($(t,f,"contains",w)),o.set(R(c),{node:y,declaration:c})};for(let c of e.getVariableDeclarations()){let g=c.getInitializer();if(!g)continue;let u=c.getName();if(p.isObjectLiteralExpression(g)){let l=X(Se(a,u,c));if(l.kind!=="function"&&l.confidence>=.65){d(c,u,"Object literal named as a construct");continue}for(let f of g.getProperties())p.isMethodDeclaration(f)?d(f,`${u}.${f.getName()}`,"Callable member of an object literal"):p.isPropertyAssignment(f)&&ze(f)&&d(f,`${u}.${f.getName()}`,"Callable member of an object literal");continue}if(o.has(R(c)))continue;let m=X(Se(a,u,c)).kind!=="function";if(!m&&!s.has(u))continue;let h=p.isAwaitExpression(g)?g.getExpression():g;p.isCallExpression(h)&&(!m&&c.getType().getCallSignatures().length===0||d(c,u,`Instance produced by ${h.getExpression().getText()}`,.9))}for(let c of e.getExportAssignments())c.isExportEquals()||!ze(c)||d(c,qi(a),"Default-exported callable")}function Ki(e){let n=new Set;for(let t of e)for(let i of t.getDescendantsOfKind(z.CallExpression)){let r=i.getExpression();p.isIdentifier(r)?n.add(r.getText()):p.isPropertyAccessExpression(r)&&n.add(r.getName());for(let o of Ut(i))n.add(p.isIdentifier(o)?o.getText():o.getName())}return n}function qi(e){let n=F.basename(e).replace(/\.[cm]?[jt]sx?$/i,"");if(!/^(index|route)$/i.test(n))return n;let t=F.basename(F.dirname(e));return t&&t!=="."?`${t} ${n}`:n}function Ui(e,n,t,i,r,o,s){if(st(e,i))return;let a=e.getExpression().getText();for(let d of Ut(e)){let c=ge(d,i);if(!c||c.node.id===n.node.id||c.node.id===t?.node.id)continue;let g=d.getStartLineNumber();if(ie.has(c.node.kind)){let u=[E(r,g,"ast",`${c.node.name} is handed to ${a} as a callback`,.9)],m=c.node.kind==="human_gate"?"human_approval":Zi(a,o);s.push($(n.node.id,c.node.id,"calls",u,{control:m}));continue}if(c.node.kind==="prompt"||c.node.kind==="model"){let u=[E(r,g,"ast",`${c.node.name} is passed into ${a}`,.94)];s.push($(c.node.id,n.node.id,"data_flow",u,{label:c.node.kind}))}}}var Bi=/^(generateText|streamText|generateObject|streamObject|embed|embedMany|create|complete|invoke)$/;function Wi(e,n,t,i,r){let o=T(n,e.getFilePath());for(let s of e.getDescendantsOfKind(z.CallExpression)){let a=s.getExpression().getText();if(!Bi.test(a.split(".").at(-1)??""))continue;let d=s.getArguments().find(p.isObjectLiteralExpression);if(!d||!d.getProperty("model"))continue;let c=Bt(s,t);if(!c)continue;let g=s.getStartLineNumber(),u=Xi(d.getProperty("model"))??Yi(s,a);if(u){let l=k("model",u.name),f=[E(o,g,"framework_convention",`${a} requests model ${u.name}`,.96,c.node.name)];i.push({id:l,kind:"model",name:u.name,qualifiedName:`model:${u.name}`,language:P(o),metadata:{model:u.name,provider:u.provider},evidence:f}),r.push($(c.node.id,l,"requests",f,{label:"model"}))}for(let l of["system","prompt","instructions","messages"]){let f=d.getProperty(l);if(!f||!p.isPropertyAssignment(f))continue;let w=f.getInitializer();if(w)for(let y of p.isIdentifier(w)?[w]:w.getDescendantsOfKind(z.Identifier)){let N=ge(y,t);if(N?.node.kind!=="prompt")continue;let C=[E(o,f.getStartLineNumber(),"framework_convention",`${c.node.name} sends ${N.node.name} as ${l}`,.96,c.node.name)];r.push($(N.node.id,c.node.id,"data_flow",C,{label:l}))}}let m=d.getProperty("tools");if(!m||!p.isPropertyAssignment(m))continue;let h=m.getInitializer();if(h)for(let l of h.getDescendantsOfKind(z.Identifier)){let f=ge(l,t);if(!f||f.node.id===c.node.id||!ie.has(f.node.kind))continue;let w=[E(o,m.getStartLineNumber(),"framework_convention",`${c.node.name} offers ${f.node.name} as a tool to the model`,.94,c.node.name)];r.push($(c.node.id,f.node.id,"calls",w,{label:"tool",control:"conditional"}))}}}var Ji=/(^|\.)(anthropic|openai|client)\.(messages|chat\.completions|completions|responses)\./;function Yi(e,n){if(!Ji.test(n))return;let t=/anthropic/i.test(n)?"anthropic":/openai/i.test(n)?"openai":void 0;return{name:`${t?de(t):"LLM"} model (runtime-selected)`,provider:t}}function Xi(e){if(!e||!p.isPropertyAssignment(e))return;let n=e.getInitializer();if(n){if(p.isStringLiteral(n)||p.isNoSubstitutionTemplateLiteral(n))return{name:n.getLiteralText()};if(p.isCallExpression(n)){let t=n.getExpression().getText(),i=n.getArguments()[0];return i&&p.isStringLiteral(i)?{name:i.getLiteralValue(),provider:t}:{name:n.getText(),provider:t}}}}function Ut(e){let n=[],t=i=>{(p.isIdentifier(i)||p.isPropertyAccessExpression(i))&&n.push(i)};for(let i of e.getArguments())p.isArrayLiteralExpression(i)?i.getElements().forEach(t):t(i);return n}function Zi(e,n){if(/^promise\s*\.\s*(all|allsettled|race|any)$/i.test(e))return"parallel";let t=e.split(".").at(-1)?.toLowerCase()??"";return xi.has(t)?"loop":t==="catch"?"fallback":n}function Bt(e,n){let t=e;for(;t;){if(p.isFunctionDeclaration(t)||p.isMethodDeclaration(t)||p.isVariableDeclaration(t)||p.isPropertyAssignment(t)||p.isExportAssignment(t)||p.isArrowFunction(t)||p.isFunctionExpression(t)){let i=n.get(R(t));if(i)return i}t=t.getParent()}}function Wt(e,n){let t=e.getExpression(),i=I(t.getSymbol(),n);if(i)return i;if(p.isPropertyAccessExpression(t))return I(t.getExpression().getSymbol(),n)}var Qi=new Set(["set","register","add"]);function er(e,n){let t={entries:new Map,registries:new Set};for(let i of e)for(let r of i.getDescendantsOfKind(z.CallExpression)){let o=r.getExpression();if(!p.isPropertyAccessExpression(o)||!Qi.has(o.getName()))continue;let[s,a]=r.getArguments(),d=ke(s);if(d===void 0||!a||!p.isIdentifier(a)&&!p.isPropertyAccessExpression(a))continue;let c=pe(o.getExpression());if(!c)continue;let g=I(a.getSymbol(),n);t.registries.add(R(c)),g&&t.entries.set(`${R(c)}|${d}`,g)}return t}function ke(e){if(e&&(p.isStringLiteral(e)||p.isNoSubstitutionTemplateLiteral(e)))return e.getLiteralValue()}function pe(e){let n=e.getSymbol();if(n){for(let t of[n,n.getAliasedSymbol()].filter(i=>i!==void 0))for(let i of t.getDeclarations())if(p.isVariableDeclaration(i))return i}}function tr(e,n,t){let i=e.getExpression(),r=ue(e,t);if(r)return r;let o=ue(i,t);if(o)return o;if(p.isPropertyAccessExpression(i)){let s=i.getExpression();if(p.isIdentifier(s)){let d=pe(s)?.getInitializer();if(d){let c=ue(d,t);if(c)return c}}let a=ue(s,t);if(a)return a;if(p.isElementAccessExpression(s))return ot(s,n);if(p.isNonNullExpression(s)){let d=s.getExpression(),c=ue(d,t);if(c)return c;if(p.isElementAccessExpression(d))return ot(d,n)}}if(p.isElementAccessExpression(i))return ot(i,n)}function ue(e,n){let t=e;if(p.isNonNullExpression(t)&&(t=t.getExpression()),p.isAwaitExpression(t)&&(t=t.getExpression()),!p.isCallExpression(t))return;let i=t.getExpression();if(!p.isPropertyAccessExpression(i)||i.getName()!=="get")return;let r=pe(i.getExpression());if(!r||!n.registries.has(R(r)))return;let o=t.getArguments()[0],s=ke(o);if(s===void 0)return{unresolved:{reason:"the registry key is computed at runtime",expression:t.getText().slice(0,160)}};let a=n.entries.get(`${R(r)}|${s}`);if(a)return{target:a,detail:`Resolved through registry key "${s}"`}}function ot(e,n){let i=pe(e.getExpression())?.getInitializer();if(!i||!p.isObjectLiteralExpression(i))return;let r=i.getProperties().some(c=>p.isPropertyAssignment(c)||p.isShorthandPropertyAssignment(c)?I(c.getSymbol(),n)!==void 0:!1),o=e.getArgumentExpression(),s=ke(o)??(o&&p.isAsExpression(o)?ke(o.getExpression()):void 0);if(s===void 0)return r?{unresolved:{reason:"the member is selected by a runtime value",expression:e.getText().slice(0,160)}}:void 0;let a=i.getProperty(s);if(!a)return;let d=I(a.getSymbol(),n);return d?{target:d,detail:`Resolved object member "${s}"`}:void 0}function nr(e,n){let t=e.getExpression().getText().toLowerCase();if(!/(^|\.)(run|runstreamed|invoke|execute)$/.test(t))return;let i=e.getArguments()[0];if(!i||!p.isIdentifier(i))return;let r=I(i.getSymbol(),n);return r&&["agent","workflow"].includes(r.node.kind)?r:void 0}function ir(e,n){if(/retry|backoff|withretry/i.test(n))return"retry";for(let t of e.getAncestors()){if(p.isFunctionDeclaration(t)||p.isMethodDeclaration(t)||p.isArrowFunction(t)||p.isFunctionExpression(t))break;if(p.isCallExpression(t)&&/^(Promise\.(all|allSettled|race|any)|parallel|all)$/.test(t.getExpression().getText()))return"parallel";if(p.isCatchClause(t))return"fallback";if(p.isForStatement(t)||p.isForOfStatement(t)||p.isForInStatement(t)||p.isWhileStatement(t)||p.isDoStatement(t))return/retry|attempt|backoff/i.test(t.getText().slice(0,240))?"retry":"loop";if(p.isIfStatement(t)||p.isSwitchStatement(t)||p.isConditionalExpression(t))return"conditional"}return"sequential"}function rr(e,n){if(n!=="retry")return;let t=[e.getText().slice(0,600)];for(let o of e.getAncestors())if(p.isFunctionDeclaration(o)||p.isMethodDeclaration(o)||p.isArrowFunction(o)||p.isFunctionExpression(o)||(t.push(o.getText().slice(0,600)),p.isForStatement(o)||p.isWhileStatement(o)||p.isDoStatement(o)))break;let i=t.join(" ");return{retryBounded:/max[A-Z_\s-]?(attempts?|retries)|retryLimit|attempt\s*[<>=!]+\s*\d+|retries\s*:\s*\d+|maxRetries\s*:\s*\d+/i.test(i)}}function I(e,n,t=0){if(!e||t>wi)return;let i=[e,e.getAliasedSymbol()].filter(r=>r!==void 0);for(let r of i.flatMap(o=>o.getDeclarations())){let o=n.get(R(r));if(o)return o;if(p.isBindingElement(r)){let s=or(r,n,t);if(s)return s}if(p.isPropertyAssignment(r)||p.isVariableDeclaration(r)){let s=r.getInitializer();if(s&&(p.isIdentifier(s)||p.isPropertyAccessExpression(s))){let a=I(s.getSymbol(),n,t+1);if(a)return a}}}}function or(e,n,t){let i=e.getParent();if(!p.isObjectBindingPattern(i))return;let r=i.getParent();if(!p.isVariableDeclaration(r))return;let o=r.getInitializer();if(!o)return;let s=e.getPropertyNameNode()?.getText()??e.getName();return I(o.getType().getProperty(s),n,t+1)}function sr(e){return e.getName()}function R(e){return`${e.getSourceFile().getFilePath()}:${e.getStart()}`}function Se(e,n,t){let i=p.isMethodDeclaration(t)?t:void 0,r=p.isFunctionDeclaration(t)||p.isMethodDeclaration(t)?t:p.isVariableDeclaration(t)||p.isPropertyAssignment(t)||p.isExportAssignment(t)?ze(t):void 0;return{relativeFile:e,name:n,returnType:r?.getReturnTypeNode()?.getText(),internal:cr(t),enclosingClass:i?ar(i):void 0,routeConvention:/\/app\/api\/.+\/route\.[jt]sx?$/.test(`/${e.toLowerCase()}`)&&Dt.has(n.toUpperCase())}}function ar(e){let n=e.getParent();return p.isClassDeclaration(n)||p.isClassExpression(n)?n.getName()??"":""}function cr(e){return p.isMethodDeclaration(e)?e.getName().startsWith("#")||e.getName().startsWith("_")?!0:e.hasModifier(z.PrivateKeyword)||e.hasModifier(z.ProtectedKeyword):!1}function dr(e,n,t){if(n!=="fetch")return;let[i,r]=e.getArguments();if(!i||!p.isStringLiteral(i))return;let o=i.getLiteralValue();if(!o.startsWith("/"))return;let s="GET";if(r&&p.isObjectLiteralExpression(r)){let a=r.getProperty("method");if(a&&p.isPropertyAssignment(a)){let d=a.getInitializer();d&&p.isStringLiteral(d)&&(s=d.getLiteralValue().toUpperCase())}}return t.find(a=>a.kind==="route"&&a.metadata?.path===o&&a.metadata?.method===s)}function lr(e){let n=e.match(/(?:^|\/)app\/(api\/.+)\/route\.[jt]sx?$/);return n?`/${n[1]}`:e}function ur(e){return/(^|\/)(page|layout|route|index|main|server|app)\.[jt]sx?$/.test(e)||/(^|\/)pages\/api\//.test(e)}var gr=/^(fetch|nodeFetch|axios|got|ky|superagent|undici)(\.(get|post|put|patch|delete|head|request))?$/;function pr(e){let n=e.getExpression();if(!p.isPropertyAccessExpression(n)||n.getName()!=="send")return;let i=pe(n.getExpression())?.getInitializer();if(!i||!p.isNewExpression(i))return;let o=i.getExpression().getSymbol(),s=[o,o?.getAliasedSymbol()].filter(a=>a!==void 0).flatMap(a=>a.getDeclarations());for(let a of s){let g=a.getFirstAncestorByKind(z.ImportDeclaration)?.getModuleSpecifierValue()?.match(/^@aws-sdk\/client-([a-z0-9-]+)$/);if(g){let u=g[1];return{key:`aws:${u}`,label:`AWS ${de(u).replace(/\b\w/g,m=>m.toUpperCase())}`,metadata:{provider:"aws",service:u},confidence:.9}}}}function fr(e,n){let t=e.getArguments()[0];if(gr.test(n)){let r=n.split(".")[0],o=t===void 0?void 0:p.isStringLiteral(t)||p.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():p.isTemplateExpression(t)?t.getHead().getLiteralText():void 0;if(o&&/^https?:\/\//.test(o)){let s=yr(o);return{key:`http:${s}`,label:s,metadata:{provider:r,url:o},confidence:.92}}if(!o)return{key:`http:${r}`,label:`${de(r)} request`,metadata:{provider:r,url:void 0},confidence:.68}}let i=[{pattern:/(^|\.)openai\.|\.responses\.create$|\.chat\.completions\.create$/,key:"sdk:openai",label:"OpenAI API"},{pattern:/(^|\.)anthropic\.|\.messages\.create$/,key:"sdk:anthropic",label:"Anthropic API"},{pattern:/(^|\.)stripe\./,key:"sdk:stripe",label:"Stripe API"}].find(r=>r.pattern.test(n.toLowerCase()));return i?{key:i.key,label:i.label,metadata:{provider:i.key.slice(4)},confidence:.9}:void 0}function mr(e){let n=e.split(".");if(n.length<2)return;let t=n.at(-1)??"",i=n[0]??"";if(!Ci.has(t))return;let r=bi.has(i.toLowerCase());if(!r&&!Ni.test(i))return;let o=n.length>2?n.at(-2)??"data":"data",s=o==="data"?i:o,a=/^(find|select|query|aggregate)/.test(t);return{key:`${i.toLowerCase()}:${o}`,label:`${de(s)} data`,operation:t,edgeKind:a?"reads":"writes",confidence:r?.88:.7}}async function hr(e,n){let t=new Set;try{let i=JSON.parse(await Ft(F.join(e,"package.json"),"utf8")),r={...Ot(i.dependencies),...Ot(i.devDependencies)},o={next:"Next.js",react:"React",express:"Express",hono:"Hono","@nestjs/core":"NestJS","@langchain/langgraph":"LangGraph",langchain:"LangChain","@openai/agents":"OpenAI Agents SDK","@mastra/core":"Mastra",ai:"Vercel AI SDK",openai:"OpenAI SDK","@anthropic-ai/sdk":"Anthropic SDK","@temporalio/workflow":"Temporal",inngest:"Inngest"};for(let[s,a]of Object.entries(o))s in r&&t.add(a)}catch{}return n.some(i=>/(^|\/)app\/api\/.+\/route\.[jt]s$/.test(i))&&t.add("Next.js"),[...t]}async function wr(e){try{let n=JSON.parse(await Ft(F.join(e,"package.json"),"utf8"));if(n.name)return n.name}catch{}return F.basename(e)}function yr(e){try{return new URL(e).hostname}catch{return e}}function Ot(e){return e&&typeof e=="object"?e:{}}import{spawn as Cr}from"child_process";import{readFile as Jt}from"fs/promises";import oe from"path";import{fileURLToPath as br}from"url";var Nr=new Set([".py"]),xr=/(^test_.*\.py$|_test\.py$|^conftest\.py$|\.pyi$)/i,vr=/^(app|router|api|server|[a-z_]*(?:router|app|api))\.(get|post|put|patch|delete|head|options)$/i,Er=/^(FastAPI|APIRouter|Flask|Blueprint|Quart|Starlette|Sanic)$/,$r=/(^|\.)((responses|chat\.completions|completions|messages|embeddings)\.create|generate_content|invoke|ainvoke)$/;async function Yt(e,n={}){let t=oe.resolve(e),i=[],r=await $e(t,Nr,xr),o=n.maxFiles??2e3,s=r.slice(0,o);r.length>o&&i.push({level:"warning",code:"FILE_LIMIT_REACHED",message:`Found ${r.length} Python files; only the first ${o} were analyzed.`});let a=[],d=[],c;s.length&&(c=await kr(s,n.pythonPath,i));let g=new Map;for(let u of c?.files??[]){if(u.error){i.push({level:"warning",code:"PYTHON_FILE_UNREADABLE",message:`${T(t,u.path)}: ${u.error}`});continue}Sr(u,t,a,d,g)}for(let u of c?.files??[])u.error||zr(u,t,a,d,g);return{schemaVersion:ne,generatedAt:new Date().toISOString(),project:{name:oe.basename(t),root:t,languages:s.length?["python"]:[],frameworks:await Gr(t,c),filesScanned:c?.files.filter(u=>!u.error).length??0},nodes:re(a),edges:re(d).filter(u=>u.source!==u.target),diagnostics:i}}function Sr(e,n,t,i,r){let o=T(n,e.path),s=k("file",o),a=Fr(o),d=[E(o,1,"path_heuristic",a?"Framework entrypoint convention":"Source file discovered",a?.86:1)];t.push({id:s,kind:a?"entrypoint":"file",name:o,qualifiedName:o,language:"python",evidence:d});for(let c of e.classes){let g=k("class",`${o}:${c.name}:${c.line}`),u=[E(o,c.line,"ast","Class declaration",1,c.name,c.endLine)],m={id:g,kind:"class",name:c.name,qualifiedName:`${o}#${c.name}`,description:c.docstring?K(c.docstring):void 0,language:"python",metadata:{bases:c.bases},evidence:u};t.push(m),i.push($(s,g,"contains",u)),r.set(c.name,m)}for(let c of e.functions){let g=_r(c.decorators,e),u=X({relativeFile:o,name:c.name,internal:!!c.enclosingClass&&c.name.startsWith("_"),enclosingClass:c.enclosingClass??void 0,routeConvention:!!g,returnType:c.returns??void 0}),m=k(u.kind,`${o}:${c.name}:${c.line}`),h=[E(o,c.line,u.method,g?`${u.detail} via ${g.decorator}`:u.detail,u.confidence,c.name,c.endLine)],l={id:m,kind:u.kind,name:g?`${g.method} ${g.path}`:c.name,qualifiedName:`${o}#${c.name}`,description:c.docstring?K(c.docstring):void 0,language:"python",metadata:{...g?{method:g.method,path:g.path,framework:g.framework}:{},async:c.isAsync,parameters:c.parameters.filter(f=>f!=="self"&&f!=="cls"),returnType:c.returns??void 0,branches:c.branches,loops:c.loops,catches:c.catches},evidence:h};t.push(l),i.push($(s,m,"contains",h)),r.set(c.name,l)}for(let c of e.assignments){if(c.scope)continue;let g=Ir(c.name,c.text);if(g){let N=k("prompt",`${o}:${c.name}:${c.line}`),C=[E(o,c.line,"name_heuristic","Prompt or instructions constant",.88,c.name,c.endLine)],b={id:N,kind:"prompt",name:c.name,qualifiedName:`${o}#${c.name}`,description:K(g),language:"python",metadata:{excerpt:g.slice(0,4e3),variables:le(g)},evidence:C};t.push(b),i.push($(s,N,"contains",C)),r.set(c.name,b);continue}let u=Tr(c.name,c.factory);if(!u)continue;let m=k(u.kind,`${o}:${c.name}:${c.line}`),h=[E(o,c.line,u.method,u.detail,u.confidence,c.name,c.endLine)],l=c.options??{},f=q(l,"instructions")??q(l,"system_prompt")??q(l,"prompt"),w=q(l,"model"),y={id:m,kind:u.kind,name:q(l,"name")??c.name,qualifiedName:`${o}#${c.name}`,description:q(l,"description")??q(l,"goal")??(f?K(f):void 0),language:"python",metadata:{factory:c.factory??void 0,role:q(l,"role"),instructions:f?.slice(0,2e3),model:w,toolNames:fe(l,"tools"),taskNames:fe(l,"tasks")},evidence:h};t.push(y),i.push($(s,m,"contains",h)),r.set(c.name,y)}}function zr(e,n,t,i,r){let o=T(n,e.path);for(let s of e.calls){let a=s.enclosingFunction?r.get(s.enclosingFunction):void 0;if(!a)continue;let d=Pr(s),c=[E(o,s.line,"ast",`Calls ${s.callee}`,.96,s.enclosingFunction??void 0)],g=ct(r,s.callee);g&&g.id!==a.id&&(ie.has(g.kind)?i.push($(a.id,g.id,"calls",c,{control:d})):(g.kind==="prompt"||g.kind==="model")&&i.push($(g.id,a.id,"data_flow",[E(o,s.line,"ast",`${g.name} is used by ${a.name}`,.92)],{label:g.kind})));for(let h of s.nameArguments){let l=ct(r,h);if(!(!l||l.id===a.id||l.id===g?.id)){if(l.kind==="prompt"||l.kind==="model"){i.push($(l.id,a.id,"data_flow",[E(o,s.line,"ast",`${l.name} is passed into ${s.callee}`,.94)],{label:l.kind}));continue}i.push($(a.id,l.id,"calls",[E(o,s.line,"ast",`${l.name} is handed to ${s.callee} as a callback`,.9)],{control:d}))}}if($r.test(s.callee)){let h=q(s.options,"model");if(h){let l=k("model",h),f=[E(o,s.line,"framework_convention",`${s.callee} requests model ${h}`,.96,s.enclosingFunction??void 0)];t.push({id:l,kind:"model",name:h,qualifiedName:`model:${h}`,language:"python",metadata:{model:h},evidence:f}),i.push($(a.id,l,"requests",f,{label:"model"}))}for(let l of fe(s.options,"input").concat(fe(s.options,"messages"),fe(s.options,"prompt"))){let f=ct(r,l);f?.kind==="prompt"&&i.push($(f.id,a.id,"data_flow",[E(o,s.line,"framework_convention",`${a.name} sends ${f.name} to the model`,.96)],{label:"prompt"}))}}let u=jr(s.callee);if(u){let h=k("database",u.key),l=[E(o,s.line,"name_heuristic",`Recognized database operation ${s.callee}`,.88)];t.push({id:h,kind:"database",name:u.label,qualifiedName:u.key,language:"python",metadata:{operation:u.operation},evidence:l}),i.push($(a.id,h,u.edgeKind,l,{control:d}))}let m=Mr(s);if(m){let h=k("external_api",m.key),l=[E(o,s.line,"name_heuristic",`Outbound request through ${s.callee}`,.9)];t.push({id:h,kind:"external_api",name:m.label,qualifiedName:m.key,language:"python",metadata:m.metadata,evidence:l}),i.push($(a.id,h,"requests",l,{control:d}))}}}async function kr(e,n,t){let i;try{i=await Lr()}catch(s){t.push({level:"warning",code:"PYTHON_EXTRACTOR_MISSING",message:s instanceof Error?s.message:String(s)});return}let r=n?[n]:["python3","python"],o="";for(let s of r)try{return await Rr(s,i,e)}catch(a){o=a instanceof Error?a.message:String(a)}t.push({level:"warning",code:"PYTHON_UNAVAILABLE",message:`Python source was found but no interpreter could analyze it (${o}). Install Python 3 or pass a path to analyze these files.`})}function Rr(e,n,t){return new Promise((i,r)=>{let o=Cr(e,["-c",n],{stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stdout.on("data",d=>{s+=d}),o.stderr.setEncoding("utf8"),o.stderr.on("data",d=>{a+=d}),o.on("error",d=>r(new Error(`${e}: ${d.message}`))),o.on("close",d=>{if(d!==0){r(new Error(`${e} exited with ${d}: ${a.trim().slice(0,200)}`));return}try{i(JSON.parse(s))}catch{r(new Error(`${e} returned output that was not valid JSON`))}}),o.stdin.end(JSON.stringify(t))})}async function Lr(){let e=oe.dirname(br(import.meta.url)),n=[oe.join(e,"..","scripts","extract.py"),oe.join(e,"python","extract.py")];for(let t of n)try{return await Jt(t,"utf8")}catch{}throw new Error("the bundled Python extractor is missing from this installation")}function _r(e,n){for(let t of e){let i=vr.exec(t);if(!i)continue;let r=i[1],o=i[2].toUpperCase(),a=n.calls.find(d=>d.callee===t&&d.stringArguments.length)?.stringArguments[0]??"/";return{method:o,path:a,framework:Ar(r,n),decorator:t}}}function Ar(e,n){let t=n.assignments.find(i=>i.name===e&&i.factory&&Er.test(i.factory));return t?.factory?t.factory==="Flask"||t.factory==="Blueprint"?"flask":t.factory.toLowerCase():"python_http"}function Tr(e,n){let t=`${n??""} ${e}`.toLowerCase(),i=/stategraph|messagegraph|create_react_agent|createagent|\bagent\(|\bcrew\(|crewai|\btask\(|\btool\(|chatopenai|chatanthropic|assistant/.test(t),r=(o,s,a=i?.96:.82)=>({kind:o,confidence:a,detail:s,method:i?"framework_convention":"name_heuristic"});if(/chatopenai|chatanthropic|azurechatopenai|generativemodel|language_?model/.test(t))return r("model",`Recognized model construction through ${n}`);if(/stategraph|messagegraph|workflow|orchestrator|pipeline|\bcrew\b/.test(t))return r("workflow",`Recognized workflow construction through ${n??e}`);if(/structuredtool|\btool\b/.test(t))return r("tool",`Recognized tool construction through ${n??e}`);if(/human_?approval|human_?review|approval_?gate|interrupt_before/.test(t))return r("human_gate",`Recognized human approval gate through ${n??e}`,.86);if(/create_react_agent|createagent|\bagent\b/.test(t))return r("agent",`Recognized Agent construction through ${n??e}`)}function Pr(e){return/retry|backoff/i.test(e.callee)?"retry":"sequential"}function Ir(e,n){if(!(!n||n.length<24))return/prompt|instruction|system|template|persona/i.test(e)?n:void 0}function q(e,n){let t=e?.[n];return t?.kind==="string"?t.value:void 0}function fe(e,n){let t=e?.[n];return t?.kind==="names"?t.value:[]}function Dr(e){return e.split(".").at(-1)??e}function ct(e,n){let t=n.split(".");return e.get(n)??e.get(t.at(-1)??n)??e.get(t[0]??n)}function jr(e){let n=Dr(e).toLowerCase(),t=["all","filter","first","get","query","scalar","select","fetchall","fetchone","find","find_one"],i=["add","bulk_save_objects","commit","create","delete","insert","save","update","upsert","insert_one","update_one"];if(!t.includes(n)&&!i.includes(n))return;let r=e.split(".").slice(0,-1).join(".")||"database";if(/session|db|database|repo|repository|table|collection|cursor|conn/i.test(r))return{key:`db:${r}`,label:`${r} data`,operation:n,edgeKind:i.includes(n)?"writes":"reads"}}function Mr(e){if(!/^(requests|httpx|aiohttp|urllib\.request)\.[a-z]+$/i.test(e.callee))return;let n=e.stringArguments.find(i=>/^https?:\/\//.test(i)),t=n?Or(n):e.callee.split(".")[0];return{key:`http:${t}`,label:t,metadata:{host:t,url:n,client:e.callee.split(".")[0]}}}function Or(e){try{return new URL(e).hostname}catch{return e}}function Fr(e){return/(^|\/)(main|app|__main__|server|asgi|wsgi|manage)\.py$/i.test(e)}async function Gr(e,n){let t=new Set,i={fastapi:"FastAPI",flask:"Flask",django:"Django",starlette:"Starlette",langgraph:"LangGraph",langchain:"LangChain",crewai:"CrewAI",llama_index:"LlamaIndex",autogen:"AutoGen",openai:"OpenAI SDK",anthropic:"Anthropic SDK",pydantic_ai:"Pydantic AI"};for(let r of n?.files??[])for(let o of r.imports??[]){let s=o.module.split(".")[0]?.toLowerCase()??"",a=i[s];a&&t.add(a)}for(let r of["requirements.txt","pyproject.toml"])try{let o=(await Jt(oe.join(e,r),"utf8")).toLowerCase();for(let[s,a]of Object.entries(i))(o.includes(s.replace("_","-"))||o.includes(s))&&t.add(a)}catch{}return[...t]}import{createHash as ho}from"crypto";var Q=["zh-CN","en"],en=.5,Hr=8,Xt={file:"agent-runtime-map.config.json",startLine:1},Vr=new Set(["api","url","id","http","https","html","json","csv","pdf","sql","ui","ux","ai","llm","rag","sdk","jwt","cdn","dns","ip","db","io","rpc","crud","otp","sms","pii"]),dt={by:{zh:(e,n)=>`\u6309${n}${e}`,en:(e,n)=>`${e} by ${n}`},from:{zh:(e,n)=>`\u4ECE${n}${e}`,en:(e,n)=>`${e} from ${n}`},to:{zh:(e,n)=>`${e}\u4E3A${n}`,en:(e,n)=>`${e} to ${n}`},for:{zh:(e,n)=>`\u9762\u5411${n}\u7684${e}`,en:(e,n)=>`${e} for ${n}`},of:{zh:(e,n)=>`${n}\u7684${e}`,en:(e,n)=>`${e} of ${n}`},with:{zh:(e,n)=>`\u643A\u5E26${n}${e}`,en:(e,n)=>`${e} with ${n}`},in:{zh:(e,n)=>`\u5728${n}\u4E2D${e}`,en:(e,n)=>`${e} in ${n}`},on:{zh:(e,n)=>`\u5728${n}\u4E0A${e}`,en:(e,n)=>`${e} on ${n}`},and:{zh:(e,n)=>`${e}\u5E76${n}`,en:(e,n)=>`${e} and ${n}`},or:{zh:(e,n)=>`${e}\u6216${n}`,en:(e,n)=>`${e} or ${n}`}},Kr=new Set(["a","an","the"]),lt=new Set(["refund","score"]);function Re(e,n,t){let i=typeof e.metadata?.rawName=="string"?e.metadata.rawName:e.label,r=e.metadata?.rawKind,o=[],s={"zh-CN":"",en:""},a={"zh-CN":"pending",en:"pending"},d={"zh-CN":0,en:0},c,g=n.overrides?.nodes?.[i]??n.overrides?.nodes?.[e.id],u=Br(e,n.capabilities);for(let l of Q){let f=g?.label?.[l];if(f){s[l]=f,a[l]="config",d[l]=1,o.some(y=>y.file===Xt.file)||o.push(Xt);continue}if(u&&ut(u.label,l)){s[l]=u.label,a[l]="documented",d[l]=u.confidence;for(let y of u.sources.slice(0,2))o.some(N=>N.file===y.file&&N.startLine===y.startLine)||o.push(y);continue}if(r==="route"||Ur(e.label)){s[l]=e.label,a[l]="route",d[l]=1;continue}if(r==="external_api"||r==="model"||e.type==="external_system"||e.type==="model"){s[l]=i,a[l]="vendor",d[l]=1;continue}let w=tn(i,l,n.overrides?.terms,Wr(e),e.type==="data"||e.type==="result"?"thing":"action");s[l]=w.text,a[l]=w.source,d[l]=w.confidence,w.source==="identifier"&&e.sources[0]&&!o.length&&o.push(e.sources[0]),w.tokens.length&&!c&&(c=w.tokens.slice(0,Hr))}let m=Q.some(l=>a[l]==="pending");if(m)for(let l of Q)a[l]==="pending"&&(s[l]=l==="zh-CN"?`\u5F85\u786E\u8BA4 \xB7 ${Zt["zh-CN"][e.type]}`:`Unconfirmed \xB7 ${Zt.en[e.type]}`);let h=Jr(e,s,a,t,g,u,o);return{label:{"zh-CN":s["zh-CN"],en:s.en},description:h,technicalName:i,labelSource:{"zh-CN":a["zh-CN"],en:a.en},confidence:{"zh-CN":me(d["zh-CN"]),en:me(d.en)},pending:m,evidence:o,glossary:c}}function tn(e,n,t,i,r="action"){let o=xe(e),s=o.filter(L=>!rt.has(L.toLowerCase())&&!Kr.has(L.toLowerCase())),a=s.length?s:o;if(i&&a.at(-1)?.toLowerCase()===i){let L=a.slice(0,-1).filter(O=>!(O.toLowerCase()in dt));(L.length>=2||L.length===1&<.has(Y(L[0].toLowerCase())))&&(a=a.slice(0,-1))}if(!a.length)return{text:e,source:"pending",confidence:0,tokens:[]};let d=a.findIndex((L,ce)=>ce>0&&ce<a.length-1&&L.toLowerCase()in dt),c=d>0?dt[a[d].toLowerCase()]:void 0,g=!c&&a.length>1&&r==="action"&<.has(Y(a[0].toLowerCase())),u=c?a.slice(0,d):g?a.slice(0,1):a,m=c?a.slice(d+1):g?a.slice(1):[],h=[],l=0,f=(L,ce)=>{let O=[];for(let[H,te]of L.entries()){let D=te.toLowerCase(),et=t?.[D];if(et?.[n]){O.push({token:D,en:et.en??Z(te),"zh-CN":et["zh-CN"],via:"config"}),l+=1;continue}if(Vr.has(D)){O.push({token:D,en:D.toUpperCase(),"zh-CN":D.toUpperCase(),via:"acronym"}),l+=1;continue}if(/^\d+$/.test(D)){O.push({token:D,en:D,"zh-CN":D,via:"literal"}),l+=1;continue}let ei=ce&&H===0?"head":"tail",tt=It(Y(D),ei);if(tt){O.push({token:D,en:tt.enUS??Z(te),"zh-CN":tt.zhCN,via:"vocabulary"}),l+=1;continue}O.push({token:D,en:Z(te),via:"unresolved"})}if(h.push(...O),!(O.some(H=>H.via==="unresolved")&&n==="zh-CN"))return{zh:O.map(H=>H["zh-CN"]??H.en).join(""),en:O.map((H,te)=>te===0?Z(H.en):qr(H.en)).join(" ")}},w=f(u,r==="action"),y=u.length===1&<.has(Y(u[0].toLowerCase())),N=m.length?f(m,!1):void 0,C=u.length+m.length,b=C?l/C:0;if(n==="zh-CN")return!w||m.length&&!N?{text:"",source:"pending",confidence:me(b),tokens:h}:{text:c&&N?c.zh(w.zh,N.zh):y&&N?`\u4E3A${N.zh}${w.zh}`:w.zh,source:"identifier",confidence:1,tokens:h};if(b<en)return{text:"",source:"pending",confidence:me(b),tokens:h};let x=w?.en??u.map(Z).join(" "),S=N?.en??m.map(Z).join(" ");return{text:c&&m.length?c.en(x,S.toLowerCase()):m.length?`${x} ${S.toLowerCase()}`:x,source:"identifier",confidence:me(b),tokens:h}}function qr(e){return e===e.toUpperCase()&&e.length<=5?e:e.toLowerCase()}function Z(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ur(e){return/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s/i.test(e)||e.startsWith("/")}function ut(e,n){let t=/[㐀-鿿]/.test(e);return n==="zh-CN"?t:!t}function Br(e,n){let t=e.metadata?.documentedCapabilityId;if(typeof t!="string")return;let i=n.find(d=>d.id===t);if(!i||e.product?.matchedOn!=="documented_name")return;let r=typeof e.metadata?.rawName=="string"?e.metadata.rawName:e.label,o=xe(r).map(d=>Y(d.toLowerCase())).filter(d=>!rt.has(d)),s=new Set(xe(i.label).map(d=>Y(d.toLowerCase())));return o.length>0&&o.every(d=>s.has(d))&&s.size===new Set(o).size?i:void 0}function Wr(e){let n=e.metadata?.rawKind;if(n==="agent"||e.type==="ai_process")return"agent";if(n==="workflow")return"workflow";if(n==="tool")return"tool";if(n==="service")return"service"}var Zt={"zh-CN":{user_action:"\u7528\u6237\u64CD\u4F5C",entrypoint:"\u5165\u53E3",process:"\u5904\u7406\u6B65\u9AA4",workflow:"\u5DE5\u4F5C\u6D41",ai_process:"AI \u5904\u7406",tool:"\u5DE5\u5177",model:"\u6A21\u578B",human_gate:"\u4EBA\u5DE5\u786E\u8BA4",decision:"\u5224\u65AD",data:"\u6570\u636E",external_system:"\u5916\u90E8\u670D\u52A1",result:"\u7ED3\u679C"},en:{user_action:"user action",entrypoint:"entrypoint",process:"process",workflow:"workflow",ai_process:"AI process",tool:"tool",model:"model",human_gate:"human gate",decision:"decision",data:"data",external_system:"external system",result:"result"}};function Jr(e,n,t,i,r,o,s){let a={"zh-CN":"",en:""},d=e.metadata?.generatedDescription===!0;for(let c of Q){let g=r?.description?.[c];if(g){a[c]=g;continue}if(o?.description&&ut(o.description,c)){a[c]=o.description;continue}if(!d&&e.description&&ut(e.description,c)){a[c]=e.description;continue}let u=Xr(c,e,i);if(u){a[c]=u;continue}a[c]=t[c]==="pending"?c==="zh-CN"?`\u8FD9\u4E00\u6B65\u7684\u4E1A\u52A1\u542B\u4E49\u8FD8\u65E0\u6CD5\u4ECE\u8BC1\u636E\u4E2D\u786E\u5B9A\uFF0C\u6280\u672F\u540D\u79F0\u4E3A ${e.metadata?.rawName??e.label}\u3002`:`This step's business meaning could not be read from evidence; its technical name is ${e.metadata?.rawName??e.label}.`:Yr(c,e.type,n[c])}return o&&!s.length&&s.push(...o.sources.slice(0,1)),{"zh-CN":a["zh-CN"],en:a.en}}function Yr(e,n,t){return e==="zh-CN"?{user_action:`\u7528\u6237\u53D1\u8D77\u300C${t}\u300D\u3002`,entrypoint:`\u7CFB\u7EDF\u901A\u8FC7 ${t} \u63A5\u6536\u8BF7\u6C42\u3002`,process:`\u7CFB\u7EDF\u6267\u884C\u300C${t}\u300D\u3002`,workflow:`\u5DE5\u4F5C\u6D41\u7F16\u6392\u300C${t}\u300D\u3002`,ai_process:`AI \u73AF\u8282\u6267\u884C\u300C${t}\u300D\u3002`,tool:`\u667A\u80FD\u4F53\u8C03\u7528\u5DE5\u5177\u300C${t}\u300D\u3002`,model:`\u667A\u80FD\u4F53\u4F7F\u7528\u6A21\u578B ${t}\u3002`,human_gate:`\u7B49\u5F85\u4EBA\u5DE5\u786E\u8BA4\u300C${t}\u300D\u3002`,decision:`\u7CFB\u7EDF\u5224\u65AD\u300C${t}\u300D\u3002`,data:`\u7CFB\u7EDF\u8BFB\u5199\u300C${t}\u300D\u3002`,external_system:`\u7CFB\u7EDF\u8C03\u7528\u5916\u90E8\u670D\u52A1 ${t}\u3002`,result:`\u6D41\u7A0B\u4EA7\u51FA\u300C${t}\u300D\u3002`}[n]:{user_action:`A person starts ${t}.`,entrypoint:`The system receives a request through ${t}.`,process:`The system runs ${t}.`,workflow:`A workflow orchestrates ${t}.`,ai_process:`An AI step runs ${t}.`,tool:`An agent calls the ${t} tool.`,model:`An agent uses the ${t} model.`,human_gate:`A person must approve ${t}.`,decision:`The system decides ${t}.`,data:`The system reads or writes ${t}.`,external_system:`The system calls ${t}.`,result:`The chain produces ${t}.`}[n]}function Xr(e,n,t){let i=n.behavior;if(!i)return;let r=d=>{let c=t.get(d);return c?.semantic?.label[e]??c?.label??d},o=d=>e==="zh-CN"?`\u300C${r(d)}\u300D`:r(d),s=[],a=d=>d.slice(0,3).map(o).join(e==="zh-CN"?"\u3001":", ");if(i.calls?.length&&s.push(e==="zh-CN"?`\u8C03\u7528${a(i.calls)}`:`calls ${a(i.calls)}`),i.branches?.length&&s.push(e==="zh-CN"?`\u6309\u6761\u4EF6\u8D70\u5411${a(i.branches)}`:`branches to ${a(i.branches)}`),i.requests?.length&&s.push(e==="zh-CN"?`\u8BF7\u6C42${a(i.requests)}`:`requests ${a(i.requests)}`),i.data?.length&&s.push(e==="zh-CN"?`\u8BFB\u5199${a(i.data)}`:`reads or writes ${a(i.data)}`),i.feeds?.length&&s.push(e==="zh-CN"?`\u7ED3\u679C\u6D41\u5411${a(i.feeds)}`:`passes its result to ${a(i.feeds)}`),!!s.length)return e==="zh-CN"?`${s.join("\uFF0C")}\u3002`:`${Z(s[0])}${s.length>1?`, then ${s.slice(1).join(", ")}`:""}.`}var Qt={"zh-CN":{sequential:"\u987A\u5E8F\u6267\u884C",conditional:"\u6761\u4EF6\u5206\u652F",parallel:"\u5E76\u884C\u6267\u884C",loop:"\u5FAA\u73AF\u6267\u884C",retry:"\u5931\u8D25\u91CD\u8BD5",fallback:"\u964D\u7EA7\u5907\u9009",human_approval:"\u7B49\u5F85\u4EBA\u5DE5\u786E\u8BA4"},en:{sequential:"Sequential",conditional:"Conditional branch",parallel:"Parallel",loop:"Loop",retry:"Retry on failure",fallback:"Fallback",human_approval:"Awaiting approval"}};function gt(e,n){if(e.type==="data_flow"){let r=n.get(e.target)?.type==="data";return{"zh-CN":r?"\u8BFB\u5199\u6570\u636E":"\u6570\u636E\u6D41\u8F6C",en:r?"Reads or writes":"Data flow"}}let t=e.control??"sequential";return{"zh-CN":Qt["zh-CN"][t],en:Qt.en[t]}}function me(e){return Math.round(e*100)/100}var pt=["ai_process","workflow","human_gate","tool","decision","process"];function mt(e,n){let t=new Map(e.map(r=>[r.id,Zr(r,n)])),i=new Map;for(let r of e){let o=t.get(r.id);i.set(r.id,{"zh-CN":ft(o,"zh-CN")??r.label,en:ft(o,"en")??r.label})}for(let r of Q){let o=new Map;for(let a of e){let d=i.get(a.id)[r];o.set(d,[...o.get(d)??[],a])}for(let[,a]of o)if(!(a.length<2))for(let d of a){let c=t.get(d.id),g=sn(c.result,r)??(c.entry?.semantic?.labelSource[r]==="route"?J(c.entry,r):void 0)??Le(c,r),u=i.get(d.id);!g||g===u[r]||(u[r]=`${u[r]} \xB7 ${g}`)}let s=new Map;for(let a of e){let d=i.get(a.id)[r];s.set(d,[...s.get(d)??[],a])}for(let[,a]of s)if(!(a.length<2))for(let d of a){let c=J(t.get(d.id).entry,r)??d.label,g=i.get(d.id);g[r].includes(c)||(g[r]=`${g[r]} \xB7 ${c}`)}}for(let r of e){let o=t.get(r.id),s=i.get(r.id),a=d=>ft(o,d)!==void 0;r.semantic={label:{"zh-CN":s["zh-CN"],en:s.en},description:{"zh-CN":nn("zh-CN",o)??r.description,en:nn("en",o)??r.description},technicalName:r.label,labelSource:{"zh-CN":a("zh-CN")?"composed":"pending",en:a("en")?"composed":"pending"},confidence:{"zh-CN":rn(o,"zh-CN"),en:rn(o,"en")},pending:[o.entry,o.mains[0],o.result].some(d=>d?.semantic?.pending===!0),evidence:Qr(o)}}}function Zr(e,n){let t=e.nodeIds.flatMap(d=>{let c=n.get(d);return c?[c]:[]}),i=n.get(e.entryNodeIds[0]??"")??t[0],r=n.get(e.resultNodeIds[0]??"")??n.get(e.variants[0]?.resultNodeId??""),o=t.filter(d=>d.id!==i?.id&&d.id!==r?.id&&pt.includes(d.type)),s=d=>e.variants.filter(c=>c.nodeIds.includes(d.id)).length,a=[...o].sort((d,c)=>pt.indexOf(d.type)-pt.indexOf(c.type)||s(c)-s(d)||d.id.localeCompare(c.id));return{entry:i,mains:a,result:r}}function ft(e,n){let t=J(e.entry,n);return e.entry?.semantic?.labelSource[n]==="route"?Le(e,n)??sn(e.result,n)??t:t??Le(e,n)}function Le(e,n){return J(on(e,n),n)}function on(e,n){return e.mains.find(t=>J(t,n)!==void 0)}function sn(e,n){if(!(!e||e.type==="data"||e.type==="external_system"))return J(e,n)}function J(e,n){if(!e)return;let t=e.semantic;if(!(!t||t.labelSource[n]==="pending"))return t.label[n]}function nn(e,n){let t=J(n.entry,e),i=Le(n,e),r=n.result&&n.result.id!==n.entry?.id?J(n.result,e):void 0;if(!t)return;if(e==="zh-CN"){let a=i?`\uFF0C\u7ECF\u8FC7\u300C${i}\u300D`:"",d=r?`\uFF0C\u6700\u7EC8\u4EA7\u51FA\u300C${r}\u300D`:"";return`\u4ECE\u300C${t}\u300D\u5F00\u59CB${a}${d}\u3002`}let o=i?`, runs ${i}`:"",s=r?`, and produces ${r}`:"";return`Starts at ${t}${o}${s}.`}function rn(e,n){let t=[e.entry,on(e,n),e.result].flatMap(i=>i?.semantic?[i.semantic.confidence[n]]:[]);return t.length?Math.round(t.reduce((i,r)=>i+r,0)/t.length*100)/100:0}function Qr(e){let n=[];for(let t of[e.entry,e.mains[0],e.result]){let i=t?.sources[0];i&&!n.some(r=>r.file===i.file&&r.startLine===i.startLine)&&n.push(i)}return n}import{createHash as eo}from"crypto";var dn=new Set(["data","external_system","model"]),_e=120,yt=12,wt=48;function Ct(e,n,t=[]){let i=new Map(e.map(u=>[u.id,u])),r=Ae(n),o=po(n),s=e.filter(u=>u.type==="user_action"),a=new Set(s.flatMap(u=>[...ln(u.id,r)])),d=e.filter(u=>u.type==="entrypoint"&&!a.has(u.id)),c=e.filter(u=>["ai_process","process"].includes(u.type)&&(o.get(u.id)?.length??0)===0&&(r.get(u.id)?.length??0)>0);return mo([...s,...d,...s.length||d.length?[]:c]).map(u=>to(u,n,i,r,t)).sort((u,m)=>cn(m.health)-cn(u.health)||u.label.localeCompare(m.label))}function to(e,n,t,i,r){let o=ln(e.id,i),s=[...o].slice(0,_e),a=new Set(s),d=n.filter(C=>a.has(C.source)&&a.has(C.target)),c=s.flatMap(C=>t.get(C)?[t.get(C)]:[]),g=c.filter(C=>!d.some(b=>b.source===C.id)),u=co(e.id,a,d,t),m=oo(e,c,d,n,t,o.size,u.truncated),h=so(e.id,c,d,u,t),l=uo(e.id,i,t),f=io(c,r),w=c.length?V(Math.min(...c.map(C=>C.confidence))):e.confidence,y=fo(m),N=f?.capability.label??l?.label??e.label;return{id:`feature_${j(`${e.id}:${N}`)}`,label:N,description:f?.capability.description??`Simulates the code-backed execution chain that starts at ${N}.`,entryNodeIds:[e.id],resultNodeIds:g.map(C=>C.id),nodeIds:s,edgeIds:d.map(C=>C.id),variants:h,diagnostics:m,health:y,confidence:w,product:no(f)}}function no(e){if(e)return{capabilityId:e.capability.id,label:e.capability.label,origin:e.capability.origin,sources:e.capability.sources,match:V(Math.min(.95,.35+Math.min(e.score,24)*.025)*e.capability.confidence),matchedOn:e.matchedOn,matchedTerms:e.matchedTerms}}function io(e,n){let t=ht(e.map(s=>`${s.label} ${s.metadata?.rawName??""}`).join(" ")),i=ht(e.filter(s=>s.type==="entrypoint"||s.type==="user_action").map(s=>`${s.label} ${s.metadata?.rawName??""}`).join(" ")),r=new Map;for(let s of e){let a=typeof s.metadata?.documentedCapabilityId=="string"?s.metadata.documentedCapabilityId:void 0;a&&r.set(a,(r.get(a)??0)+1)}let o;for(let s of n){let a=ht(`${s.label} ${s.keywords.join(" ")}`),d=[...a].filter(u=>i.has(u)).length,c=[...a].filter(u=>t.has(u)).length,g=d*8+c+(r.get(s.id)??0)*.5;g>0&&(!o||g>o.score||g===o.score&&s.confidence>o.capability.confidence)&&(o={capability:s,score:g,matchedOn:d>0?"entry_terms":"step_terms",matchedTerms:[...a].filter(u=>i.has(u)||t.has(u)).slice(0,4)})}if(!(o&&o.matchedOn==="step_terms"&&o.score<3))return o}function ht(e){let n=e.toLowerCase().match(/[a-z][a-z0-9-]{2,}|[\u3400-\u9fff]{2,8}/g)??[];return new Set(n.map(t=>ro(t).replace(/^(post|get|put|patch|delete)$/,"")).filter(t=>t.length>=3))}function ro(e){return/(ations?|tion)$/.test(e)?e.replace(/ations?$/,"ate").replace(/tion$/,"te"):e.replace(/(ing|ed|es|s)$/i,"")}function oo(e,n,t,i,r,o,s){let a=[],d=new Set(n.map(l=>l.id)),c=i.filter(l=>d.has(l.source)&&(!r.has(l.source)||!r.has(l.target)));for(let l of c)a.push({id:`diagnostic_${j(`broken:${l.id}`)}`,code:"CHAIN_BROKEN_REFERENCE",severity:"error",message:"The chain references a logic node that does not exist in the graph.",suggestion:"Check the unresolved call, import, or generated edge at this point.",edgeId:l.id,nodeId:l.source,sources:r.get(l.source)?.sources??[],confidence:1});t.length===0&&a.push({id:`diagnostic_${j(`downstream:${e.id}`)}`,code:"CHAIN_NO_DOWNSTREAM",severity:"error",message:"The feature entry has no resolvable downstream execution step.",suggestion:"Check whether the entry calls a workflow, agent, service, or tool that the analyzer can resolve.",nodeId:e.id,sources:e.sources,confidence:1});let g=go(n,t),u=n.filter(l=>!t.some(f=>f.source===l.id)).length;g&&a.push({id:`diagnostic_${j(`cycle:${g.id}`)}`,code:"CHAIN_CYCLE",severity:u===0?"error":"warning",message:u===0?"The feature chain contains a cycle with no resolvable exit.":"The feature chain contains a cycle; verify that its runtime exit condition is intentional.",suggestion:"Inspect the loop guard or add an explicit terminal path.",nodeId:g.id,sources:g.sources,confidence:u===0?.95:.75}),n.length>1&&u===0&&a.push({id:`diagnostic_${j(`result:${e.id}`)}`,code:"CHAIN_NO_RESULT",severity:"error",message:"The analyzer could not find a terminal result for this feature.",suggestion:"Add or expose a return, persistence, response, or handoff that completes the chain.",nodeId:e.id,sources:e.sources,confidence:.9});let m=n.filter(l=>l.confidence<.6);for(let l of m.slice(0,6))a.push({id:`diagnostic_${j(`confidence:${l.id}`)}`,code:"CHAIN_LOW_CONFIDENCE",severity:"warning",message:`The step \u201C${l.label}\u201D is inferred with ${Math.round(l.confidence*100)}% confidence.`,suggestion:"Confirm the call relationship or add a clearer workflow, agent, tool, or service name.",nodeId:l.id,sources:l.sources,confidence:l.confidence});for(let l of t.filter(f=>f.control==="retry"&&f.metadata?.retryBounded!==!0)){let f=r.get(l.source);a.push({id:`diagnostic_${j(`retry:${l.id}`)}`,code:"CHAIN_RETRY_WITHOUT_LIMIT",severity:"warning",message:"A retry path was detected without a statically resolvable attempt limit.",suggestion:"Set a maximum retry count, backoff policy, and explicit failure exit.",nodeId:l.source,edgeId:l.id,sources:f?.sources??[],confidence:.82})}let h=Ae(t);for(let l of n.filter(f=>f.type==="external_system")){let f=t.filter(y=>y.target===l.id).flatMap(y=>r.get(y.source)??[]),w=f.some(y=>Number(y.metadata?.catches??0)>0||(h.get(y.id)??[]).some(N=>N.control==="fallback"));f.length&&!w&&a.push({id:`diagnostic_${j(`fallback:${l.id}`)}`,code:"CHAIN_EXTERNAL_NO_FALLBACK",severity:"info",message:`The external call to ${l.label} has no statically resolvable fallback path.`,suggestion:"Add error handling, a bounded retry, or a degraded response for this dependency.",nodeId:l.id,sources:l.sources,confidence:.72})}for(let l of n.filter(f=>f.type==="ai_process")){let f=(h.get(l.id)??[]).filter(y=>{let N=r.get(y.target);return N&&!["data","external_system","model"].includes(N.type)}),w=typeof l.metadata?.returnType=="string"?l.metadata.returnType:"";!f.length&&/(^|<)(void|undefined)(>|$)/i.test(w)&&l.metadata?.terminal!==!0&&a.push({id:`diagnostic_${j(`agent-output:${l.id}`)}`,code:"CHAIN_AGENT_NO_OUTPUT",severity:"warning",message:`The Agent step \u201C${l.label}\u201D has no structured output or downstream handoff.`,suggestion:"Declare an output type or schema, persist a result, or connect the Agent to its next step.",nodeId:l.id,sources:l.sources,confidence:.86})}return(o>_e||s)&&a.push({id:`diagnostic_${j(`limit:${e.id}`)}`,code:"CHAIN_PATH_LIMIT",severity:"warning",message:s?`The feature has more than ${yt} branches or exceeds ${wt} steps; simulation uses a bounded path set.`:`The feature reaches ${o} nodes; simulation is limited to ${_e}.`,suggestion:"Increase graph compression or split the feature into explicit workflows.",nodeId:e.id,sources:e.sources,confidence:1}),a}function so(e,n,t,i,r){let o=n.map(d=>d.id),s=an(`variant_${j(`${e}:all`)}`,i.paths.length>1?"All paths":"Default path",i.paths.length>1?"Checks every inferred branch in the feature.":"Checks the inferred execution path.",e,o,t.map(d=>d.id),t,r);if(i.paths.length<=1)return[s];let a=i.paths.slice(0,yt).map((d,c)=>{let g=lo(d.nodeIds,t,r),u=new Set(g),m=t.filter(l=>u.has(l.source)&&u.has(l.target)).map(l=>l.id),h=r.get(d.nodeIds.at(-1)??"");return an(`variant_${j(`${e}:${d.edgeIds.join(":")}`)}`,`Path ${c+1}${h?` \xB7 ${h.label}`:""}`,`Checks the branch that reaches ${h?.label??"its terminal step"}.`,e,g,m,t,r)});return[s,...a]}function an(e,n,t,i,r,o,s,a){let d=new Set(r),c=s.filter(l=>o.includes(l.id)),g=ao(i,d,c),u=[...d].map(l=>a.get(l)).find(l=>l?.type==="result")??[...d].map(l=>a.get(l)).find(l=>l&&!c.some(f=>f.source===l.id)),m=[...d].flatMap(l=>a.get(l)?[a.get(l).confidence]:[]),h=m.length?V(Math.min(...m)):0;return{id:e,label:n,description:t,nodeIds:[...d],edgeIds:o,steps:g,resultNodeId:u?.id,confidence:h}}function ao(e,n,t){let i=new Map([[e,0]]),r=[e];for(;r.length;){let s=r.shift();if(!s)continue;let a=i.get(s)??0;for(let d of t.filter(c=>c.source===s)){if(!n.has(d.target))continue;let c=a+1;(!i.has(d.target)||c<i.get(d.target))&&(i.set(d.target,c),r.push(d.target))}}let o=Math.max(0,...i.values());return Array.from({length:o+1},(s,a)=>{let d=[...n].filter(c=>i.get(c)===a);return{order:a,nodeIds:d,incomingEdgeIds:t.filter(c=>d.includes(c.target)&&i.has(c.source)).map(c=>c.id)}}).filter(s=>s.nodeIds.length>0)}function co(e,n,t,i){let r=[],o=!1,s=t.filter(c=>{let g=i.get(c.target);return g&&!dn.has(g.type)}),a=Ae(s);function d(c,g,u,m){if(r.length>=yt){o=!0;return}let h=(a.get(c)??[]).filter(l=>n.has(l.target)&&!m.has(l.target));if(!h.length||g.length>=wt){r.push({nodeIds:g,edgeIds:u}),g.length>=wt&&(o=!0);return}for(let l of h)d(l.target,[...g,l.target],[...u,l.id],new Set([...m,l.target]))}return d(e,[e],[],new Set([e])),{paths:r.length?r:[{nodeIds:[e],edgeIds:[]}],truncated:o}}function lo(e,n,t){let i=new Set(e);for(let r of n){let o=t.get(r.target);i.has(r.source)&&o&&dn.has(o.type)&&i.add(o.id)}return[...i]}function uo(e,n,t){let i=[e],r=new Set;for(;i.length;){let o=i.shift();if(!o||r.has(o))continue;r.add(o);let s=t.get(o);if(s?.type==="entrypoint")return s;i.push(...(n.get(o)??[]).map(a=>a.target))}}function ln(e,n){let t=new Set,i=[e];for(;i.length&&t.size<_e+1;){let r=i.shift();!r||t.has(r)||(t.add(r),i.push(...(n.get(r)??[]).map(o=>o.target)))}return t}function go(e,n){let t=new Map(e.map(a=>[a.id,a])),i=Ae(n),r=new Set,o=new Set;function s(a){if(r.has(a))return t.get(a);if(!o.has(a)){r.add(a);for(let d of i.get(a)??[]){let c=s(d.target);if(c)return c}r.delete(a),o.add(a)}}for(let a of e){let d=s(a.id);if(d)return d}}function Ae(e){let n=new Map;for(let t of e)n.set(t.source,[...n.get(t.source)??[],t]);return n}function po(e){let n=new Map;for(let t of e)n.set(t.target,[...n.get(t.target)??[],t]);return n}function fo(e){return e.some(n=>n.severity==="error")?"error":e.some(n=>n.severity==="warning")?"warning":"healthy"}function cn(e){return e==="error"?2:e==="warning"?1:0}function mo(e){let n=new Set;return e.filter(t=>!n.has(t.id)&&!!n.add(t.id))}function j(e){return eo("sha1").update(e).digest("hex").slice(0,12)}var Nt=new Set(["calls","data_flow","handles","reads","writes","requests"]);function un(e,n={}){let t=Math.max(4,n.maxNodes??40),i=[...e.diagnostics],r=xo(e.edges),o=No(e),s=e.nodes.filter(f=>Co(f,r.get(f.id)??0,o)),a=vo(s,r),d=a.slice(0,t),c=new Set(d.map(f=>f.id));a.length>d.length&&i.push({level:"info",code:"LOGIC_GRAPH_COMPRESSED",message:`Compressed ${a.length} business-relevant code nodes to the ${d.length} highest-signal logic nodes.`});let g=d.map(f=>Eo(f,e.context?.capabilityHints??[])),u=new Map(g.map(f=>[f.rawNodeIds[0],f.id])),m=Fo(Ao(e,c,u),g);Go(g,m),ko(g,m);let h=Ct(g,m,e.context?.capabilityHints??[]);if(n.localize!==!1){let f={capabilities:e.context?.capabilityHints??[],overrides:n.localizationOverrides??e.context?.localization},w=new Map(g.map(y=>[y.id,y]));for(let y of g)y.semantic=Re(y,f,w);for(let y of g)y.semantic=Re(y,f,w);for(let y of m)y.semantic={label:gt(y,w)};mt(h,w)}let l=n.graphType??"runtime_logic";return l==="product_logic"&&i.push({level:"info",code:"PRODUCT_LOGIC_CONTEXTUAL_INFERENCE",message:"Product logic combines code structure with README, docs, PRD, prompt, and configuration evidence when available; uncertain matches retain confidence scores."}),{schemaVersion:ne,generatedAt:new Date().toISOString(),graphType:l,title:`${e.project.name} ${l==="runtime_logic"?"runtime logic":"product logic"}`,description:n.productDescription??e.context?.description??e.context?.documents.find(f=>f.kind==="readme")?.summary??(l==="runtime_logic"?"A static, evidence-backed view of how work flows through the codebase.":"A code-informed view of how user actions become product value."),project:e.project,understanding:Do(e,g,n.productDescription),nodes:g,edges:m,features:h,diagnostics:i}}var wo=/^(assert|audit|cap|clamp|clone|debug|dedupe|ensure|equals|error|format|from|get|has|hash|id|is|log|map|merge|noop|normali[sz]e|now|parse|pick|print|require|serialize|set|sleep|sort|to|trace|trim|truncate|unique|validate|warn|wrap)([A-Z_]|$)/;function yo(e){let n=e&&`${e[0].toLowerCase()}${e.slice(1)}`;return wo.test(n)}function Co(e,n,t){return e.kind==="route"||e.kind==="database"||e.kind==="external_api"?!0:["service","agent","workflow","tool","human_gate"].includes(e.kind)?n===0&&Te(e)<=.5?!1:n>0||!yo(e.name):e.kind==="function"?t.has(e.id)?!0:/^(handle|on)(submit|click|upload|save|create|generate)|submit|upload/i.test(e.name):["model","prompt"].includes(e.kind)?n>0:!1}var bo=new Set(["agent","workflow","tool","human_gate","model","external_api","database","route"]);function No(e){let n=new Map(e.nodes.map(i=>[i.id,i.kind])),t=new Set;for(let i of e.edges)Nt.has(i.kind)&&n.get(i.source)==="function"&&bo.has(n.get(i.target)??"")&&t.add(i.source);return t}function xo(e){let n=new Map;for(let t of e)Nt.has(t.kind)&&(n.set(t.source,(n.get(t.source)??0)+1),n.set(t.target,(n.get(t.target)??0)+1));return n}function vo(e,n){let t={route:100,agent:95,workflow:98,tool:85,model:81,prompt:64,human_gate:92,database:82,external_api:80,service:75,function:60,entrypoint:30,class:20,file:0};return[...e].sort((i,r)=>{let o=t[i.kind]+(n.get(i.id)??0)*4+Te(i)*20;return t[r.kind]+(n.get(r.id)??0)*4+Te(r)*20-o||i.name.localeCompare(r.name)})}function Eo(e,n){let t=$o(e),i=Te(e),r=e.evidence.some(a=>a.method.includes("heuristic")||a.method==="framework_convention"),o=Mo(`${e.name} ${e.qualifiedName??""} ${e.description??""}`,n),s=Oo(o);return{id:`logic_${e.id}`,type:t,label:So(e),description:_o(e,t),sources:Vo(e.evidence.map(a=>a.source)),confidence:V(i),inference:{method:r?"heuristic":"deterministic",explanation:e.evidence.map(a=>a.detail).join("; ")},rawNodeIds:[e.id],product:s,metadata:{rawKind:e.kind,rawName:e.name,documentedCapabilityId:o?.capability.id,documentedCapabilityLabel:o?.capability.label,generatedDescription:!e.description,...e.metadata}}}function $o(e){return e.kind==="function"&&/submit|click|upload/i.test(e.name)?"user_action":e.kind==="route"?"entrypoint":e.kind==="workflow"?"workflow":e.kind==="agent"?"ai_process":e.kind==="tool"?"tool":e.kind==="model"?"model":e.kind==="human_gate"?"human_gate":e.kind==="prompt"||e.kind==="database"?"data":e.kind==="external_api"?"external_system":"process"}function So(e){if(e.kind==="route"){let n=typeof e.metadata?.method=="string"?e.metadata.method:void 0,t=typeof e.metadata?.path=="string"?e.metadata.path:void 0;if(n&&t)return`${n.toUpperCase()} ${t}`}return e.kind==="external_api"?e.name:Ho(Pe(e.name).replace(/\b(agent|service|handler|controller|workflow|orchestrator)\b/gi,"").trim()||Pe(e.name))}var zo=4;function ko(e,n){let t=new Map(e.map(i=>[i.id,i]));for(let i of e){let r={calls:[],branches:[],requests:[],data:[],feeds:[]};for(let s of n){if(s.source!==i.id)continue;let a=t.get(s.target);a&&(a.type==="model"||a.type==="external_system"?he(r.requests,a.id):a.type==="data"?he(r.data,a.id):s.control==="conditional"||s.control==="fallback"?he(r.branches,a.id):s.type==="data_flow"?he(r.feeds,a.id):he(r.calls,a.id))}if(i.behavior=r,i.metadata?.generatedDescription!==!0)continue;let o=Ro(r,s=>t.get(s)?.label??s);o&&(i.description=o)}}function he(e,n){e.includes(n)||e.push(n)}function Ro(e,n){let t=(a,d)=>Lo(a.map(n),d),i=[e.calls.length?`calls ${t(e.calls,"and")}`:void 0,e.branches.length?`branches to ${t(e.branches,"or")}`:void 0,e.requests.length?`requests ${t(e.requests,"and")}`:void 0,e.data.length?`reads or writes ${t(e.data,"and")}`:void 0,e.feeds.length?`passes its result to ${t(e.feeds,"and")}`:void 0].filter(a=>!!a);if(!i.length)return;let[r,...o]=i,s=r.charAt(0).toUpperCase()+r.slice(1);return o.length?`${[s,...o.slice(0,-1)].join(", ")}, and ${o.at(-1)}.`:`${s}.`}function Lo(e,n){let t=e.slice(0,zo),i=e.length>t.length?` and ${e.length-t.length} more`:"";return t.length===1?`${t[0]}${i}`:t.length===2&&!i?`${t[0]} ${n} ${t[1]}`:`${t.slice(0,-1).join(", ")}, ${n} ${t.at(-1)}${i}`}function _o(e,n){if(e.description)return e.description;let t=Pe(e.name).replace(/\b(agent|service|handler|controller)\b/gi,"").replace(/\s+/g," ").trim().toLowerCase();return{user_action:`The user initiates ${t}.`,entrypoint:`The system receives work through ${e.name}.`,process:`The system runs ${t}.`,workflow:`The workflow coordinates ${t}.`,ai_process:`An AI workflow performs ${t}.`,tool:`An Agent uses the tool ${t}.`,model:`The Agent uses the model ${e.name}.`,human_gate:`A person reviews or approves ${t}.`,decision:`The system evaluates ${t}.`,data:`The system reads or changes ${t}.`,external_system:`The flow communicates with ${e.name}.`,result:`The flow produces ${t}.`}[n]}function Ao(e,n,t){let i=new Map;for(let o of e.edges){if(!Nt.has(o.kind))continue;let s=i.get(o.source)??[];s.push(o),i.set(o.source,s)}let r=[];for(let o of n){let s=[...i.get(o)??[]].map(d=>({nodeId:d.target,path:[d]})),a=new Set;for(;s.length;){let d=s.shift();if(!(!d||a.has(d.nodeId))){if(a.add(d.nodeId),n.has(d.nodeId)){let c=t.get(o),g=t.get(d.nodeId);c&&g&&c!==g&&r.push(To(c,g,d.path));continue}if(!(d.path.length>=8))for(let c of i.get(d.nodeId)??[])s.push({nodeId:c.target,path:[...d.path,c]})}}}return Ko(r)}function To(e,n,t){let i=new Set(t.map(s=>s.kind)),r=Po(t.map(s=>s.control)),o=i.has("data_flow")||i.has("reads")||i.has("writes")?"data_flow":r==="conditional"||r==="fallback"||r==="human_approval"?"branch":"flow";return{id:`logic_edge_${qo(`${e}:${o}:${r??"sequential"}:${n}`)}`,source:e,target:n,type:o,label:t.find(s=>s.label)?.label??Io(r),control:r,metadata:r?{retryBounded:r==="retry"?t.some(s=>s.metadata?.retryBounded===!0):void 0,rawControls:[...new Set(t.flatMap(s=>s.control?[s.control]:[]))]}:void 0,confidence:V(Math.min(...t.flatMap(s=>s.evidence.map(a=>a.confidence)))),rawEdgeIds:t.map(s=>s.id)}}function Po(e){return["human_approval","fallback","retry","loop","parallel","conditional","sequential"].find(t=>e.includes(t))}function Io(e){return e&&e!=="sequential"?e.replace("_"," "):void 0}function Do(e,n,t){let i=e.context,r=t??i?.description??i?.documents.find(a=>a.kind==="readme")?.summary??`An evidence-backed understanding of ${e.project.name}.`,o=i?.capabilityHints??[],s=o.length?Math.min(1,o.reduce((a,d)=>a+d.confidence,0)/o.length):i?.documents.length?.7:.55;return{summary:r,capabilities:o,agentNodeIds:n.filter(a=>a.type==="ai_process").map(a=>a.id),workflowNodeIds:n.filter(a=>a.type==="workflow").map(a=>a.id),toolNodeIds:n.filter(a=>a.type==="tool").map(a=>a.id),modelNodeIds:n.filter(a=>a.type==="model").map(a=>a.id),documentsUsed:i?.documents.map(a=>a.path)??[],confidence:V(s)}}var jo=2;function Mo(e,n){let t=bt(e),i;for(let r of n){let o=bt(r.label),s=r.keywords.filter(c=>t.includes(bt(c))),a=o.length>=3&&t.includes(o)?3:0,d=a+s.length;d>0&&(!i||d>i.score||d===i.score&&r.confidence>i.capability.confidence)&&(i={capability:r,score:d,matchedOn:a?"documented_name":"documented_terms",matchedTerms:a?[r.label]:s.slice(0,4)})}return i}function Oo(e){if(!(!e||e.score<jo))return{capabilityId:e.capability.id,label:e.capability.label,origin:e.capability.origin,sources:e.capability.sources,match:V(Math.min(.95,.4+e.score*.15)*e.capability.confidence),matchedOn:e.matchedOn,matchedTerms:e.matchedTerms}}function bt(e){return Pe(e).toLowerCase().replace(/\b(agent|api|handler|route|service|workflow)\b/g," ").replace(/\s+/g," ").trim()}function Fo(e,n){let t=new Map(n.map(i=>[i.id,i.type]));return e.filter(i=>{if(i.type!=="flow"||["external_system","data"].includes(t.get(i.target)??""))return!0;let r=new Map;for(let a of e){if(a.id===i.id)continue;let d=r.get(a.source)??[];d.push(a.target),r.set(a.source,d)}let o=[...r.get(i.source)??[]],s=new Set;for(;o.length;){let a=o.shift();if(!(!a||s.has(a))){if(a===i.target)return!1;s.add(a),o.push(...r.get(a)??[])}}return!0})}function Go(e,n){let t=new Set(n.map(i=>i.source));for(let i of e)!t.has(i.id)&&i.type==="process"&&!/save|store|persist/i.test(i.label)&&(i.type="result",i.description=`The flow produces ${i.label.toLowerCase()}.`)}function Te(e){return e.evidence.length?Math.max(...e.evidence.map(n=>n.confidence)):.5}function Pe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_/.]+/g," ").replace(/\s+/g," ").trim()}function Ho(e){return e.replace(/\b\w/g,n=>n.toUpperCase())}function Vo(e){let n=new Set;return e.filter(t=>{let i=`${t.file}:${t.startLine}`;return n.has(i)?!1:(n.add(i),!0)})}function Ko(e){let n=new Set;return e.filter(t=>{let i=`${t.source}:${t.target}:${t.type}:${t.control??"sequential"}`;return n.has(i)?!1:(n.add(i),!0)})}function qo(e){return ho("sha1").update(e).digest("hex").slice(0,12)}import{createHash as Uo}from"crypto";import{access as Bo,open as Wo,readFile as fn,readdir as mn}from"fs/promises";import M from"path";var Jo=new Set([".git",".next",".logic-map",".turbo","build","coverage","dist","node_modules","out"]),xt=new Set([".md",".mdx",".txt",".rst"]),Yo=new Set([".md",".mdx",".txt",".yaml",".yml",".json"]),Xo=new Set(["agent-runtime-map.config.json","package.json","tsconfig.json","jsconfig.json","next.config.js","next.config.mjs","next.config.ts","vite.config.js","vite.config.ts","wrangler.json","wrangler.toml"]),Zo=/(^|\/)(?:\.env(?:\.[^\/]*)?|[^\/]*\.(?:pem|key|p12|pfx)|(?:credentials?|secrets?)(?:[._-][^\/]*)?)(?:\/|$)/i,hn=/^(about|api|architecture|configuration|contents?|contributing|development|docs?|features?|getting started|installation|license|overview|quick ?start|roadmap|setup|tests?|usage|关于|功能|功能列表|安装|开始|开发|架构|概览|目录|配置|使用|路线图)$/i;async function wn(e,n={}){let t=M.resolve(e),i=[],r=n.maxDocuments??80,o=n.maxDocumentBytes??96e3,s=n.maxTotalBytes??75e4,a=await gs(t,i),d=await ps(t,i),c=(await Qo(t)).slice(0,r),g=[],u=[],m=0;for(let l of c){if(m>=s)break;let f=Math.min(o,s-m),w=await ts(l.absolute,f);if(!w)continue;m+=w.bytesRead;let y=ds(l.relative,w.text),N=Cn(w.text);g.push({path:l.relative,kind:l.kind,title:y,summary:ls(w.text,y),headings:N.map(C=>C.label).slice(0,32),excerpt:pn(w.text,6e3),truncated:w.truncated}),l.kind==="prompt"&&u.push({path:l.relative,name:y,excerpt:pn(w.text,6e3),variables:us(w.text),source:"file"})}c.length>=r&&i.push({level:"warning",code:"PROJECT_CONTEXT_FILE_LIMIT",message:`Project context reading was limited to ${r} documentation and prompt files.`}),m>=s&&i.push({level:"warning",code:"PROJECT_CONTEXT_BYTE_LIMIT",message:`Project context reading reached the ${s}-byte safety limit.`});let h=as([...os(n.productDescription),...ss(d),...g.flatMap(ns),...u.flatMap(rs)]).slice(0,48);return{description:d.description??se(a.description,600),packageManager:await hs(t),scripts:Object.keys(G(a.scripts)).sort(),dependencies:fs(a),documents:g,prompts:u,configurationFiles:await ms(t),capabilityHints:h,localization:d.terms||d.nodes?{terms:d.terms,nodes:d.nodes}:void 0,diagnostics:i}}async function Qo(e){let n=[];async function t(i,r){if(r>5)return;let o;try{o=await mn(i,{withFileTypes:!0})}catch{return}o.sort((s,a)=>s.name.localeCompare(a.name));for(let s of o){let a=M.join(i,s.name),d=ys(e,a);if(s.isDirectory()){!Jo.has(s.name)&&!s.name.startsWith(".")&&await t(a,r+1);continue}if(!s.isFile()||Zo.test(d))continue;let c=es(d);c&&n.push({absolute:a,relative:d,kind:c})}}return await t(e,0),n.sort((i,r)=>gn(i)-gn(r)||i.relative.localeCompare(r.relative))}function es(e){let n=e.toLowerCase(),t=M.posix.basename(n),i=M.posix.extname(t);if(/^readme(?:\.|$)/.test(t)&&xt.has(i))return"readme";if(/(^|\/)(prd|product[-_ ]?requirements?)(\.|\/)/.test(n)&&xt.has(i))return"prd";if(/(^|\/)(prompts?|instructions?|system-prompts?)(\/|\.|$)/.test(n)&&Yo.has(i))return"prompt";if((n.startsWith("docs/")||n.includes("/docs/"))&&xt.has(i))return"documentation"}function gn(e){return e.kind==="readme"?0:e.kind==="prd"?1:e.kind==="prompt"?2:3}async function ts(e,n){let t;try{t=await Wo(e,"r");let i=await t.stat(),r=Math.min(i.size,Math.max(0,n)),o=Buffer.alloc(r),s=await t.read(o,0,r,0),a=o.subarray(0,s.bytesRead);return a.includes(0)?void 0:{text:a.toString("utf8"),bytesRead:s.bytesRead,truncated:i.size>s.bytesRead}}catch{return}finally{await t?.close().catch(()=>{})}}function ns(e){let n=e.excerpt.split(/\r?\n/),t=[];for(let i=0;i<n.length;i+=1){let r=n[i]??"",o=/^(#{2,4})\s+(.+?)\s*$/.exec(r),s=/^\s*[-*+]\s+\*\*(.+?)\*\*\s*[::-]?\s*(.*)$/.exec(r),a=ee(o?.[2]??s?.[1]??"");if(!yn(a))continue;let d=ee(s?.[2]||cs(n,i+1));t.push({id:`capability_${je(`${e.path}:${i+1}:${a}`)}`,label:a,description:d||`Project documentation describes ${a}.`,keywords:Ie(`${a} ${d}`),origin:is(e.kind),sources:[{file:e.path,startLine:i+1}],confidence:e.kind==="prd"?.9:e.kind==="readme"?.8:.74})}return t}function is(e){return e==="readme"?"readme":e==="prd"?"prd":e==="prompt"?"prompt":"docs"}function rs(e){let n=ee(e.name);if(!yn(n))return[];let t=bn(e.excerpt);return t?[{id:`capability_${je(`prompt:${e.path}:${n}`)}`,label:n,description:t,keywords:Ie(`${n} ${t}`),origin:"prompt",sources:[{file:e.path,startLine:1,symbol:e.name}],confidence:.7}]:[]}function os(e){let n=e?.trim();return n?[{id:`capability_${je(`user:${n}`)}`,label:ee(bn(n))||n.slice(0,80),description:n.slice(0,600),keywords:Ie(n),origin:"user",sources:[],confidence:1}]:[]}function ss(e){return Object.entries(e.features??{}).map(([n,t])=>{let i=t.label?.trim()||$t(n);return{id:`capability_${je(`config:${n}`)}`,label:i,description:t.description?.trim()||`Configured project capability ${i}.`,keywords:De([...t.keywords??[],...Ie(`${n} ${i} ${t.description??""}`)]),origin:"config",sources:[{file:"agent-runtime-map.config.json",startLine:1,symbol:n}],confidence:1}})}function as(e){let n=new Map;for(let t of e){let i=ws(t.label),r=n.get(i);if(!r){n.set(i,t);continue}n.set(i,{...r,description:r.description.length>=t.description.length?r.description:t.description,keywords:De([...r.keywords,...t.keywords]),sources:xs([...r.sources,...t.sources]),confidence:Math.max(r.confidence,t.confidence)})}return[...n.values()]}function yn(e){return!e||e.length<3||e.length>80||hn.test(e)?!1:!/^(v?\d+(\.\d+)+|https?:|npm |pnpm |yarn )/i.test(e)}function Cn(e){return e.split(/\r?\n/).flatMap((n,t)=>{let i=/^(#{1,4})\s+(.+?)\s*$/.exec(n);return i?[{label:ee(i[2]??""),line:t+1}]:[]})}function cs(e,n){for(let t=n;t<Math.min(e.length,n+5);t+=1){let i=e[t]?.trim()??"";if(i&&!i.startsWith("#")&&!i.startsWith("```")&&!/^[-*_]{3,}$/.test(i))return i}return""}function ds(e,n){return Cn(n)[0]?.label||$t(M.posix.basename(e,M.posix.extname(e)))}function ls(e,n){return(e.split(/\r?\n/).map(r=>ee(r)).find(r=>r&&r!==n&&!hn.test(r)&&!r.startsWith("```"))||n).slice(0,320)}function us(e){let n=[...e.matchAll(/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g),...e.matchAll(/\$\{\s*([A-Za-z_][\w.-]*)\s*\}/g)].map(t=>t[1]).filter(t=>!!t);return De(n).slice(0,40)}function pn(e,n){return e.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\n{4,}/g,`
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
`).trim().slice(0,n)}async function Yr(e,n){try{return W(JSON.parse(await St(T.join(e,"package.json"),"utf8")))}catch(t){return await Ke(T.join(e,"package.json"))&&n.push({level:"warning",code:"PROJECT_MANIFEST_INVALID",message:`Could not parse package.json: ${t instanceof Error?t.message:String(t)}`,source:{file:"package.json",startLine:1}}),{}}}async function Zr(e,n){let t=T.join(e,"agent-runtime-map.config.json");try{return ro(JSON.parse(await St(t,"utf8")))}catch(i){return await Ke(t)&&n.push({level:"warning",code:"PROJECT_READER_CONFIG_INVALID",message:`Could not parse agent-runtime-map.config.json: ${i instanceof Error?i.message:String(i)}`,source:{file:"agent-runtime-map.config.json",startLine:1}}),{}}}function Qr(e){return[["runtime",e.dependencies],["development",e.devDependencies],["peer",e.peerDependencies]].flatMap(([t,i])=>Object.entries(W(i)).map(([r,s])=>({name:r,version:String(s),category:t}))).sort((t,i)=>t.name.localeCompare(i.name))}async function eo(e){let n=[],t;try{t=await kt(e,{withFileTypes:!0})}catch{return n}for(let i of t)i.isFile()&&jr.has(i.name)&&n.push(i.name);return n.sort()}async function to(e){for(let[n,t]of[["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"],["package-lock.json","npm"]])if(await Ke(T.join(e,n)))return t}async function Ke(e){try{return await Lr(e),!0}catch{return!1}}function At(e){let n=V(e.split(/\r?\n/).find(i=>i.trim().length>0)??"");return(/^(.{10,200}?[.!?。!?])\s/.exec(`${n} `)?.[1]??n).slice(0,200).trim()}function V(e){return e.replace(/<[^>]+>/g," ").replace(/\[([^\]]+)\]\([^\)]+\)/g,"$1").replace(/[*_`>#]/g,"").replace(/^[-+\d.()\s]+/,"").replace(/\s+/g," ").trim()}function me(e){let n=e.toLowerCase().match(/[a-z][a-z0-9-]{2,}/g)??[],t=e.match(/[\u3400-\u9fff]{2,8}/g)??[],i=new Set(["agent","agents","and","before","can","feature","features","for","from","into","its","later","project","returning","runtime","system","that","the","this","through","using","with","\u529F\u80FD","\u7CFB\u7EDF","\u9879\u76EE"]);return he([...n,...t].filter(r=>!i.has(r))).slice(0,24)}function qe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_/.]+/g," ").replace(/\s+/g," ").trim()}function no(e){return qe(e).toLowerCase().replace(/\b(agent|service|workflow|feature)\b/g,"").replace(/\s+/g,"").trim()}function io(e,n){return T.relative(e,n).split(T.sep).join("/")}function W(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ro(e){let n=W(e),t=Object.fromEntries(Object.entries(W(n.features)).flatMap(([i,r])=>{let s=W(r),o=fe(s.label,80),a=fe(s.description,600),d=Array.isArray(s.keywords)?s.keywords.flatMap(c=>typeof c=="string"&&c.trim()?[c.trim().slice(0,80)]:[]).slice(0,24):void 0;return!o&&!a&&!d?.length?[]:[[i.slice(0,120),{label:o,description:a,keywords:d}]]}));return{description:fe(n.description,600),features:t}}function fe(e,n){return typeof e=="string"&&e.trim()?e.trim().slice(0,n):void 0}function he(e){return[...new Set(e)]}function oo(e){let n=new Set;return e.filter(t=>{let i=`${t.file}:${t.startLine}:${t.symbol??""}`;return n.has(i)?!1:(n.add(i),!0)})}function we(e){return Ar("sha1").update(e).digest("hex").slice(0,12)}var so={type:"object",additionalProperties:!1,required:["summary","confidence","nodes","features"],properties:{summary:{type:"string",maxLength:600},confidence:{type:"number",minimum:0,maximum:1},nodes:{type:"array",maxItems:80,items:{type:"object",additionalProperties:!1,required:["id","label","description","confidence","reason"],properties:{id:{type:"string"},label:{type:"string",maxLength:80},description:{type:"string",maxLength:400},confidence:{type:"number",minimum:0,maximum:1},reason:{type:"string",maxLength:400}}}},features:{type:"array",maxItems:48,items:{type:"object",additionalProperties:!1,required:["id","label","description","confidence","reason"],properties:{id:{type:"string"},label:{type:"string",maxLength:80},description:{type:"string",maxLength:400},confidence:{type:"number",minimum:0,maximum:1},reason:{type:"string",maxLength:400}}}}}};async function Lt(e,n,t){if(!t.apiKey.trim())throw new Error("Semantic enrichment requires an API key.");if(!t.model.trim())throw new Error("Semantic enrichment requires an explicit model name.");let i=t.fetchImpl??fetch,r=(t.baseUrl??"https://api.openai.com/v1").replace(/\/$/,""),s=ao(e,n,t.maxDocumentCharacters??16e3),o=await i(`${r}/responses`,{method:"POST",headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,store:!1,instructions:["You are the semantic compiler for an evidence-backed Agent code map.","Translate technical names into concise product and runtime concepts.","Use only the supplied node and feature IDs. Never add nodes, edges, files, or capabilities.","Do not hide uncertainty: lower confidence when documentation and code evidence disagree.","Labels must describe observable business or Agent behavior, not implementation syntax."].join(" "),input:JSON.stringify(s),text:{format:{type:"json_schema",name:"agent_runtime_map_semantics",strict:!0,schema:so}}})}),a=await o.json();if(!o.ok)throw new Error(go(a,o.status));let d=lo(a);if(!d)throw new Error("Semantic enrichment returned no structured output.");return co(n,JSON.parse(d),t.model)}function ao(e,n,t=16e3){let i=Math.max(0,t),r=(e.context?.documents??[]).flatMap(o=>{if(i<=0)return[];let a=o.excerpt.slice(0,Math.min(i,2e3));return i-=a.length,[{path:o.path,kind:o.kind,title:o.title,summary:o.summary,excerpt:a}]}),s=(e.context?.prompts??[]).flatMap(o=>{if(i<=0)return[];let a=o.excerpt.slice(0,Math.min(i,1200));return i-=a.length,[{path:o.path,name:o.name,excerpt:a,variables:o.variables}]});return{project:{name:e.project.name,frameworks:e.project.frameworks,description:e.context?.description,dependencies:e.context?.dependencies.map(o=>o.name).slice(0,120)??[]},documentedCapabilities:e.context?.capabilityHints??[],documents:r,prompts:s,nodes:n.nodes.map(o=>({id:o.id,type:o.type,label:o.label,description:o.description,confidence:o.confidence,sources:o.sources,metadata:uo(o.metadata)})),edges:n.edges.map(o=>({id:o.id,source:o.source,target:o.target,type:o.type,control:o.control,label:o.label,confidence:o.confidence})),features:n.features.map(o=>({id:o.id,label:o.label,description:o.description,nodeIds:o.nodeIds,health:o.health,confidence:o.confidence}))}}function co(e,n,t){let i=new Set(e.nodes.map(c=>c.id)),r=new Set(e.features.map(c=>c.id)),s=new Map(n.nodes.filter(c=>i.has(c.id)&&J(c.label,80)&&J(c.description,400)).map(c=>[c.id,c])),o=new Map(n.features.filter(c=>r.has(c.id)&&J(c.label,80)&&J(c.description,400)).map(c=>[c.id,c])),a=e.nodes.map(c=>{let g=s.get(c.id);return g?{...c,label:g.label.trim(),description:g.description.trim(),confidence:Math.min(c.confidence,Ue(g.confidence)),inference:{method:"mixed",explanation:`${c.inference.explanation}; LLM semantic compression (${t}): ${g.reason.trim()}`},metadata:{...c.metadata,semanticModel:t,generatedDescription:!1}}:c}),d=e.features.map(c=>{let g=o.get(c.id);return g?{...c,label:g.label.trim(),description:g.description.trim(),confidence:Math.min(c.confidence,Ue(g.confidence))}:c});return{...e,description:J(n.summary,600)?n.summary.trim():e.description,understanding:e.understanding?{...e.understanding,summary:J(n.summary,600)?n.summary.trim():e.understanding.summary,confidence:Math.min(e.understanding.confidence,Ue(n.confidence))}:e.understanding,nodes:a,features:d,diagnostics:[...e.diagnostics,{level:"info",code:"SEMANTIC_ENRICHMENT_APPLIED",message:`Applied evidence-constrained semantic labels with ${t}; graph topology and source evidence were not changed.`}]}}function uo(e){if(!e)return{};let n=["rawKind","rawName","role","returnType","parameters","factory","model","toolNames","documentedCapabilityLabel"];return Object.fromEntries(Object.entries(e).filter(([t])=>n.includes(t)))}function lo(e){let n=Array.isArray(e.output)?e.output:[];for(let t of n){if(!t||typeof t!="object")continue;let i=Array.isArray(t.content)?t.content:[];for(let r of i)if(r&&typeof r=="object"&&r.type==="output_text"&&typeof r.text=="string")return r.text}}function go(e,n){let t=e.error,i=t&&typeof t=="object"&&typeof t.message=="string"?t.message:void 0;return`Semantic enrichment request failed (${n})${i?`: ${i}`:"."}`}function J(e,n){return typeof e=="string"&&e.trim().length>0&&e.trim().length<=n}function Ue(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}import{createHash as po,randomBytes as fo}from"crypto";import{watch as It}from"fs";import{cp as Vt,mkdir as Xe,readFile as ne,readdir as Kt,rename as Be,rm as be,stat as ie,writeFile as xe}from"fs/promises";import x from"path";var mo=".agent-runtime-map",ho=["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.mjs","**/*.cjs","**/*.py","**/*.md","**/*.mdx","**/*.txt","package.json","agent-runtime-map.config.json"],qt=new Set([".git",".hg",".svn",".next",".turbo",".venv",".logic-map","node_modules","dist","build","out","coverage","__pycache__","venv","site-packages"]);function Je(e){let n=e?.watch;return{outDir:typeof e?.outDir=="string"&&e.outDir.trim()?e.outDir.trim():mo,watch:{include:Ht(n?.include)??[...ho],exclude:Ht(n?.exclude)??[],debounceMs:zt(n?.debounceMs,50,6e4)??800},history:{limit:zt(e?.history?.limit,0,1e4)??30}}}async function Ye(e){let n=x.join(x.resolve(e),"agent-runtime-map.config.json");try{let t=JSON.parse(await ne(n,"utf8"));return{config:Je(t),configFile:n}}catch(t){let i=await ie(n).then(()=>!0,()=>!1);return{config:Je(),configFile:n,warning:i?`Could not parse agent-runtime-map.config.json (${t instanceof Error?t.message:String(t)}); using defaults.`:void 0}}}async function Ut(e){let n=x.resolve(e),t=x.join(n,"agent-runtime-map.config.json"),i=Je(),r={"map:build":"agent-runtime-map build .","map:watch":"agent-runtime-map watch ."},s;try{let d=JSON.parse(await ne(t,"utf8"));s=d&&typeof d=="object"&&!Array.isArray(d)?d:{}}catch(d){if(await ie(t).then(()=>!0,()=>!1))throw new Error(`agent-runtime-map.config.json exists but could not be parsed: ${d instanceof Error?d.message:String(d)}`)}let o=s?{...s}:{},a=[];return o.outDir===void 0&&(o.outDir=i.outDir,a.push("outDir")),o.watch===void 0&&(o.watch=i.watch,a.push("watch")),o.history===void 0&&(o.history=i.history,a.push("history")),(!s||a.length)&&await xe(t,`${JSON.stringify(o,null,2)}
|
|
7
|
-
`,"utf8"),{configFile:t,created:!
|
|
8
|
-
<script type="module"`).replace("</body>",`${
|
|
9
|
-
</body>`);if(c===a)throw new Error("Viewer index.html has an unexpected shape; report.html was not generated.");await
|
|
10
|
-
`),"utf8")}function
|
|
6
|
+
`).trim().slice(0,n)}async function gs(e,n){try{return G(JSON.parse(await fn(M.join(e,"package.json"),"utf8")))}catch(t){return await Et(M.join(e,"package.json"))&&n.push({level:"warning",code:"PROJECT_MANIFEST_INVALID",message:`Could not parse package.json: ${t instanceof Error?t.message:String(t)}`,source:{file:"package.json",startLine:1}}),{}}}async function ps(e,n){let t=M.join(e,"agent-runtime-map.config.json");try{return Cs(JSON.parse(await fn(t,"utf8")))}catch(i){return await Et(t)&&n.push({level:"warning",code:"PROJECT_READER_CONFIG_INVALID",message:`Could not parse agent-runtime-map.config.json: ${i instanceof Error?i.message:String(i)}`,source:{file:"agent-runtime-map.config.json",startLine:1}}),{}}}function fs(e){return[["runtime",e.dependencies],["development",e.devDependencies],["peer",e.peerDependencies]].flatMap(([t,i])=>Object.entries(G(i)).map(([r,o])=>({name:r,version:String(o),category:t}))).sort((t,i)=>t.name.localeCompare(i.name))}async function ms(e){let n=[],t;try{t=await mn(e,{withFileTypes:!0})}catch{return n}for(let i of t)i.isFile()&&Xo.has(i.name)&&n.push(i.name);return n.sort()}async function hs(e){for(let[n,t]of[["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"],["package-lock.json","npm"]])if(await Et(M.join(e,n)))return t}async function Et(e){try{return await Bo(e),!0}catch{return!1}}function bn(e){let n=ee(e.split(/\r?\n/).find(i=>i.trim().length>0)??"");return(/^(.{10,200}?[.!?。!?])\s/.exec(`${n} `)?.[1]??n).slice(0,200).trim()}function ee(e){return e.replace(/<[^>]+>/g," ").replace(/\[([^\]]+)\]\([^\)]+\)/g,"$1").replace(/[*_`>#]/g,"").replace(/^[-+\d.()\s]+/,"").replace(/\s+/g," ").trim()}function Ie(e){let n=e.toLowerCase().match(/[a-z][a-z0-9-]{2,}/g)??[],t=e.match(/[\u3400-\u9fff]{2,8}/g)??[],i=new Set(["agent","agents","and","before","can","feature","features","for","from","into","its","later","project","returning","runtime","system","that","the","this","through","using","with","\u529F\u80FD","\u7CFB\u7EDF","\u9879\u76EE"]);return De([...n,...t].filter(r=>!i.has(r))).slice(0,24)}function $t(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_/.]+/g," ").replace(/\s+/g," ").trim()}function ws(e){return $t(e).toLowerCase().replace(/\b(agent|service|workflow|feature)\b/g,"").replace(/\s+/g,"").trim()}function ys(e,n){return M.relative(e,n).split(M.sep).join("/")}function G(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Cs(e){let n=G(e),t=Object.fromEntries(Object.entries(G(n.features)).flatMap(([i,r])=>{let o=G(r),s=se(o.label,80),a=se(o.description,600),d=Array.isArray(o.keywords)?o.keywords.flatMap(c=>typeof c=="string"&&c.trim()?[c.trim().slice(0,80)]:[]).slice(0,24):void 0;return!s&&!a&&!d?.length?[]:[[i.slice(0,120),{label:s,description:a,keywords:d}]]}));return{description:se(n.description,600),features:t,terms:bs(n.terms),nodes:Ns(n.nodes)}}function bs(e){let n=Object.entries(G(e)).flatMap(([t,i])=>{let r=t.trim().toLowerCase().slice(0,64),o=vt(i,80);return r&&o?[[r,o]]:[]}).slice(0,500);return n.length?Object.fromEntries(n):void 0}function Ns(e){let n=Object.entries(G(e)).flatMap(([t,i])=>{let r=G(i),o=vt(r.label,80),s=vt(r.description,600);return!o&&!s?[]:[[t.trim().slice(0,200),{label:o,description:s}]]}).slice(0,500);return n.length?Object.fromEntries(n):void 0}function vt(e,n){let t=G(e),i=se(t["zh-CN"],n),r=se(t.en,n);return i||r?{...i?{"zh-CN":i}:{},...r?{en:r}:{}}:void 0}function se(e,n){return typeof e=="string"&&e.trim()?e.trim().slice(0,n):void 0}function De(e){return[...new Set(e)]}function xs(e){let n=new Set;return e.filter(t=>{let i=`${t.file}:${t.startLine}:${t.symbol??""}`;return n.has(i)?!1:(n.add(i),!0)})}function je(e){return Uo("sha1").update(e).digest("hex").slice(0,12)}var vs={type:"object",additionalProperties:!1,required:["summary","confidence","nodes","features"],properties:{summary:{type:"string",maxLength:600},confidence:{type:"number",minimum:0,maximum:1},nodes:{type:"array",maxItems:80,items:{type:"object",additionalProperties:!1,required:["id","label","description","confidence","reason"],properties:{id:{type:"string"},label:{type:"string",maxLength:80},description:{type:"string",maxLength:400},confidence:{type:"number",minimum:0,maximum:1},reason:{type:"string",maxLength:400}}}},features:{type:"array",maxItems:48,items:{type:"object",additionalProperties:!1,required:["id","label","description","confidence","reason"],properties:{id:{type:"string"},label:{type:"string",maxLength:80},description:{type:"string",maxLength:400},confidence:{type:"number",minimum:0,maximum:1},reason:{type:"string",maxLength:400}}}}}};async function Nn(e,n,t){if(!t.apiKey.trim())throw new Error("Semantic enrichment requires an API key.");if(!t.model.trim())throw new Error("Semantic enrichment requires an explicit model name.");let i=t.fetchImpl??fetch,r=(t.baseUrl??"https://api.openai.com/v1").replace(/\/$/,""),o=Es(e,n,t.maxDocumentCharacters??16e3),s=await i(`${r}/responses`,{method:"POST",headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,store:!1,instructions:["You are the semantic compiler for an evidence-backed Agent code map.","Translate technical names into concise product and runtime concepts.","Use only the supplied node and feature IDs. Never add nodes, edges, files, or capabilities.","Do not hide uncertainty: lower confidence when documentation and code evidence disagree.","Labels must describe observable business or Agent behavior, not implementation syntax."].join(" "),input:JSON.stringify(o),text:{format:{type:"json_schema",name:"agent_runtime_map_semantics",strict:!0,schema:vs}}})}),a=await s.json();if(!s.ok)throw new Error(ks(a,s.status));let d=zs(a);if(!d)throw new Error("Semantic enrichment returned no structured output.");return $s(n,JSON.parse(d),t.model)}function Es(e,n,t=16e3){let i=Math.max(0,t),r=(e.context?.documents??[]).flatMap(s=>{if(i<=0)return[];let a=s.excerpt.slice(0,Math.min(i,2e3));return i-=a.length,[{path:s.path,kind:s.kind,title:s.title,summary:s.summary,excerpt:a}]}),o=(e.context?.prompts??[]).flatMap(s=>{if(i<=0)return[];let a=s.excerpt.slice(0,Math.min(i,1200));return i-=a.length,[{path:s.path,name:s.name,excerpt:a,variables:s.variables}]});return{project:{name:e.project.name,frameworks:e.project.frameworks,description:e.context?.description,dependencies:e.context?.dependencies.map(s=>s.name).slice(0,120)??[]},documentedCapabilities:e.context?.capabilityHints??[],documents:r,prompts:o,nodes:n.nodes.map(s=>({id:s.id,type:s.type,label:s.label,description:s.description,confidence:s.confidence,sources:s.sources,metadata:Ss(s.metadata)})),edges:n.edges.map(s=>({id:s.id,source:s.source,target:s.target,type:s.type,control:s.control,label:s.label,confidence:s.confidence})),features:n.features.map(s=>({id:s.id,label:s.label,description:s.description,nodeIds:s.nodeIds,health:s.health,confidence:s.confidence}))}}function $s(e,n,t){let i=new Set(e.nodes.map(c=>c.id)),r=new Set(e.features.map(c=>c.id)),o=new Map(n.nodes.filter(c=>i.has(c.id)&&ae(c.label,80)&&ae(c.description,400)).map(c=>[c.id,c])),s=new Map(n.features.filter(c=>r.has(c.id)&&ae(c.label,80)&&ae(c.description,400)).map(c=>[c.id,c])),a=e.nodes.map(c=>{let g=o.get(c.id);if(!g)return c;let u=c.semantic?.pending!==!1,m=c.semantic&&u?{...c.semantic,label:{"zh-CN":g.label.trim(),en:g.label.trim()},description:{"zh-CN":g.description.trim(),en:g.description.trim()},labelSource:{"zh-CN":"llm",en:"llm"},confidence:{"zh-CN":we(g.confidence),en:we(g.confidence)},pending:!1}:c.semantic;return{...c,label:u?g.label.trim():c.label,description:u?g.description.trim():c.description,semantic:m,confidence:Math.min(c.confidence,we(g.confidence)),inference:{method:"mixed",explanation:`${c.inference.explanation}; LLM semantic compression (${t}): ${g.reason.trim()}`},metadata:{...c.metadata,semanticModel:t,generatedDescription:!1}}}),d=e.features.map(c=>{let g=s.get(c.id);return g?{...c,label:g.label.trim(),description:g.description.trim(),confidence:Math.min(c.confidence,we(g.confidence))}:c});return{...e,description:ae(n.summary,600)?n.summary.trim():e.description,understanding:e.understanding?{...e.understanding,summary:ae(n.summary,600)?n.summary.trim():e.understanding.summary,confidence:Math.min(e.understanding.confidence,we(n.confidence))}:e.understanding,nodes:a,features:d,diagnostics:[...e.diagnostics,{level:"info",code:"SEMANTIC_ENRICHMENT_APPLIED",message:`Applied evidence-constrained semantic labels with ${t}; graph topology and source evidence were not changed.`}]}}function Ss(e){if(!e)return{};let n=["rawKind","rawName","role","returnType","parameters","factory","model","toolNames","documentedCapabilityLabel"];return Object.fromEntries(Object.entries(e).filter(([t])=>n.includes(t)))}function zs(e){let n=Array.isArray(e.output)?e.output:[];for(let t of n){if(!t||typeof t!="object")continue;let i=Array.isArray(t.content)?t.content:[];for(let r of i)if(r&&typeof r=="object"&&r.type==="output_text"&&typeof r.text=="string")return r.text}}function ks(e,n){let t=e.error,i=t&&typeof t=="object"&&typeof t.message=="string"?t.message:void 0;return`Semantic enrichment request failed (${n})${i?`: ${i}`:"."}`}function ae(e,n){return typeof e=="string"&&e.trim().length>0&&e.trim().length<=n}function we(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}import{createHash as Rs,randomBytes as Ls}from"crypto";import{watch as xn}from"fs";import{cp as An,mkdir as Rt,readFile as ye,readdir as Tn,rename as St,rm as Oe,stat as Ce,writeFile as Fe}from"fs/promises";import v from"path";var _s=".agent-runtime-map",As=["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.mjs","**/*.cjs","**/*.py","**/*.md","**/*.mdx","**/*.txt","package.json","agent-runtime-map.config.json"],Pn=new Set([".git",".hg",".svn",".next",".turbo",".venv",".logic-map","node_modules","dist","build","out","coverage","__pycache__","venv","site-packages"]);function kt(e){let n=e?.watch;return{outDir:typeof e?.outDir=="string"&&e.outDir.trim()?e.outDir.trim():_s,watch:{include:Ln(n?.include)??[...As],exclude:Ln(n?.exclude)??[],debounceMs:_n(n?.debounceMs,50,6e4)??800},history:{limit:_n(e?.history?.limit,0,1e4)??30}}}async function Lt(e){let n=v.join(v.resolve(e),"agent-runtime-map.config.json");try{let t=JSON.parse(await ye(n,"utf8"));return{config:kt(t),configFile:n}}catch(t){let i=await Ce(n).then(()=>!0,()=>!1);return{config:kt(),configFile:n,warning:i?`Could not parse agent-runtime-map.config.json (${t instanceof Error?t.message:String(t)}); using defaults.`:void 0}}}async function In(e){let n=v.resolve(e),t=v.join(n,"agent-runtime-map.config.json"),i=kt(),r={"map:build":"agent-runtime-map build .","map:watch":"agent-runtime-map watch ."},o;try{let d=JSON.parse(await ye(t,"utf8"));o=d&&typeof d=="object"&&!Array.isArray(d)?d:{}}catch(d){if(await Ce(t).then(()=>!0,()=>!1))throw new Error(`agent-runtime-map.config.json exists but could not be parsed: ${d instanceof Error?d.message:String(d)}`)}let s=o?{...o}:{},a=[];return s.outDir===void 0&&(s.outDir=i.outDir,a.push("outDir")),s.watch===void 0&&(s.watch=i.watch,a.push("watch")),s.history===void 0&&(s.history=i.history,a.push("history")),(!o||a.length)&&await Fe(t,`${JSON.stringify(s,null,2)}
|
|
7
|
+
`,"utf8"),{configFile:t,created:!o,addedKeys:a,suggestedScripts:r}}function Ge(e){let{generatedAt:n,...t}=e;return Rs("sha1").update(JSON.stringify(t)).digest("hex").slice(0,16)}function Ts(e,n,t){let i=zt(e?.nodes??[],n.nodes,Ps),r=zt(e?.edges??[],n.edges,Is),o=zt(e?.features??[],n.features,vn),s=new Set([...i.added.map(u=>u.id),...i.removed.map(u=>u.id),...i.modified.map(u=>u.id),...r.added.map(u=>u.id),...r.removed.map(u=>u.id),...r.modified.map(u=>u.id)]),a=new Set([...o.added.map(u=>u.id),...o.modified.map(u=>u.id)]),d=n.features.filter(u=>a.has(u.id)||u.nodeIds.some(m=>s.has(m))||u.edgeIds.some(m=>s.has(m))).map(vn),c=e?En(e):new Map,g=En(n);return{schemaVersion:1,generatedAt:t.generatedAt,buildId:Ge(n),previousBuildId:e?Ge(e):void 0,initial:!e,trigger:t.trigger,nodes:i,edges:r,features:o,affectedFeatures:d,diagnostics:{appeared:[...g].filter(([u])=>!c.has(u)).map(([,u])=>u),resolved:[...c].filter(([u])=>!g.has(u)).map(([,u])=>u)}}}function zt(e,n,t){let i=new Map(e.map(o=>[o.id,o])),r=new Map(n.map(o=>[o.id,o]));return{added:n.filter(o=>!i.has(o.id)).map(t),removed:e.filter(o=>!r.has(o.id)).map(t),modified:n.filter(o=>{let s=i.get(o.id);return s!==void 0&&JSON.stringify(s)!==JSON.stringify(o)}).map(t)}}function Ps(e){return{id:e.id,label:e.label,type:e.type}}function Is(e){return{id:e.id,source:e.source,target:e.target,type:e.type}}function vn(e){return{id:e.id,label:e.label}}function En(e){let n=new Map,t=i=>{n.set(`${i.featureId??""}|${i.level}|${i.code}|${i.message}`,i)};for(let i of e.diagnostics)t({level:i.level,code:i.code,message:i.message});for(let i of e.features)for(let r of i.diagnostics)t({level:r.severity,code:r.code,message:r.message,featureId:i.id,nodeId:r.nodeId});return n}var Ds=["graph.json","manifest.json","status.json","changes.json","report.html"];async function He(e,n,t={}){let i=v.resolve(e),r=v.isAbsolute(n.outDir)?n.outDir:v.join(i,n.outDir),o=v.join(r,"current"),s=t.now??(()=>new Date),a=t.trigger?.length?t.trigger:["manual"],d=t.analyze??Ke,c=Date.now(),g=await Me(v.join(o,"graph.json")),u=await Me(v.join(o,"status.json")),m=await Me(v.join(o,"manifest.json")),h;try{h=await d(i,{...t.analyzeOptions,outputFile:!1,rawOutputFile:!1})}catch(b){let x=Date.now()-c,S=b instanceof Error?b.message:String(b);return await $n(o,{message:S.slice(0,2e3),failedAt:s().toISOString(),trigger:a,previous:u,toolVersion:t.toolVersion,source:t.source}),{ok:!1,currentDir:o,outDir:r,error:S,durationMs:x}}let l=Ge(h.graph),f=s().toISOString(),w=Date.now()-c;if(g&&Ge(g)===l)return await U(v.join(o,"status.json"),Ve({state:"updated",toolVersion:t.toolVersion,buildId:l,generatedAt:u?.generatedAt??f,lastSuccessAt:f,durationMs:w,trigger:a})),m&&await U(v.join(o,"manifest.json"),{...m,toolVersion:t.toolVersion??m.toolVersion,generatedAt:f,commit:t.source?{sha:t.source.commitSha,ref:t.source.ref,baselineSha:m.commit?.sha,baselineRestored:t.source.baselineRestored}:m.commit}),{ok:!0,unchanged:!0,buildId:l,graph:h.graph,currentDir:o,outDir:r,durationMs:w};let y=Ts(g,h.graph,{trigger:a,generatedAt:f}),N={schemaVersion:1,name:"agent-runtime-map",toolVersion:t.toolVersion??"0.0.0",buildId:l,generatedAt:f,graphType:h.graph.graphType,project:{name:v.basename(i)},commit:t.source?{sha:t.source.commitSha,ref:t.source.ref,baselineSha:m?.commit?.sha,baselineRestored:t.source.baselineRestored}:void 0,files:{graph:"graph.json",rawGraph:"raw-graph.json",changes:"changes.json",status:"status.json",report:"report.html"}},C=v.join(r,`.staging-${Ls(6).toString("hex")}`);try{await Rt(C,{recursive:!0}),await U(v.join(C,"graph.json"),h.graph),await U(v.join(C,"raw-graph.json"),h.rawGraph),await U(v.join(C,"changes.json"),y),await U(v.join(C,"manifest.json"),N),await U(v.join(C,"status.json"),Ve({state:"updated",toolVersion:t.toolVersion,buildId:l,generatedAt:f,lastSuccessAt:f,durationMs:w,trigger:a})),await Gs(C,h.graph,h.rawGraph,t.viewerAssetsDir),await Os(r,C,f,n.history.limit),await js(r,C)}catch(b){await Oe(C,{recursive:!0,force:!0});let x=b instanceof Error?b.message:String(b);return await $n(o,{message:x.slice(0,2e3),failedAt:s().toISOString(),trigger:a,previous:u,toolVersion:t.toolVersion,source:t.source}),{ok:!1,currentDir:o,outDir:r,error:x,durationMs:Date.now()-c}}return{ok:!0,buildId:l,graph:h.graph,changes:y,currentDir:o,outDir:r,durationMs:w}}async function js(e,n){await Ms(n);let t=v.join(e,"current"),i=v.join(e,".previous");await Oe(i,{recursive:!0,force:!0});let r=await Ce(t).then(o=>o.isDirectory(),()=>!1);r&&await St(t,i);try{await St(n,t)}catch(o){throw r&&await St(i,t).catch(()=>{}),o}await Oe(i,{recursive:!0,force:!0})}async function Ms(e){for(let n of Ds){let t=v.join(e,n),i=await Ce(t).catch(()=>{});if(!i?.isFile()||i.size===0)throw new Error(`Staging is incomplete: ${n} is missing or empty. The current map was left untouched.`);n.endsWith(".json")&&JSON.parse(await ye(t,"utf8"))}}async function Os(e,n,t,i){if(i<=0)return;let r=v.join(e,"history"),o=t.replace(/[:.]/g,"-"),s=v.join(r,o);await Rt(s,{recursive:!0});for(let d of["graph.json","changes.json","manifest.json"])await An(v.join(n,d),v.join(s,d));let a=(await Tn(r,{withFileTypes:!0})).filter(d=>d.isDirectory()).map(d=>d.name).sort();for(let d of a.slice(0,Math.max(0,a.length-i)))await Oe(v.join(r,d),{recursive:!0,force:!0})}async function Fs(e,n,t=()=>new Date){let i=await Me(v.join(e,"status.json"));await U(v.join(e,"status.json"),Ve({state:"stale",buildId:i?.buildId,generatedAt:i?.generatedAt,lastSuccessAt:i?.lastSuccessAt,staleSince:t().toISOString(),trigger:n}))}async function $n(e,n){await U(v.join(e,"status.json"),Ve({state:"failed",toolVersion:n.toolVersion,buildId:n.previous?.buildId,generatedAt:n.previous?.generatedAt,lastSuccessAt:n.previous?.lastSuccessAt,trigger:n.trigger,error:{message:n.message,failedAt:n.failedAt},attemptedCommit:n.source?.commitSha,attemptedRef:n.source?.ref}))}function Ve(e){return{schemaVersion:1,...e}}async function Gs(e,n,t,i){let r=Sn(n),o=JSON.stringify(t).length<=4e6?Sn(t):void 0,s=`<script>window.__ARM_GRAPH__=${r};${o?`window.__ARM_RAW_GRAPH__=${o};`:""}</script>`;if(i){let a=await ye(v.join(i,"index.html"),"utf8"),c=a.replace(/<script type="module"/,`${s}
|
|
8
|
+
<script type="module"`).replace("</body>",`${zn}
|
|
9
|
+
</body>`);if(c===a)throw new Error("Viewer index.html has an unexpected shape; report.html was not generated.");await Fe(v.join(e,"report.html"),c,"utf8"),await An(v.join(i,"assets"),v.join(e,"assets"),{recursive:!0});return}await Fe(v.join(e,"report.html"),["<!doctype html>",'<html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/>',`<title>Agent Runtime Map \xB7 ${Hs(n.title??"Report")}</title></head>`,`<body><div id="root"></div>${s}${zn}</body></html>`].join(`
|
|
10
|
+
`),"utf8")}function Sn(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Hs(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var zn=`<script>
|
|
11
11
|
(function () {
|
|
12
12
|
function ready(fn) { document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", fn) : fn(); }
|
|
13
13
|
ready(function () {
|
|
@@ -36,8 +36,8 @@ import{parseArgs as rs}from"util";import{mkdir as Go,stat as Ho,writeFile as zo}
|
|
|
36
36
|
}, 1500);
|
|
37
37
|
});
|
|
38
38
|
})();
|
|
39
|
-
</script>`;function
|
|
40
|
-
`,"utf8")}function
|
|
39
|
+
</script>`;function Vs(e,n){let t=e.replaceAll("\\","/").replace(/^\.\//,"");if(!t||t.startsWith(".."))return!1;let i=n.outDir.replaceAll("\\","/").replace(/\/+$/,"");return t===i||t.startsWith(`${i}/`)||t.split("/").some(o=>Pn.has(o)||o.startsWith(".")&&o!==".")||n.watch.exclude.some(o=>Rn(o).test(t))?!1:n.watch.include.some(o=>Rn(o).test(t))}var kn=new Map;function Rn(e){let n=kn.get(e);if(n)return n;let t="";for(let r=0;r<e.length;r+=1){let o=e[r];o==="*"?e[r+1]==="*"?e[r+2]==="/"?(t+="(?:[^/]+/)*",r+=2):(t+=".*",r+=1):t+="[^/]*":o==="?"?t+="[^/]":t+=o.replace(/[.+^${}()|[\]\\]/g,"\\$&")}let i=new RegExp(`^${t}$`);return kn.set(e,i),i}function Ks(e,n,t){let i=v.resolve(e),r=new Map,o=new Set,s,a=!1,d=g=>{a||!Vs(g,n)||(o.add(g.replaceAll("\\","/")),s&&clearTimeout(s),s=setTimeout(()=>{s=void 0;let u=[...o].sort();o.clear(),!a&&u.length&&t(u)},n.watch.debounceMs))},c=async g=>{if(a||r.has(g))return;let u=v.relative(i,g).replaceAll(v.sep,"/");if(u&&!qs(u,n))return;let m;try{m=xn(g,(l,f)=>{if(!f)return;let w=v.join(u,f.toString()).replaceAll(v.sep,"/");d(w);let y=v.join(i,w);Ce(y).then(N=>{N.isDirectory()&&c(y)}).catch(()=>{})})}catch{return}m.on("error",()=>{}),r.set(g,m);let h;try{h=await Tn(g,{withFileTypes:!0})}catch{return}for(let l of h)l.isDirectory()&&await c(v.join(g,l.name))};try{let g=xn(i,{recursive:!0},(u,m)=>{m&&d(m.toString())});g.on("error",()=>{}),r.set(i,g)}catch{c(i)}return{close:async()=>{a=!0,s&&clearTimeout(s),s=void 0,o.clear();for(let g of r.values())g.close();r.clear()}}}function qs(e,n){let t=n.outDir.replaceAll("\\","/").replace(/\/+$/,"");return e===t||e.startsWith(`${t}/`)?!1:!e.split("/").some(r=>Pn.has(r)||r.startsWith("."))}async function Dn(e,n,t={}){let i=v.join(v.isAbsolute(n.outDir)?n.outDir:v.join(v.resolve(e),n.outDir),"current"),r=await He(e,n,{...t,trigger:t.trigger??["watch-start"]});t.onBuild?.(r);let o=!1,s,a=!1,d=async g=>{o=!0;try{for(;!a;){let u=await He(e,n,{...t,trigger:g});if(t.onBuild?.(u),!s)break;g=[...s].sort(),s=void 0}}finally{o=!1}},c=Ks(e,n,g=>{if(!a){if(t.onChangesDetected?.(g),o){s=new Set([...s??[],...g]);return}Fs(i,g).then(()=>d(g))}});return{initial:r,handle:{close:async()=>{a=!0,await c.close()}}}}async function Me(e){try{return JSON.parse(await ye(e,"utf8"))}catch{return}}async function U(e,n){await Rt(v.dirname(e),{recursive:!0}),await Fe(e,`${JSON.stringify(n,null,2)}
|
|
40
|
+
`,"utf8")}function Ln(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string"&&t.trim().length>0);return n.length||e.length===0?n:void 0}function _n(e,n,t){if(!(typeof e!="number"||!Number.isFinite(e)))return Math.min(t,Math.max(n,Math.round(e)))}import{execFile as Us}from"child_process";import{createHash as Bs}from"crypto";import{mkdir as Ws,readFile as Js,writeFile as jn}from"fs/promises";import qe from"path";import{promisify as Ys}from"util";var Xs=Ys(Us),_t="# agent-runtime-map-integrity: ",Zs=".github/workflows/agent-runtime-map.yml";function Qs(e={}){let t=`# Generated by \`agent-runtime-map init --github\`.
|
|
41
41
|
# Re-running init updates this file only while it is unmodified; edits are yours to keep.
|
|
42
42
|
name: Agent Runtime Map
|
|
43
43
|
|
|
@@ -62,23 +62,23 @@ jobs:
|
|
|
62
62
|
map:
|
|
63
63
|
runs-on: ubuntu-latest
|
|
64
64
|
steps:
|
|
65
|
-
- uses: actions/checkout@
|
|
65
|
+
- uses: actions/checkout@v7
|
|
66
66
|
with:
|
|
67
67
|
# Full history keeps the previous map's commit reachable, so the change
|
|
68
68
|
# report can name the files that actually changed instead of the event.
|
|
69
69
|
fetch-depth: 0
|
|
70
70
|
- uses: TheCrazyAnt/agent-runtime-map@v1
|
|
71
|
-
`;return`${
|
|
72
|
-
${t}`}async function
|
|
73
|
-
`).map(i=>i.trim()).filter(Boolean).includes("origin"))return}catch{return}try{return await n("symbolic-ref","--short","HEAD")||void 0}catch{return}}function
|
|
74
|
-
`);return n<0||!e.startsWith(
|
|
75
|
-
`,"utf8")}function
|
|
71
|
+
`;return`${_t}${Mn(t)}
|
|
72
|
+
${t}`}async function ea(e){let n=async(...t)=>(await Xs("git",["-C",qe.resolve(e),...t])).stdout.trim();try{let t=await n("symbolic-ref","refs/remotes/origin/HEAD"),i=t.replace(/^refs\/remotes\/origin\//,"");if(i&&i!==t)return i}catch{}try{if((await n("remote")).split(`
|
|
73
|
+
`).map(i=>i.trim()).filter(Boolean).includes("origin"))return}catch{return}try{return await n("symbolic-ref","--short","HEAD")||void 0}catch{return}}function Mn(e){return Bs("sha256").update(e).digest("hex").slice(0,16)}function ta(e){let n=e.indexOf(`
|
|
74
|
+
`);return n<0||!e.startsWith(_t)?!1:e.slice(_t.length,n).trim()===Mn(e.slice(n+1))}var be=class extends Error{constructor(t){super(`${t} exists and has local modifications; it was not touched. Re-run with --force to overwrite it.`);this.workflowFile=t;this.name="WorkflowModifiedError"}workflowFile};async function On(e,n={}){let t=qe.join(qe.resolve(e),Zs),i=n.defaultBranch??await ea(e),r=Qs({defaultBranch:i}),o;try{o=await Js(t,"utf8")}catch{o=void 0}if(o!==void 0){if(o===r)return{workflowFile:t,outcome:"unchanged",defaultBranch:i};let s=ta(o);if(!s&&!n.force)throw new be(t);return await jn(t,r,"utf8"),{workflowFile:t,outcome:s?"updated":"overwritten",defaultBranch:i}}return await Ws(qe.dirname(t),{recursive:!0}),await jn(t,r,"utf8"),{workflowFile:t,outcome:"created",defaultBranch:i}}async function Ke(e,n={}){let t=Ue.resolve(e);if(!(await ia(t).catch(()=>{}))?.isDirectory())throw new Error(`Project path does not exist or is not a directory: ${t}`);let r=n.outputFile===!1?void 0:Gn(t,n.outputFile??".logic-map/graph.json"),o=n.rawOutputFile===!1?void 0:Gn(t,n.rawOutputFile??".logic-map/raw-graph.json"),s=n.readContext===!1?void 0:await wn(t,{maxDocuments:n.maxContextFiles,maxTotalBytes:n.maxContextBytes,productDescription:n.productDescription}),[a,d]=await Promise.all([Ht(t,{maxFiles:n.maxFiles}),Yt(t,{maxFiles:n.maxFiles,pythonPath:n.pythonPath})]),c=oa(a,d);if(s){let u=c.nodes.filter(h=>h.kind==="prompt").flatMap(h=>{let l=h.evidence[0]?.source,f=typeof h.metadata?.excerpt=="string"?h.metadata.excerpt:void 0;return!l||!f?[]:[{path:l.file,name:h.name,excerpt:f,variables:Array.isArray(h.metadata?.variables)?h.metadata.variables.filter(w=>typeof w=="string"):[],source:"code"}]}),m=new Set(s.prompts.map(h=>`${h.path}:${h.name}`));s.prompts.push(...u.filter(h=>!m.has(`${h.path}:${h.name}`))),c.context=s,c.diagnostics.push(...s.diagnostics)}let g=un(c,n);return n.semantic&&(g=await Nn(c,g,n.semantic)),r&&await Fn(r,g),o&&await Fn(o,c),{graph:g,rawGraph:c,outputFile:r,rawOutputFile:o}}async function Fn(e,n){await na(Ue.dirname(e),{recursive:!0}),await ra(e,`${JSON.stringify(n,null,2)}
|
|
75
|
+
`,"utf8")}function Gn(e,n){return Ue.isAbsolute(n)?n:Ue.resolve(e,n)}function oa(e,n){return!n.nodes.length&&!n.diagnostics.length?e:{...e,project:{...e.project,languages:[...new Set([...e.project.languages,...n.project.languages])],frameworks:[...new Set([...e.project.frameworks,...n.project.frameworks])],filesScanned:e.project.filesScanned+n.project.filesScanned},nodes:[...e.nodes,...n.nodes],edges:[...e.edges,...n.edges],diagnostics:[...e.diagnostics,...n.diagnostics]}}import{createReadStream as sa}from"fs";import{access as Kn,readFile as aa,stat as qn}from"fs/promises";import{createServer as ca}from"http";import _ from"path";import{spawn as da}from"child_process";import{fileURLToPath as la}from"url";var ua={".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff":"font/woff",".woff2":"font/woff2"};async function Be(e){let n=e.viewerDirectory?_.resolve(e.viewerDirectory):await Je();await Kn(_.join(n,"index.html"));let t=e.host??"127.0.0.1",i=e.port??4173,r=ca((d,c)=>{ga(r,n,e,d.url??"/",d.method??"GET",c)}),o=await ma(r,t,i);return{url:`http://${t==="0.0.0.0"||t==="::"?"localhost":t}:${o}`,port:o,close:()=>new Promise((d,c)=>r.close(g=>g?c(g):d()))}}function We(e){let n=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",t=process.platform==="win32"?["/c","start","",e]:[e];try{let i=da(n,t,{detached:!0,stdio:"ignore"});return i.on("error",()=>{}),i.unref(),!0}catch{return!1}}async function ga(e,n,t,i,r,o){if(fa(o),r!=="GET"&&r!=="HEAD"){o.writeHead(405,{Allow:"GET, HEAD"}),o.end("Method Not Allowed");return}let s,a;try{s=new URL(i,"http://localhost"),a=decodeURIComponent(s.pathname)}catch{o.writeHead(400),o.end("Bad Request");return}if(a==="/healthz"){B(o,200,JSON.stringify({status:"ok"}),"application/json; charset=utf-8",r);return}if(a==="/graph.json"){await Ne(o,t.graphFile,r,"no-store");return}if(a==="/raw-graph.json"){if(!t.rawGraphFile){B(o,404,"Raw graph was not generated.","text/plain; charset=utf-8",r);return}await Ne(o,t.rawGraphFile,r,"no-store");return}if(a==="/source.json"){await pa(o,t,s,r);return}if(t.currentDir&&(a==="/manifest.json"||a==="/status.json"||a==="/changes.json")){await Ne(o,_.join(t.currentDir,a.slice(1)),r,"no-store");return}let d=a==="/"?"index.html":a.replace(/^\/+/,""),c=_.resolve(n,d);if(c!==n&&!c.startsWith(`${n}${_.sep}`)){B(o,403,"Forbidden","text/plain; charset=utf-8",r);return}await Ne(o,c,r,d==="index.html"?"no-cache":"public, max-age=31536000, immutable",n)}async function pa(e,n,t,i){let r=typeof n.sourceFiles=="function"?n.sourceFiles():n.sourceFiles;if(!n.projectRoot||!r?.length){B(e,404,"Source access is unavailable.","text/plain; charset=utf-8",i);return}let o=Hn(t.searchParams.get("file")??""),s=new Set(r.map(Hn));if(!o||_.isAbsolute(o)||o.startsWith("../")||!s.has(o)){B(e,403,"Source file is not part of this graph.","text/plain; charset=utf-8",i);return}let a=_.resolve(n.projectRoot),d=_.resolve(a,o);if(d===a||!d.startsWith(`${a}${_.sep}`)){B(e,403,"Forbidden","text/plain; charset=utf-8",i);return}try{let c=await qn(d);if(!c.isFile()||c.size>15e5)throw new Error("Unsupported source file");let u=(await aa(d,"utf8")).split(/\r?\n/),m=Vn(t.searchParams.get("start"),1),h=Vn(t.searchParams.get("end"),m),l=Math.min(m,Math.max(1,u.length)),f=Math.max(l,Math.min(h,l+119,u.length)),w=Math.max(1,l-6),y=Math.min(u.length,Math.max(f+8,w+24),w+159),N={file:o,startLine:w,endLine:y,highlightStart:l,highlightEnd:f,lines:u.slice(w-1,y).map((C,b)=>({number:w+b,text:C}))};B(e,200,JSON.stringify(N),"application/json; charset=utf-8",i)}catch{B(e,404,"Source file could not be read.","text/plain; charset=utf-8",i)}}function Hn(e){return _.posix.normalize(e.replaceAll("\\","/")).replace(/^\.\//,"")}function Vn(e,n){let t=Number(e);return Number.isInteger(t)&&t>0?t:n}async function Ne(e,n,t,i,r){try{let o=await qn(n);if(!o.isFile())throw new Error("Not a file");e.writeHead(200,{"Cache-Control":i,"Content-Length":o.size,"Content-Type":ua[_.extname(n)]??"application/octet-stream"}),t==="HEAD"?e.end():sa(n).on("error",()=>e.destroy()).pipe(e)}catch{if(r){let o=_.join(r,"index.html");if(n!==o){await Ne(e,o,t,"no-cache");return}}B(e,404,"Not Found","text/plain; charset=utf-8",t)}}function B(e,n,t,i,r){e.writeHead(n,{"Content-Type":i,"Content-Length":Buffer.byteLength(t)}),e.end(r==="HEAD"?void 0:t)}function fa(e){e.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),e.setHeader("Referrer-Policy","no-referrer"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("X-Frame-Options","SAMEORIGIN")}async function ma(e,n,t){if(t===0){await new Promise((r,o)=>{e.once("error",o),e.listen(0,n,()=>r())});let i=e.address();if(!i||typeof i=="string")throw new Error("Could not resolve the assigned viewer port.");return i.port}for(let i=t;i<Math.min(t+20,65536);i+=1)if(await new Promise((o,s)=>{let a=c=>{e.off("listening",d),c.code==="EADDRINUSE"?o("in-use"):s(c)},d=()=>{e.off("error",a),o("listening")};e.once("error",a),e.once("listening",d),e.listen(i,n)})==="listening")return i;throw new Error(`No available port found between ${t} and ${t+19}.`)}async function Je(){let e=_.dirname(la(import.meta.url)),n=[_.join(e,"viewer"),_.resolve(e,"../../../apps/viewer/dist"),_.resolve(process.cwd(),"apps/viewer/dist")];for(let t of n)try{return await Kn(_.join(t,"index.html")),t}catch{}throw new Error("Viewer assets are missing. Run `npm run build` before starting the viewer.")}import Xe from"path";var ha={en:{analyzing:e=>`Analyzing ${e}...`,scanned:e=>`Scanned ${e} files.`,contextSummary:(e,n,t)=>`Read ${e} project documents, ${n} prompt files, and ${t} documented capability hints.`,found:(e,n)=>`Found ${e} code nodes and ${n} relationships.`,compiled:(e,n)=>`Compiled ${e} logic nodes and ${n} flows.`,featureSummary:(e,n,t)=>`Detected ${e} feature circuits (${n} errors, ${t} warnings).`,logicGraph:e=>`Logic graph: ${e}`,rawGraph:e=>`Raw graph: ${e}`,viewer:e=>`Viewer: ${e}`,unexpected:e=>`unexpected positional argument ${e}`,exposed:e=>`Warning: the viewer is exposed on ${e}; its graph may contain source paths and code structure.`,openFailed:e=>`Could not open a browser automatically. Open ${e} manually.`,graphTypeInvalid:"--graph-type must be runtime_logic or product_logic",localeInvalid:"--locale must be auto, zh-CN, or en",semanticProviderInvalid:"--semantic currently supports openai only",semanticModelRequired:"--semantic-model is required when --semantic openai is enabled",semanticApiKeyMissing:"OPENAI_API_KEY is required when --semantic openai is enabled",stop:"Press Ctrl+C to stop.",portInvalid:"--port must be an integer between 1 and 65535",positiveInteger:e=>`${e} must be a positive integer`,initCreated:e=>`Created ${e}.`,initCompleted:(e,n)=>`Completed ${e} (added: ${n}).`,initUnchanged:e=>`${e} already has every continuous-map setting; nothing changed.`,initScripts:e=>`Suggested package.json scripts (add them yourself if you want them):
|
|
76
76
|
${e}`,configWarning:e=>`Warning: ${e}`,buildUpdated:(e,n,t)=>`Map updated in ${e} (build ${n}, ${t}ms).`,buildUnchanged:e=>`Map is already current (build ${e}); nothing rewritten.`,buildFailed:e=>`Analysis failed; the last successful map was kept. Reason: ${e}`,changesSummary:(e,n,t,i)=>`Changes: +${e} / -${n} / ~${t} nodes, ${i} features affected.`,watchStarted:e=>`Watching for changes. Map: ${e}`,watchChanges:e=>`${e} file(s) changed; rebuilding...`,reportHint:e=>`Standalone report: ${e}`,githubWorkflowCreated:e=>`Created ${e}.`,githubWorkflowUpdated:e=>`Updated ${e} (it was an unmodified generated file).`,githubWorkflowOverwritten:e=>`Overwrote ${e} as requested by --force; your previous edits to it are gone.`,githubWorkflowUnchanged:e=>`${e} is already current; nothing changed.`,githubWorkflowModified:e=>`${e} exists and has local modifications, so it was NOT touched. Re-run with --force to overwrite it.`,githubNextSteps:`Next: commit agent-runtime-map.config.json and .github/workflows/agent-runtime-map.yml.
|
|
77
77
|
Every push, pull request, and a weekly schedule will then rebuild the map on GitHub:
|
|
78
78
|
the run's Summary shows what changed, and the full map (report.html) is attached as an artifact.`,forceRequiresGithub:"--force is only meaningful together with init --github"},"zh-CN":{analyzing:e=>`\u6B63\u5728\u5206\u6790 ${e}\u2026`,scanned:e=>`\u5DF2\u626B\u63CF ${e} \u4E2A\u4EE3\u7801\u6587\u4EF6\u3002`,contextSummary:(e,n,t)=>`\u5DF2\u8BFB\u53D6 ${e} \u4E2A\u9879\u76EE\u6587\u6863\u3001${n} \u4E2A Prompt \u6587\u4EF6\uFF0C\u5E76\u63D0\u53D6 ${t} \u6761\u529F\u80FD\u7EBF\u7D22\u3002`,found:(e,n)=>`\u53D1\u73B0 ${e} \u4E2A\u4EE3\u7801\u8282\u70B9\u548C ${n} \u6761\u5173\u7CFB\u3002`,compiled:(e,n)=>`\u5DF2\u7F16\u8BD1\u4E3A ${e} \u4E2A\u903B\u8F91\u8282\u70B9\u548C ${n} \u6761\u903B\u8F91\u6D41\u3002`,featureSummary:(e,n,t)=>`\u8BC6\u522B\u5230 ${e} \u4E2A\u529F\u80FD\u7535\u8DEF\uFF08${n} \u4E2A\u9519\u8BEF\uFF0C${t} \u4E2A\u8B66\u544A\uFF09\u3002`,logicGraph:e=>`\u903B\u8F91\u56FE\uFF1A${e}`,rawGraph:e=>`\u539F\u59CB\u4EE3\u7801\u56FE\uFF1A${e}`,viewer:e=>`\u67E5\u770B\u5730\u5740\uFF1A${e}`,unexpected:e=>`\u5B58\u5728\u65E0\u6CD5\u8BC6\u522B\u7684\u4F4D\u7F6E\u53C2\u6570\uFF1A${e}`,exposed:e=>`\u8B66\u544A\uFF1AViewer \u5DF2\u66B4\u9732\u5728 ${e}\uFF1B\u903B\u8F91\u56FE\u53EF\u80FD\u5305\u542B\u6E90\u7801\u8DEF\u5F84\u548C\u4EE3\u7801\u7ED3\u6784\u3002`,openFailed:e=>`\u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668\uFF0C\u8BF7\u624B\u52A8\u8BBF\u95EE ${e}\u3002`,graphTypeInvalid:"--graph-type \u5FC5\u987B\u662F runtime_logic \u6216 product_logic",localeInvalid:"--locale \u5FC5\u987B\u662F auto\u3001zh-CN \u6216 en",semanticProviderInvalid:"--semantic \u5F53\u524D\u53EA\u652F\u6301 openai",semanticModelRequired:"\u542F\u7528 --semantic openai \u65F6\u5FC5\u987B\u63D0\u4F9B --semantic-model",semanticApiKeyMissing:"\u542F\u7528 --semantic openai \u65F6\u5FC5\u987B\u8BBE\u7F6E OPENAI_API_KEY",stop:"\u6309 Ctrl+C \u505C\u6B62\u670D\u52A1\u3002",portInvalid:"--port \u5FC5\u987B\u662F 1 \u5230 65535 \u4E4B\u95F4\u7684\u6574\u6570",positiveInteger:e=>`${e} \u5FC5\u987B\u662F\u6B63\u6574\u6570`,initCreated:e=>`\u5DF2\u521B\u5EFA ${e}\u3002`,initCompleted:(e,n)=>`\u5DF2\u8865\u5168 ${e}\uFF08\u65B0\u589E\uFF1A${n}\uFF09\u3002`,initUnchanged:e=>`${e} \u5DF2\u5305\u542B\u5168\u90E8\u6301\u7EED\u5730\u56FE\u914D\u7F6E\uFF0C\u672A\u505A\u4FEE\u6539\u3002`,initScripts:e=>`\u5EFA\u8BAE\u6DFB\u52A0\u5230 package.json \u7684 scripts\uFF08\u9700\u8981\u8BF7\u81EA\u884C\u6DFB\u52A0\uFF09\uFF1A
|
|
79
79
|
${e}`,configWarning:e=>`\u8B66\u544A\uFF1A${e}`,buildUpdated:(e,n,t)=>`\u5730\u56FE\u5DF2\u66F4\u65B0\uFF1A${e}\uFF08\u6784\u5EFA ${n}\uFF0C\u8017\u65F6 ${t}ms\uFF09\u3002`,buildUnchanged:e=>`\u5730\u56FE\u5DF2\u662F\u6700\u65B0\uFF08\u6784\u5EFA ${e}\uFF09\uFF0C\u672A\u91CD\u5199\u4EFB\u4F55\u6587\u4EF6\u3002`,buildFailed:e=>`\u5206\u6790\u5931\u8D25\uFF0C\u5DF2\u4FDD\u7559\u6700\u540E\u4E00\u6B21\u6210\u529F\u7684\u5730\u56FE\u3002\u539F\u56E0\uFF1A${e}`,changesSummary:(e,n,t,i)=>`\u53D8\u66F4\uFF1A\u8282\u70B9 +${e} / -${n} / ~${t}\uFF0C${i} \u4E2A\u529F\u80FD\u53D7\u5F71\u54CD\u3002`,watchStarted:e=>`\u6B63\u5728\u76D1\u542C\u53D8\u5316\u3002\u5730\u56FE\u76EE\u5F55\uFF1A${e}`,watchChanges:e=>`\u68C0\u6D4B\u5230 ${e} \u4E2A\u6587\u4EF6\u53D8\u5316\uFF0C\u6B63\u5728\u91CD\u65B0\u5206\u6790\u2026`,reportHint:e=>`\u72EC\u7ACB\u62A5\u544A\u9875\uFF1A${e}`,githubWorkflowCreated:e=>`\u5DF2\u521B\u5EFA ${e}\u3002`,githubWorkflowUpdated:e=>`\u5DF2\u66F4\u65B0 ${e}\uFF08\u539F\u6587\u4EF6\u662F\u672A\u7ECF\u4FEE\u6539\u7684\u751F\u6210\u6587\u4EF6\uFF09\u3002`,githubWorkflowOverwritten:e=>`\u5DF2\u6309 --force \u8981\u6C42\u8986\u76D6 ${e}\uFF1B\u4F60\u4E4B\u524D\u5BF9\u5B83\u7684\u4FEE\u6539\u5DF2\u88AB\u4E22\u5F03\u3002`,githubWorkflowUnchanged:e=>`${e} \u5DF2\u662F\u6700\u65B0\uFF0C\u672A\u505A\u4FEE\u6539\u3002`,githubWorkflowModified:e=>`${e} \u5DF2\u5B58\u5728\u4E14\u5305\u542B\u4F60\u7684\u624B\u52A8\u4FEE\u6539\uFF0C\u56E0\u6B64\u6CA1\u6709\u6539\u52A8\u5B83\u3002\u5982\u9700\u8986\u76D6\uFF0C\u8BF7\u4F7F\u7528 --force \u91CD\u65B0\u6267\u884C\u3002`,githubNextSteps:`\u4E0B\u4E00\u6B65\uFF1A\u63D0\u4EA4 agent-runtime-map.config.json \u548C .github/workflows/agent-runtime-map.yml\u3002
|
|
80
80
|
\u4E4B\u540E\u6BCF\u6B21 push\u3001Pull Request \u4EE5\u53CA\u6BCF\u5468\u4E00\u6B21\u7684\u5B9A\u65F6\u4EFB\u52A1\u90FD\u4F1A\u5728 GitHub \u4E0A\u81EA\u52A8\u91CD\u5EFA\u5730\u56FE\uFF1A
|
|
81
|
-
\u8FD0\u884C\u7684 Summary \u4F1A\u663E\u793A\u53D8\u66F4\u6458\u8981\uFF0C\u5B8C\u6574\u5730\u56FE\uFF08report.html\uFF09\u4F1A\u4F5C\u4E3A artifact \u9644\u5728\u8FD0\u884C\u7ED3\u679C\u91CC\u3002`,forceRequiresGithub:"--force \u53EA\u80FD\u4E0E init --github \u4E00\u8D77\u4F7F\u7528"}};function
|
|
81
|
+
\u8FD0\u884C\u7684 Summary \u4F1A\u663E\u793A\u53D8\u66F4\u6458\u8981\uFF0C\u5B8C\u6574\u5730\u56FE\uFF08report.html\uFF09\u4F1A\u4F5C\u4E3A artifact \u9644\u5728\u8FD0\u884C\u7ED3\u679C\u91CC\u3002`,forceRequiresGithub:"--force \u53EA\u80FD\u4E0E init --github \u4E00\u8D77\u4F7F\u7528"}};function Un(e){return ha[e]}function Bn(e){let n=e.find(i=>i.startsWith("--locale="));if(n)return n.slice(9);let t=e.indexOf("--locale");return t>=0?e[t+1]:void 0}function Wn(e){return e===void 0?!0:["auto","zh","zh-cn","en","en-us"].includes(e.toLowerCase())}function At(e,n=process.env){let t=wa(e);return t||([n.LC_ALL,n.LC_MESSAGES,n.LANG,Intl.DateTimeFormat().resolvedOptions().locale].filter(Boolean).join(" ").toLowerCase().includes("zh")?"zh-CN":"en")}function Ye(e,n){if(!n||n.toLowerCase()==="auto")return e;let t=At(n),i=new URL(e);return i.searchParams.set("locale",t),i.toString()}function Tt(e,n){return e==="zh-CN"?`Agent Runtime Map ${n}
|
|
82
82
|
|
|
83
83
|
\u5C06\u4EE3\u7801\u9879\u76EE\u8F6C\u6362\u6210\u4E00\u5F20\u6709\u6E90\u7801\u8BC1\u636E\u3001\u53EF\u9010\u6B65\u68C0\u67E5\u7684 Agent \u529F\u80FD\u7535\u8DEF\u56FE\u3002
|
|
84
84
|
|
|
@@ -150,46 +150,46 @@ Options:
|
|
|
150
150
|
--debug Print stack traces for failures
|
|
151
151
|
-h, --help Show help
|
|
152
152
|
-v, --version Show version
|
|
153
|
-
`}function
|
|
153
|
+
`}function wa(e){if(!(!e||e.toLowerCase()==="auto"))return e.toLowerCase().startsWith("zh")?"zh-CN":e.toLowerCase().startsWith("en")?"en":void 0}async function Jn(e,n,t={}){let i=await In(e);i.created?process.stdout.write(`${n.initCreated(i.configFile)}
|
|
154
154
|
`):i.addedKeys.length?process.stdout.write(`${n.initCompleted(i.configFile,i.addedKeys.join(", "))}
|
|
155
155
|
`):process.stdout.write(`${n.initUnchanged(i.configFile)}
|
|
156
|
-
`);let r=Object.entries(i.suggestedScripts).map(([s
|
|
156
|
+
`);let r=Object.entries(i.suggestedScripts).map(([o,s])=>` "${o}": "${s}"`).join(`
|
|
157
157
|
`);if(process.stdout.write(`${n.initScripts(r)}
|
|
158
|
-
`),!t.github)return 0;try{let
|
|
158
|
+
`),!t.github)return 0;try{let o=await On(e,{force:t.force}),s=o.outcome==="created"?n.githubWorkflowCreated(o.workflowFile):o.outcome==="unchanged"?n.githubWorkflowUnchanged(o.workflowFile):o.outcome==="overwritten"?n.githubWorkflowOverwritten(o.workflowFile):n.githubWorkflowUpdated(o.workflowFile);return process.stdout.write(`${s}
|
|
159
159
|
${n.githubNextSteps}
|
|
160
|
-
`),0}catch(
|
|
161
|
-
`),1;throw
|
|
162
|
-
`).map(
|
|
163
|
-
`);let
|
|
164
|
-
`),
|
|
165
|
-
`);let
|
|
166
|
-
`),onBuild:
|
|
167
|
-
`);let c=await
|
|
160
|
+
`),0}catch(o){if(o instanceof be)return process.stderr.write(`${n.githubWorkflowModified(o.workflowFile)}
|
|
161
|
+
`),1;throw o}}function ya(e=process.env){let n=e.AGENT_RUNTIME_MAP_COMMIT_SHA?.trim(),t=e.AGENT_RUNTIME_MAP_REF?.trim(),i=e.AGENT_RUNTIME_MAP_BASELINE_RESTORED?.trim(),r=e.AGENT_RUNTIME_MAP_TRIGGER?.split(`
|
|
162
|
+
`).map(o=>o.trim()).filter(Boolean);return{source:n||t||i!==void 0?{commitSha:n||void 0,ref:t||void 0,baselineRestored:i===void 0?void 0:i==="true"}:void 0,trigger:r?.length?r:void 0}}async function Yn(e,n,t){let{config:i,warning:r}=await Lt(e);r&&process.stderr.write(`${t.configWarning(r)}
|
|
163
|
+
`);let o=process.env.AGENT_RUNTIME_MAP_SIMULATE_FAILURE,s=await He(e,i,{...ya(),analyzeOptions:n.analyzeOptions,toolVersion:n.toolVersion,viewerAssetsDir:await Je().catch(()=>{}),analyze:o?async()=>{throw new Error(`Simulated analysis failure: ${o}`)}:void 0});return Zn(s,t),s.ok&&!s.unchanged&&process.stdout.write(`${t.reportHint(Xe.join(s.currentDir,"report.html"))}
|
|
164
|
+
`),s.ok?0:1}async function Xn(e,n,t){let{config:i,warning:r}=await Lt(e);r&&process.stderr.write(`${t.configWarning(r)}
|
|
165
|
+
`);let o=[],s=u=>{u.ok&&u.graph&&(o=Ca(u.graph)),Zn(u,t)},{handle:a,initial:d}=await Dn(e,i,{analyzeOptions:n.analyzeOptions,toolVersion:n.toolVersion,viewerAssetsDir:await Je().catch(()=>{}),onChangesDetected:u=>process.stdout.write(`${t.watchChanges(u.length)}
|
|
166
|
+
`),onBuild:s});d.ok||process.stdout.write(`${t.watchStarted(d.currentDir)}
|
|
167
|
+
`);let c=await Be({graphFile:Xe.join(d.currentDir,"graph.json"),rawGraphFile:Xe.join(d.currentDir,"raw-graph.json"),currentDir:d.currentDir,projectRoot:Xe.resolve(e),sourceFiles:()=>o,host:n.host,port:n.port}),g=Ye(c.url,n.localeParam);return process.stdout.write(`${t.watchStarted(d.currentDir)}
|
|
168
168
|
${t.viewer(g)}
|
|
169
169
|
${t.stop}
|
|
170
|
-
`),n.open!==!1&&!
|
|
171
|
-
`),await new Promise(
|
|
170
|
+
`),n.open!==!1&&!We(g)&&process.stdout.write(`${t.openFailed(g)}
|
|
171
|
+
`),await new Promise(u=>{let m=!1,h=()=>{m||(m=!0,a.close().then(()=>c.close()).then(u,u))};process.once("SIGINT",h),process.once("SIGTERM",h)}),0}function Zn(e,n){if(!e.ok){process.stderr.write(`${n.buildFailed(e.error??"unknown")}
|
|
172
172
|
`);return}if(e.unchanged){process.stdout.write(`${n.buildUnchanged(e.buildId??"")}
|
|
173
173
|
`);return}process.stdout.write(`${n.buildUpdated(e.currentDir,e.buildId??"",e.durationMs)}
|
|
174
174
|
`),e.changes&&!e.changes.initial&&process.stdout.write(`${n.changesSummary(e.changes.nodes.added.length,e.changes.nodes.removed.length,e.changes.nodes.modified.length,e.changes.affectedFeatures.length)}
|
|
175
|
-
`)}function
|
|
175
|
+
`)}function Ca(e){return[...new Set([...e.nodes.flatMap(n=>n.sources.map(t=>t.file)),...e.nodes.flatMap(n=>n.product?.sources.map(t=>t.file)??[]),...e.features.flatMap(n=>n.product?.sources.map(t=>t.file)??[])])]}var Ze="0.8.2";async function Na(e=process.argv.slice(2)){let n=Bn(e),t=At(n),i=Un(t),r;try{r=ba({args:e,allowPositionals:!0,strict:!0,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"},out:{type:"string",short:"o"},"raw-out":{type:"string"},"no-raw":{type:"boolean"},"max-files":{type:"string"},"max-context-files":{type:"string"},"max-context-bytes":{type:"string"},"no-context":{type:"boolean"},"max-nodes":{type:"string"},"graph-type":{type:"string"},description:{type:"string"},semantic:{type:"string"},"semantic-model":{type:"string"},"semantic-base-url":{type:"string"},locale:{type:"string"},port:{type:"string",short:"p"},host:{type:"string"},"no-open":{type:"boolean"},github:{type:"boolean"},force:{type:"boolean"},debug:{type:"boolean"}}})}catch(l){return process.stderr.write(`agent-runtime-map: ${l instanceof Error?l.message:String(l)}
|
|
176
176
|
|
|
177
|
-
${
|
|
178
|
-
`),0;let
|
|
179
|
-
`),1;if(!
|
|
180
|
-
`),1;let
|
|
177
|
+
${Tt(t,Ze)}`),1}if(r.values.help)return process.stdout.write(Tt(t,Ze)),0;if(r.values.version)return process.stdout.write(`${Ze}
|
|
178
|
+
`),0;let o=r.positionals[0],s=new Set(["analyze","serve","init","build","watch"]),a=o!==void 0&&s.has(o)?o:"serve",d=o!==void 0&&s.has(o),c=d?r.positionals[1]??".":o??".",g=d?r.positionals.slice(2):r.positionals.slice(1);if(g.length)return process.stderr.write(`agent-runtime-map: ${i.unexpected(g[0])}
|
|
179
|
+
`),1;if(!Wn(r.values.locale))return process.stderr.write(`agent-runtime-map: ${i.localeInvalid}
|
|
180
|
+
`),1;let u=r.values["graph-type"]??"runtime_logic";if(u!=="runtime_logic"&&u!=="product_logic")return process.stderr.write(`agent-runtime-map: ${i.graphTypeInvalid}
|
|
181
181
|
`),1;let m=r.values.semantic;if(m!==void 0&&m!=="openai")return process.stderr.write(`agent-runtime-map: ${i.semanticProviderInvalid}
|
|
182
182
|
`),1;if(m==="openai"&&!r.values["semantic-model"])return process.stderr.write(`agent-runtime-map: ${i.semanticModelRequired}
|
|
183
183
|
`),1;if(m==="openai"&&!process.env.OPENAI_API_KEY)return process.stderr.write(`agent-runtime-map: ${i.semanticApiKeyMissing}
|
|
184
|
-
`),1;let h={maxFiles:
|
|
184
|
+
`),1;let h={maxFiles:Qe(r.values["max-files"],"--max-files",i),maxContextFiles:Qe(r.values["max-context-files"],"--max-context-files",i),maxContextBytes:Qe(r.values["max-context-bytes"],"--max-context-bytes",i),readContext:!r.values["no-context"],maxNodes:Qe(r.values["max-nodes"],"--max-nodes",i),graphType:u,productDescription:r.values.description,semantic:m==="openai"?{apiKey:process.env.OPENAI_API_KEY,model:r.values["semantic-model"],baseUrl:r.values["semantic-base-url"]}:void 0};if(a==="init"||a==="build"||a==="watch")try{if(a==="init")return await Jn(c,i,{github:!!r.values.github,force:!!r.values.force});if(r.values.force||r.values.github)return process.stderr.write(`agent-runtime-map: ${i.forceRequiresGithub}
|
|
185
185
|
`),1;process.stdout.write(`${i.analyzing(c)}
|
|
186
|
-
`);let
|
|
186
|
+
`);let l={analyzeOptions:h,toolVersion:Ze,host:r.values.host??"127.0.0.1",port:Qn(r.values.port,i),open:!r.values["no-open"],localeParam:r.values.locale};return a==="build"?await Yn(c,l,i):await Xn(c,l,i)}catch(l){let f=l instanceof Error?r.values.debug?l.stack??l.message:l.message:String(l);return process.stderr.write(`agent-runtime-map: ${f}
|
|
187
187
|
`),1}try{process.stdout.write(`${i.analyzing(c)}
|
|
188
|
-
`);let
|
|
188
|
+
`);let l=await Ke(c,{...h,outputFile:r.values.out,rawOutputFile:r.values["no-raw"]?!1:r.values["raw-out"]});if(process.stdout.write([i.scanned(l.rawGraph.project.filesScanned),l.rawGraph.context?i.contextSummary(l.rawGraph.context.documents.length,l.rawGraph.context.prompts.length,l.rawGraph.context.capabilityHints.length):void 0,i.found(l.rawGraph.nodes.length,l.rawGraph.edges.length),i.compiled(l.graph.nodes.length,l.graph.edges.length),i.featureSummary(l.graph.features.length,l.graph.features.filter(C=>C.health==="error").length,l.graph.features.filter(C=>C.health==="warning").length),l.outputFile?i.logicGraph(l.outputFile):void 0,l.rawOutputFile?i.rawGraph(l.rawOutputFile):void 0].filter(Boolean).join(`
|
|
189
189
|
`)+`
|
|
190
|
-
`),a==="analyze")return 0;let
|
|
190
|
+
`),a==="analyze")return 0;let f=r.values.host??"127.0.0.1",w=Qn(r.values.port,i),y=await Be({graphFile:l.outputFile,rawGraphFile:l.rawOutputFile,projectRoot:l.rawGraph.project.root,sourceFiles:[...new Set([...l.graph.nodes.flatMap(C=>C.sources.map(b=>b.file)),...l.graph.nodes.flatMap(C=>C.product?.sources.map(b=>b.file)??[]),...l.graph.features.flatMap(C=>C.product?.sources.map(b=>b.file)??[])])],host:f,port:w}),N=Ye(y.url,r.values.locale);return process.stdout.write(`${i.viewer(N)}
|
|
191
191
|
${i.stop}
|
|
192
|
-
`),
|
|
193
|
-
`),!r.values["no-open"]&&!
|
|
194
|
-
`),await
|
|
195
|
-
`),1}}function
|
|
192
|
+
`),f!=="127.0.0.1"&&f!=="localhost"&&f!=="::1"&&process.stdout.write(`${i.exposed(f)}
|
|
193
|
+
`),!r.values["no-open"]&&!We(N)&&process.stdout.write(`${i.openFailed(N)}
|
|
194
|
+
`),await xa(y.close),0}catch(l){let f=l instanceof Error?r.values.debug?l.stack??l.message:l.message:String(l);return process.stderr.write(`agent-runtime-map: ${f}
|
|
195
|
+
`),1}}function Qn(e,n){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new Error(n.portInvalid);return t}async function xa(e){await new Promise(n=>{let t=!1,i=()=>{t||(t=!0,e().then(n,n))};process.once("SIGINT",i),process.once("SIGTERM",i)})}function Qe(e,n,t){if(e===void 0)return;let i=Number(e);if(!Number.isInteger(i)||i<=0)throw new Error(t.positiveInteger(n));return i}process.exitCode=await Na();export{Na as run};
|