workspai 0.75.2 → 0.77.0

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.
Files changed (118) hide show
  1. package/README.md +2 -2
  2. package/contracts/agent-framework-capabilities.v1.json +2 -2
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +12 -0
  4. package/contracts/create-planner-capabilities.v1.json +48 -0
  5. package/contracts/extension-cli-compatibility.v1.json +4 -2
  6. package/contracts/published-contract-catalog.v1.json +10 -0
  7. package/contracts/runtime-command-surface.v1.json +5 -1
  8. package/contracts/workspace-intelligence/agent-framework-admission-candidate.v2.json +217 -0
  9. package/contracts/workspace-intelligence/agent-framework-conformance-report.v2.json +274 -0
  10. package/contracts/workspace-intelligence/workspace-model.v1.json +4 -0
  11. package/contracts/workspace-intelligence-architecture.v1.json +7 -3
  12. package/dist/analyze-TJM66CPF.js +1 -0
  13. package/dist/autopilot-release-C7Q4OTPY.js +1 -0
  14. package/dist/capabilities-command-TIBIKWPK.js +1 -0
  15. package/dist/{chunk-K52IQX3J.js → chunk-223SWPTL.js} +1 -1
  16. package/dist/chunk-3EMAC3MF.js +4 -0
  17. package/dist/{chunk-GDOO2YZW.js → chunk-3EPR3D5Q.js} +1 -1
  18. package/dist/chunk-3SQIV3F4.js +1 -0
  19. package/dist/{chunk-ZI54C2AO.js → chunk-475GQJ2D.js} +1 -1
  20. package/dist/{chunk-P36TACKN.js → chunk-47UR6ZH4.js} +1 -1
  21. package/dist/{chunk-VHMDWRDG.js → chunk-4BPZJR4Z.js} +4 -4
  22. package/dist/{chunk-VWBWDDU2.js → chunk-4CXV3PPV.js} +1 -1
  23. package/dist/chunk-4ZUBPFSO.js +6 -0
  24. package/dist/chunk-5KXOV7W4.js +1 -0
  25. package/dist/chunk-6BO4QHKA.js +1 -0
  26. package/dist/{chunk-OA2YJN22.js → chunk-DWDYLKVW.js} +1 -1
  27. package/dist/{chunk-KDVNRNDU.js → chunk-DWKCFHHL.js} +1 -1
  28. package/dist/{chunk-EP7SUMAX.js → chunk-E7WJ2QX7.js} +1 -1
  29. package/dist/{chunk-FNVWDXK2.js → chunk-GLBFY7AB.js} +5 -5
  30. package/dist/{chunk-ZGVODK5C.js → chunk-HRVHQBTA.js} +1 -1
  31. package/dist/{chunk-WHBKKJ7L.js → chunk-IAXRGH4Q.js} +1 -1
  32. package/dist/chunk-IDETNYCF.js +1 -0
  33. package/dist/chunk-IHWS3ALP.js +2 -0
  34. package/dist/{chunk-FZWLWFR4.js → chunk-J2MPBSQJ.js} +1 -1
  35. package/dist/{chunk-PFAGXI3G.js → chunk-JVZA35OL.js} +1 -1
  36. package/dist/chunk-LUPKDFQ3.js +7 -0
  37. package/dist/chunk-N7DOKE7V.js +2 -0
  38. package/dist/chunk-O3TVVQ6X.js +6 -0
  39. package/dist/chunk-P5LI5DL3.js +1 -0
  40. package/dist/{chunk-4JXJRIJM.js → chunk-QCX6BO2M.js} +1 -1
  41. package/dist/chunk-SC43A6LH.js +97 -0
  42. package/dist/chunk-SEZTSMRR.js +1 -0
  43. package/dist/{chunk-COOVCORC.js → chunk-SVO2GGTV.js} +1 -1
  44. package/dist/{chunk-5K4O3TAW.js → chunk-TGNPMOM6.js} +1 -1
  45. package/dist/chunk-UNEK3VVR.js +2684 -0
  46. package/dist/{chunk-IKBE3HOH.js → chunk-UP3UWAJV.js} +1 -1
  47. package/dist/{chunk-LFY7KTPD.js → chunk-UTIK3K3M.js} +1 -1
  48. package/dist/{chunk-WXUCAVFT.js → chunk-V6HVDVKJ.js} +8 -8
  49. package/dist/chunk-WC2K5QFI.js +10 -0
  50. package/dist/{chunk-DTNOF3MP.js → chunk-X5XFT5UZ.js} +1 -1
  51. package/dist/{chunk-ADHX7D3F.js → chunk-ZIWWE4BQ.js} +1 -1
  52. package/dist/{create-ZFSFWAW3.js → create-YPAZJYCE.js} +1 -1
  53. package/dist/{doctor-4KL4XUCS.js → doctor-W5PXJ5FL.js} +1 -1
  54. package/dist/{goal-lifecycle-EXQZD7IA.js → goal-lifecycle-5R55CA7H.js} +1 -1
  55. package/dist/{goal-pack-DKJU2DEP.js → goal-pack-IS6GGJPH.js} +1 -1
  56. package/dist/index.d.ts +12 -6
  57. package/dist/index.js +181 -171
  58. package/dist/{pipeline-4GVAOCEN.js → pipeline-LW3SW2WT.js} +1 -1
  59. package/dist/platform-capabilities-RWOWND5Q.js +1 -0
  60. package/dist/{project-agent-entry-7QKNEEXP.js → project-agent-entry-5TYKK5IV.js} +1 -1
  61. package/dist/{project-intelligence-lens-IHRYCLNU.js → project-intelligence-lens-TEOSTKNU.js} +1 -1
  62. package/dist/{project-test-coverage-3P5FH6E5.js → project-test-coverage-T4TIWGKN.js} +1 -1
  63. package/dist/proof-carrying-change-2TKRADCW.js +1 -0
  64. package/dist/{pythonRapidkitExec-UMFLDIYR.js → pythonRapidkitExec-S35OEIEF.js} +1 -1
  65. package/dist/{verified-goal-XI4RQESU.js → verified-goal-RN4TOV34.js} +1 -1
  66. package/dist/{workspace-EYXAKMVI.js → workspace-A33YMF2N.js} +1 -1
  67. package/dist/{workspace-agent-sync-SN55KT6N.js → workspace-agent-sync-VCA4G4DT.js} +1 -1
  68. package/dist/{workspace-context-PW6ESEHH.js → workspace-context-YBWLSKR6.js} +1 -1
  69. package/dist/{workspace-contract-FPLFL4G3.js → workspace-contract-3QUZDBMM.js} +1 -1
  70. package/dist/{workspace-explain-TVQ5IF5D.js → workspace-explain-NXYRAQFI.js} +1 -1
  71. package/dist/{workspace-foundation-DWIJPZRH.js → workspace-foundation-DZ52PECX.js} +1 -1
  72. package/dist/{workspace-graph-stream-RUTNWLQB.js → workspace-graph-stream-4VT46HZ7.js} +1 -1
  73. package/dist/{workspace-intelligence-4CA2CSPZ.js → workspace-intelligence-FKYQQDJ6.js} +1 -1
  74. package/dist/{workspace-intelligence-runner-VM5SXXAT.js → workspace-intelligence-runner-3K2JZH6Q.js} +1 -1
  75. package/dist/{workspace-knowledge-graph-JXN2ZOAF.js → workspace-knowledge-graph-CPBKNXQI.js} +1 -1
  76. package/dist/workspace-knowledge-graph-snapshot-67XDXUOT.js +1 -0
  77. package/dist/{workspace-mcp-serve-4WN4CSD7.js → workspace-mcp-serve-UXPKX7K6.js} +1 -1
  78. package/dist/{workspace-model-D4IECQML.js → workspace-model-POCPMNRT.js} +1 -1
  79. package/dist/{workspace-onboarding-6XWDKLM5.js → workspace-onboarding-KLG3GG7S.js} +1 -1
  80. package/dist/{workspace-registry-summary-Y3ET36NH.js → workspace-registry-summary-M4WMFDQ4.js} +1 -1
  81. package/dist/{workspace-repair-engine-HBUXRHDY.js → workspace-repair-engine-2VGN42QD.js} +1 -1
  82. package/dist/workspace-run-5YQR7GEZ.js +1 -0
  83. package/dist/{workspace-verify-OOAZ3NMZ.js → workspace-verify-PLAKTF3J.js} +1 -1
  84. package/dist/{workspace-watch-BNM5B6HU.js → workspace-watch-VNU4KVYN.js} +1 -1
  85. package/docs/README.md +4 -2
  86. package/docs/agent-framework-adapters.md +168 -39
  87. package/docs/ci-workflows.md +40 -22
  88. package/docs/commands-reference.md +19 -8
  89. package/docs/create-planner-capabilities.md +1 -0
  90. package/docs/creating-workspaces-and-projects.md +28 -9
  91. package/docs/doctor-command.md +9 -4
  92. package/docs/model-gateways.md +204 -0
  93. package/docs/native-kit-baselines.md +4 -2
  94. package/docs/workspace-run.md +3 -1
  95. package/package.json +5 -1
  96. package/scripts/enterprise-package-smoke.mjs +200 -5
  97. package/dist/analyze-6UEBC5OJ.js +0 -1
  98. package/dist/autopilot-release-H5TO6NYY.js +0 -1
  99. package/dist/capabilities-command-VK3LQLP2.js +0 -1
  100. package/dist/chunk-3N27P3KO.js +0 -7
  101. package/dist/chunk-3RNWBFRP.js +0 -4
  102. package/dist/chunk-66O62XNJ.js +0 -97
  103. package/dist/chunk-7NKM6EHE.js +0 -7
  104. package/dist/chunk-BR6QIYQS.js +0 -1
  105. package/dist/chunk-DFREJHG7.js +0 -1
  106. package/dist/chunk-E42IFQFR.js +0 -6
  107. package/dist/chunk-EWD6QTAM.js +0 -2
  108. package/dist/chunk-G5UCEXP6.js +0 -1
  109. package/dist/chunk-JKAAKE4Z.js +0 -6
  110. package/dist/chunk-LARREYZN.js +0 -1
  111. package/dist/chunk-RGNCL5OB.js +0 -1
  112. package/dist/chunk-SZHRPELL.js +0 -1
  113. package/dist/chunk-VXFIMEC6.js +0 -2
  114. package/dist/chunk-X7OI24LO.js +0 -418
  115. package/dist/platform-capabilities-DB4BZPTD.js +0 -1
  116. package/dist/proof-carrying-change-O37XUPIZ.js +0 -1
  117. package/dist/workspace-knowledge-graph-snapshot-KBNUXA64.js +0 -1
  118. package/dist/workspace-run-VN7KV4BU.js +0 -1
@@ -0,0 +1,6 @@
1
+ import {a}from'./chunk-NS53IPAC.js';import {a as a$1}from'./chunk-SVO2GGTV.js';import {h as h$1}from'./chunk-BLEIUQL6.js';import {s,b,a as a$2,d,c}from'./chunk-ODK4LCEL.js';import pe from'path';import h from'chalk';import {createHash}from'crypto';var F="workspai.doctor-adapter.v1",D=["runtime","dependency","security","configuration","test","quality"];function A(e){return e.trim().toLowerCase().replace(/[^a-z0-9+.#-]+/g,"-")}function ae(e){if(e.contractVersion!==F)throw new Error(`Unsupported Doctor adapter contract: ${e.contractVersion}`);if(!e.id.trim())throw new Error("Doctor adapter id must not be empty.");if(e.runtimeFamilies.length===0)throw new Error(`Doctor adapter ${e.id} must own at least one runtime family.`);if(e.platforms.length===0)throw new Error(`Doctor adapter ${e.id} must declare supported platforms.`);let i=e.domains.map(t=>t.domain);if(i.length!==D.length||new Set(i).size!==D.length||D.some(t=>!i.includes(t)))throw new Error(`Doctor adapter ${e.id} must declare every canonical diagnostic domain exactly once.`);for(let t of e.domains)if(t.level==="unsupported"&&t.limitations.length===0)throw new Error(`Doctor adapter ${e.id} must explain unsupported ${t.domain} coverage.`)}var $=class{#e=new Map;#i=new Map;#t=new Map;register(i){ae(i);let t=A(i.id);if(this.#e.has(t))throw new Error(`Doctor adapter id is already registered: ${i.id}`);let s=[...i.runtimeFamilies,...i.aliases].map(A);for(let c of s){let a=this.#i.get(c);if(a)throw new Error(`Doctor runtime ${c} is already owned by adapter ${a}.`)}for(let c of i.frameworks.map(A)){let a=this.#t.get(c);if(a)throw new Error(`Doctor framework ${c} is already owned by adapter ${a}.`)}let r=structuredClone(i);this.#e.set(t,r);for(let c of s)this.#i.set(c,t);for(let c of i.frameworks.map(A))this.#t.set(c,t);return this}resolveWithDiagnostics(i){let t=i.runtimeFamily?this.#i.get(A(i.runtimeFamily)):void 0,s=i.framework?this.#t.get(A(i.framework)):void 0;if(t&&s&&t!==s)return {status:"conflict",descriptor:null,runtimeOwner:t,frameworkOwner:s};let r=t??s;return {status:r?"matched":"unresolved",descriptor:r?structuredClone(this.#e.get(r)??null):null,...t?{runtimeOwner:t}:{},...s?{frameworkOwner:s}:{}}}resolve(i){return this.resolveWithDiagnostics(i).descriptor}list(){return [...this.#e.values()].map(i=>structuredClone(i)).sort((i,t)=>i.id.localeCompare(t.id))}};var Y=[...D],W=["linux","darwin","win32"],re=[{id:"node",aliases:["nodejs","javascript","typescript"],frameworks:["NestJS","Next.js","Remix","Nuxt","React","Vue","Angular","SvelteKit","Svelte","Vite","Astro","Solid","Express","Fastify","Koa","Electron","VS Code Extension"],tier:"first-class",native:Y},{id:"python",aliases:["py"],frameworks:["FastAPI","Django","Flask","Python"],tier:"first-class",native:Y},{id:"go",aliases:["golang"],frameworks:["Go","Go/Fiber","Go/Gin","Echo"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"java",aliases:["jvm"],frameworks:["Java","Spring Boot"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"dotnet",aliases:[".net","csharp","c#"],frameworks:["ASP.NET"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"rust",aliases:["cargo"],frameworks:["Rust","Axum"],tier:"first-class",native:["runtime","dependency","test","quality"],portable:["security","configuration"]},{id:"php",aliases:["composer"],frameworks:["PHP","Laravel"],tier:"first-class",native:["runtime","dependency","security"],portable:["configuration","test","quality"]},{id:"ruby",aliases:["bundler"],frameworks:["Ruby","Ruby on Rails"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"elixir",aliases:["beam"],frameworks:["Elixir","Phoenix"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"clojure",frameworks:["Clojure"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"deno",frameworks:["Deno"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"bun",frameworks:["Bun"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"scala",frameworks:["Scala"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"kotlin",frameworks:["Kotlin"],tier:"extended",portable:["runtime","dependency","configuration","test","quality"],observable:["security"]},{id:"c",aliases:["c-lang"],frameworks:["C"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]},{id:"cpp",aliases:["c++","cplusplus"],frameworks:["C++"],tier:"extended",portable:["runtime","dependency","test","quality"],observable:["configuration"],limitations:["Security diagnosis requires a declared native scanner or workspace adapter."]}];function oe(e,i){let t={runtime:["project markers","entrypoints","toolchain evidence"],dependency:["dependency manifests","lockfiles","installed-tree evidence"],security:["runtime-native audit","advisory evidence"],configuration:["environment contracts","deployment/container markers"],test:["test scripts","test configuration","coverage evidence"],quality:["lint/format/static-analysis contracts"]};return [`${e} adapter`,...t[i]]}function ce(e,i){return e.native?.includes(i)?"native":e.portable?.includes(i)?"portable":e.observable?.includes(i)?"observable":"unsupported"}function le(e){let i=D.map(t=>{let s=ce(e,t);return {domain:t,level:s,evidenceSources:s==="unsupported"?[]:oe(e.id,t),limitations:s==="unsupported"?[`${e.id} has no built-in ${t} provider; declare a workspace adapter.`]:s==="observable"?[`${t} evidence is observable but not runtime-native for ${e.id}.`]:[]}});return {contractVersion:F,id:`builtin.${e.id}`,runtimeFamilies:[e.id],aliases:e.aliases??[],frameworks:e.frameworks,projectKinds:["backend","frontend","desktop","extension","agent","gateway","fullstack","generic"],tier:e.tier,platforms:[...W],domains:i,repairModes:["typed-operation","structured-invocation","manual-guidance"],source:"builtin",limitations:e.limitations??[]}}function de(){return {contractVersion:F,id:"builtin.unknown",runtimeFamilies:["unknown"],aliases:["generic","unrecognized"],frameworks:["Unknown"],projectKinds:["backend","frontend","desktop","extension","agent","gateway","fullstack","generic"],tier:"fallback",platforms:[...W],domains:D.map(e=>({domain:e,level:e==="security"?"unsupported":"observable",evidenceSources:e==="security"?[]:["portable workspace markers","declared custom checks"],limitations:[e==="security"?"No safe security claim is possible without a runtime-native audit provider.":`Only portable ${e} evidence is available until a runtime adapter is registered.`]})),repairModes:["manual-guidance"],source:"builtin",limitations:["Unknown runtimes are fail-closed: missing domain evidence is reported as unknown, never healthy.","Automatic repair is unavailable until a typed adapter owns the runtime."]}}function P(){let e=new $;for(let i of re)e.register(le(i));return e.register(de()),e}function J(e,i=P()){let t=i.resolveWithDiagnostics(e),s=t.descriptor??i.resolve({runtimeFamily:"unknown"});if(!s)throw new Error("Doctor fallback adapter is not registered.");let r=c=>s.domains.filter(a=>a.level===c).map(a=>a.domain);return {registryVersion:b,adapterId:s.id,runtimeFamily:s.runtimeFamilies[0]??"unknown",tier:s.tier,confidence:s.tier==="first-class"?"high":s.tier==="extended"?"medium":"low",nativeDomains:r("native"),portableDomains:r("portable"),observableDomains:r("observable"),unsupportedDomains:r("unsupported"),limitations:[...t.status==="conflict"?[`Runtime/framework ownership conflict (${t.runtimeOwner} vs ${t.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`]:[],...s.limitations,...s.domains.flatMap(c=>c.limitations)]}}function K(e={}){let i=P(),t=i.list(),s=i.resolveWithDiagnostics({runtimeFamily:e.runtime,framework:e.framework}),r=e.runtime||e.framework?[s.descriptor]:t;if((e.runtime||e.framework)&&!r[0]){let a=i.resolve({runtimeFamily:"unknown"});a&&(s.status==="conflict"&&a.limitations.unshift(`Runtime/framework ownership conflict (${s.runtimeOwner} vs ${s.frameworkOwner}); Doctor failed closed instead of selecting an ambiguous adapter.`),r[0]=a);}let c=r.filter(a=>!!a);return {schemaVersion:a$2,registryVersion:b,generatedBy:"workspai",policy:{unknownIsHealthy:false,unsupportedIsHealthy:false,repairRequiresTypedOperation:true,canonicalDomains:[...D]},summary:{adapterCount:c.length,firstClassRuntimes:c.filter(a=>a.tier==="first-class").length,extendedRuntimes:c.filter(a=>a.tier==="extended").length,fallbackRuntimes:c.filter(a=>a.tier==="fallback").length,frameworkCount:new Set(c.flatMap(a=>a.frameworks)).size,platformCount:new Set(c.flatMap(a=>a.platforms)).size},adapters:c}}var me=["runtime","dependency","security","configuration","test","quality"];function I(e){return createHash("sha256").update(e).digest("hex").slice(0,12)}function S(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Q(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function ge(e,i){let t=Q(e);return t?i.some(s=>[s.reason,s.recommendation??""].map(Q).filter(Boolean).some(c=>c===t||c.includes(t)||t.includes(c))):true}function fe(e){return e.status==="fail"?"blocking":e.status==="warn"?"advisory":"informational"}function X(e){return e.issueClass==="dependency"?"dependency":e.issueClass==="security"?"security":e.issueClass==="environment"||e.issueClass==="configuration"||e.issueClass==="container"||e.issueClass==="deployment"||e.issueClass==="workspace-contract"?"configuration":e.issueClass==="test"?"test":e.issueClass==="quality"||e.issueClass==="custom"?"quality":e.issueClass==="runtime"||e.issueClass==="framework"||e.issueClass==="source-tree"?"runtime":null}function ye(e,i){return me.map(t=>{let s=e.filter(o=>X(o)===t),r=e.filter(o=>o.applicability!=="not-applicable"&&X(o)===t),c=i.unsupportedDomains.includes(t);if(r.length===0){let o=s.some(d=>d.applicability==="not-applicable");return {id:t,status:o?"not-applicable":"not-run",observationCount:0,blockingFindings:0,advisoryFindings:0,reason:o?`${t} checks ran and found no declared intent requiring this domain.`:c?`${t} is unsupported by Doctor adapter ${i.adapterId}; no healthy claim is allowed.`:`No ${t} diagnostic observation was produced.`}}let a=r.some(o=>o.freshness?.status==="stale"||o.freshness?.status==="unknown"),p=r.filter(o=>o.status==="fail").length,m=r.filter(o=>o.status==="warn").length,C=p>0||m>0;return {id:t,status:a?"stale":C?"findings":c?"not-run":"clean",observationCount:r.length,blockingFindings:p,advisoryFindings:m,reason:a?`${t} evidence is stale or has unknown freshness.`:C?`${t} diagnostics produced findings.`:c?`${t} observations cannot establish complete health because adapter ${i.adapterId} declares the domain unsupported.`:`${t} diagnostics completed without findings.`}})}function De(e){if(e.status==="pass")return "not-needed";let i=e.repairCapability;return i?i.status==="manual"||i.requiresReview?"manual":i.status!=="available"||!i.canAutoFix?"unavailable":i.requiresApproval?"approval-required":"automatic":"unavailable"}function be(e){if(e.freshness?.status==="stale"||e.freshness?.status==="unknown")return {label:"low",score:.35,state:"unknown"};let i=!!(e.issueClass&&e.issueClass!=="unknown"),t=!!(e.repairCapability?.operation?.type||e.repairCapability?.invocation?.executable);return i&&t&&e.repairIntent?.confidence==="high"?{label:"high",score:.95,state:"confirmed"}:i&&(e.status==="fail"||e.status==="warn")?{label:"medium",score:t?.82:.68,state:"candidate"}:e.status==="pass"?{label:"high",score:.98,state:"confirmed"}:{label:"low",score:.3,state:"unknown"}}function ve(e,i){let t=[{kind:"probe",role:"observation",ref:`probe:${e.id}`,claim:e.reason}];for(let r of e.repairCapability?.files??[])t.push({kind:"file",role:"repair-target",ref:r.split(pe.sep).join("/"),claim:"Structured repair capability declared this path as an affected target."});if(e.repairCapability?.invocation?.executable){let r=e.repairCapability.invocation;t.push({kind:"command",role:"verification",ref:[r.executable,...r.args??[]].join(" "),claim:"Structured command invocation is available for this diagnostic path."});}if(e.issueClass==="security"&&/(?:dependency|audit|vulnerab|security-hygiene)/i.test(`${e.id} ${e.label}`))for(let r of i??[])t.push({kind:"dependency",role:"subject",ref:r.version?`${r.name}@${r.version}`:r.name,claim:r.advisoryIds&&r.advisoryIds.length>0?`Dependency is referenced by ${r.advisoryIds.join(", ")}.`:"Dependency is present in security audit evidence."});return t}function we(e,i){let t=i.issueClass?.trim()||"unknown",s=be(i);return {id:`${S(i.id)}:${I(`${e.projectPath}\0${i.id}`)}`,causalKey:[S(e.projectName),I(e.projectPath),S(t),S(i.id)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:i.id,label:i.label,status:fe(i),severity:i.severity,issueClass:t,operationalImpact:i.operationalImpact?.trim()||"developer-friction",applicability:i.applicability??"applicable",confidence:s.label,confidenceScore:s.score,diagnosisState:s.state,symptom:i.reason,...i.recommendation?{recommendation:i.recommendation}:{},proofs:ve(i,e.dependencySubjects),repair:{disposition:De(i),...i.repairCapability?.id?{capabilityId:i.repairCapability.id}:{},...i.repairCapability?.operation?.type?{operationType:i.repairCapability.operation.type}:{},...i.repairCapability?.verifyCommand?{verifyCommand:i.repairCapability.verifyCommand}:{},requiresFreshEvidence:i.repairIntent?.requiresFreshEvidence===true||i.freshness?.verifyBeforeUse===true}}}function he(e,i,t){let s=`legacy-runtime-issue-${t+1}`;return {id:`${s}:${I(`${e.projectPath}\0${i}`)}`,causalKey:[S(e.projectName),I(e.projectPath),"unknown",I(i)].join(":"),projectName:e.projectName,projectPath:e.projectPath,probeId:s,label:"Runtime diagnostic issue",status:"blocking",severity:"error",issueClass:"unknown",operationalImpact:"runtime-risk",applicability:"applicable",confidence:"low",confidenceScore:.25,diagnosisState:"unknown",symptom:i,proofs:[{kind:"unknown",role:"observation",ref:`legacy-issue:${t+1}`,claim:i}],repair:{disposition:"unavailable",requiresFreshEvidence:true}}}function Z(e){let i=[...e.probes],t=[...new Set((e.runtimeFamilies&&e.runtimeFamilies.length>0?e.runtimeFamilies:[e.runtimeFamily??"unknown"]).filter(Boolean))],s=e.runtimeFamily??t[0]??"unknown",r=t.filter(n=>n!==s&&n!=="unknown"),c=J({runtimeFamily:e.runtimeFamily,framework:e.framework},e.adapterRegistry),a$1=ye(i,c),p=(e.legacyIssues??[]).filter(n=>!ge(n,i)),m=new Map;for(let n of i){let l=m.get(n.id)??new Set;l.add(n.status),m.set(n.id,l);}let C=[...m.entries()].filter(([,n])=>n.size>1).map(([n,l])=>({probeId:n,statuses:[...l].sort(),reason:"The same diagnostic probe produced contradictory states in one project scan."})),o=[...i.filter(n=>n.applicability!=="not-applicable"&&n.status!=="pass").map(n=>we(e,n)),...p.map((n,l)=>he(e,n,l))],d={blocking:4,unknown:3,advisory:2,informational:1},O=new Map;for(let n of o){let l=O.get(n.causalKey)??[];l.push(n),O.set(n.causalKey,l);}let g=[...O.values()].map(n=>{let u=[...n].sort((f,j)=>d[j.status]-d[f.status]||j.confidenceScore-f.confidenceScore||f.id.localeCompare(j.id)).at(0);if(!u)throw new Error("Doctor diagnosis causal group cannot be empty.");let G=structuredClone(u);return G.proofs=[...new Map(n.flatMap(f=>f.proofs).map(f=>[`${f.kind}:${f.role}:${f.ref}:${f.claim}`,f])).values()],G}).sort((n,l)=>n.causalKey.localeCompare(l.causalKey)||n.id.localeCompare(l.id)),k=new Map;for(let n of g){let l=k.get(n.causalKey)??[];l.push(n),k.set(n.causalKey,l);}let b=[...k.entries()].map(([n,l])=>({causalKey:n,issueClass:l[0]?.issueClass??"unknown",status:l.some(u=>u.status==="blocking")?"blocking":l.some(u=>u.status==="advisory")?"advisory":l.some(u=>u.status==="unknown")?"unknown":"informational",findingIds:l.map(u=>u.id),projectPaths:[...new Set(l.map(u=>u.projectPath))],repairable:l.some(u=>u.repair.disposition==="automatic"||u.repair.disposition==="approval-required")})),v=[...g.filter(n=>n.diagnosisState==="unknown"||n.issueClass==="unknown"||n.applicability==="unknown").map(n=>({id:`unknown:${n.id}`,probeId:n.probeId,reason:n.issueClass==="unknown"?"The observation is real, but Doctor cannot yet bind it to a typed issue class.":"Evidence is insufficient or stale for a confirmed diagnosis."})),...a$1.filter(n=>n.status==="not-run"||n.status==="stale").map(n=>({id:`unknown:domain:${n.id}:${I(e.projectPath)}`,reason:n.reason})),...r.map(n=>({id:`unknown:runtime:${S(n)}:${I(e.projectPath)}`,reason:e.projectArchetype==="platform"?`${n} is part of this cross-language platform, but only portable evidence and the primary ${s} runtime adapter were evaluated. Add a typed ${n} adapter before making runtime-specific health claims.`:`${n} was detected inside this composite project boundary, but the ${s} adapter is the only runtime-specific adapter evaluated for this scan. Declare a nested project boundary or a typed Doctor adapter before treating ${n} as healthy.`}))],y=g.filter(n=>n.diagnosisState!=="unknown").length,x=g.length===0?100:y/g.length*100,ie=a$1.filter(n=>n.status!=="not-run"&&n.status!=="stale").length/a$1.length*100,U=t.filter(n=>n!=="unknown").length,te=s!=="unknown"&&t.includes(s)?1:0,ne=U===0?0:te/U*100,se=Math.round(Math.min(x,ie,ne)*100)/100;return {schemaVersion:a,engineVersion:"universal-diagnosis-v1",project:{name:e.projectName,path:e.projectPath,runtimeFamily:e.runtimeFamily??"unknown",runtimeFamilies:t,framework:e.framework??"Unknown",projectKind:e.projectKind??"generic"},capability:c,domains:a$1,coverage:{totalObservations:i.length+p.length,evaluatedObservations:i.filter(n=>n.applicability!=="not-applicable").length,passingObservations:i.filter(n=>n.applicability!=="not-applicable"&&n.status==="pass").length,blockingFindings:g.filter(n=>n.status==="blocking").length,advisoryFindings:g.filter(n=>n.status==="advisory").length,unknownFindings:v.length,repairableFindings:g.filter(n=>n.repair.disposition==="automatic"||n.repair.disposition==="approval-required").length,manualFindings:g.filter(n=>n.repair.disposition==="manual").length,unsupportedFindings:g.filter(n=>n.repair.disposition==="unavailable").length,contradictionCount:C.length,diagnosisCompleteness:se},findings:g,causalGroups:b,unknowns:v,contradictions:C}}function w(e){let i=e.severity??"error",t=e.repair??"unavailable";return {id:e.id,label:e.label,status:i==="error"?"fail":"warn",severity:i,reason:`${e.label} detected by the validation corpus.`,issueClass:e.issueClass,operationalImpact:i==="error"?"release-risk":"ci-risk",repairIntent:{confidence:e.confidence??"medium",requiresFreshEvidence:true},...t==="unavailable"?{}:{repairCapability:{id:`repair.${e.id}`,status:t==="manual"?"manual":"available",canAutoFix:t==="automatic"||t==="approval-required",requiresApproval:t==="approval-required",requiresReview:t==="manual",operation:{type:"validation-operation"},verifyCommand:"npx workspai doctor project --json"}}}}var Ce=[{id:"runtime-missing",diseaseClass:"runtime",description:"Required runtime is absent.",probe:w({id:"runtime-missing",label:"Runtime missing",issueClass:"runtime"}),expected:{finding:true,domain:"runtime",status:"blocking",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"dependencies-missing",diseaseClass:"dependency",description:"Installed dependency tree is absent.",probe:w({id:"dependencies-missing",label:"Dependencies missing",issueClass:"dependency",repair:"automatic",confidence:"high"}),expected:{finding:true,domain:"dependency",status:"blocking",diagnosisState:"confirmed",repairDisposition:"automatic"}},{id:"security-advisory",diseaseClass:"security",description:"A runtime-native audit reports a blocking advisory.",probe:w({id:"security-advisory",label:"Security advisory",issueClass:"security",repair:"approval-required",confidence:"high"}),expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"confirmed",repairDisposition:"approval-required"}},{id:"environment-contract",diseaseClass:"configuration",description:"Environment/configuration contract is incomplete.",probe:w({id:"environment-contract",label:"Environment contract incomplete",issueClass:"environment",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"container-contract",diseaseClass:"configuration",description:"Container delivery contract is incomplete.",probe:w({id:"container-contract",label:"Container contract incomplete",issueClass:"container",severity:"warn"}),expected:{finding:true,domain:"configuration",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"tests-missing",diseaseClass:"test",description:"No deterministic test surface is declared.",probe:w({id:"tests-missing",label:"Tests missing",issueClass:"test",severity:"warn",repair:"manual"}),expected:{finding:true,domain:"test",status:"advisory",diagnosisState:"candidate",repairDisposition:"manual"}},{id:"quality-missing",diseaseClass:"quality",description:"No lint/format/static-analysis surface is declared.",probe:w({id:"quality-missing",label:"Quality tooling missing",issueClass:"quality",severity:"warn"}),expected:{finding:true,domain:"quality",status:"advisory",diagnosisState:"candidate",repairDisposition:"unavailable"}},{id:"stale-evidence",diseaseClass:"freshness",description:"Evidence is stale and must not be treated as confirmed.",probe:{...w({id:"stale-evidence",label:"Stale evidence",issueClass:"security"}),freshness:{status:"stale",verifyBeforeUse:true}},expected:{finding:true,domain:"security",status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"unknown-disease",diseaseClass:"unknown",description:"A real symptom cannot be bound to a typed disease class.",probe:w({id:"unknown-disease",label:"Unknown disease",issueClass:"unknown"}),expected:{finding:true,status:"blocking",diagnosisState:"unknown",repairDisposition:"unavailable"}},{id:"healthy-runtime",diseaseClass:"healthy-control",description:"Healthy evidence must not become a finding.",probe:{id:"healthy-runtime",label:"Healthy runtime",status:"pass",severity:"info",reason:"Runtime evidence is healthy.",issueClass:"runtime",operationalImpact:"none"},expected:{finding:false,domain:"runtime"}}];function _(e){return Math.round(e*1e4)/1e4}function ee(){let i=P().list(),t=i.flatMap(o=>Ce.map(d=>{let O=o.runtimeFamilies[0]??"unknown",g=o.frameworks[0]??"Unknown",k=Z({projectName:`validation-${o.id}-${d.id}`,projectPath:`/virtual/doctor-validation/${o.id}/${d.id}`,runtimeFamily:O,framework:g,projectKind:"generic",probes:[d.probe]}),b=k.findings.find(x=>x.probeId===d.probe.id),N=k.domains.find(x=>x.observationCount>0)?.id,v={finding:!!b,...N?{domain:N}:{},...b?.status?{status:b.status}:{},...b?.diagnosisState?{diagnosisState:b.diagnosisState}:{},...b?.repair.disposition?{repairDisposition:b.repair.disposition}:{}},y=[];return v.finding!==d.expected.finding&&y.push("finding-presence"),d.expected.domain&&v.domain!==d.expected.domain&&y.push("domain"),d.expected.status&&v.status!==d.expected.status&&y.push("status"),d.expected.diagnosisState&&v.diagnosisState!==d.expected.diagnosisState&&y.push("diagnosis-state"),d.expected.repairDisposition&&v.repairDisposition!==d.expected.repairDisposition&&y.push("repair-disposition"),k.capability.adapterId!==o.id&&y.push("adapter-binding"),{id:`${o.id}:${d.id}`,passed:y.length===0,expected:d.expected,actual:v,failures:y}})),s=t.filter(o=>o.expected.finding),r=t.filter(o=>!o.expected.finding),c$1=s.filter(o=>o.actual.finding).length,a=s.length-c$1,p=r.filter(o=>!o.actual.finding).length,m=r.length-p,C=new Set(t.map(o=>o.actual.domain).filter(o=>!!o));return {schemaVersion:c,corpusVersion:d,capabilityRegistryVersion:b,scope:"synthetic-contract-corpus",summary:{totalCases:t.length,passedCases:t.filter(o=>o.passed).length,failedCases:t.filter(o=>!o.passed).length,truePositives:c$1,trueNegatives:p,falsePositives:m,falseNegatives:a,precision:_(c$1/Math.max(1,c$1+m)),recall:_(c$1/Math.max(1,c$1+a)),domainCoverage:_(C.size/D.length),runtimeAdapterCoverage:_(new Set(t.map(o=>o.id.split(":",1)[0])).size/Math.max(1,i.length)),runtimeAdaptersExercised:i.length,declaredPlatforms:new Set(i.flatMap(o=>o.platforms)).size},cases:t,limitations:["Precision and recall describe the versioned synthetic contract corpus, not every public repository.","Every registered runtime adapter is exercised against the same disease corpus; this proves contract behavior, not tool availability on a host.","Runtime-native fixture and real Linux, macOS, and Windows acceptance gates remain separate evidence surfaces."]}}async function Qe(e={}){let i=K({runtime:e.runtime,framework:e.framework}),t=e.validate?ee():void 0,s$1,r;if(e.write){let a=e.workspace?pe.resolve(e.workspace):a$1(process.cwd());if(!a)return e.json?console.log(JSON.stringify({schemaVersion:i.schemaVersion,status:"error",error:{code:"doctor.capabilities.workspace-not-found",message:"--write requires a Workspai workspace or --workspace <path>."}},null,2)):console.log(h.red("Doctor capabilities could not be written: no workspace found.")),1;let p=K();s$1=await h$1(a,s.doctorCapabilities.artifactPath,p),t&&(r=await h$1(a,s.doctorValidation.artifactPath,t));}let c={...i,...t?{validation:t}:{},...s$1?{artifactPath:s$1}:{},...r?{validationArtifactPath:r}:{}};if(e.json)e.quiet||console.log(JSON.stringify(c,null,2));else if(!e.quiet){console.log(h.bold.cyan(`
2
+ \u{1FA7A} Workspai Doctor capabilities
3
+ `)),console.log(`${i.summary.adapterCount} adapter(s) \xB7 ${i.summary.frameworkCount} framework mapping(s) \xB7 ${i.summary.platformCount} platform(s)`);for(let a of i.adapters){let p=a.domains.map(m=>`${m.domain}:${m.level}`).join(" \xB7 ");console.log(h.bold(`
4
+ ${a.runtimeFamilies.join(", ")} \xB7 ${a.tier}`)),console.log(h.gray(p));for(let m of a.limitations)console.log(h.yellow(` ! ${m}`));}if(t){let a=t.summary,p=a.failedCases===0?h.green:h.red;console.log(p(`
5
+ Validation ${a.passedCases}/${a.totalCases} \xB7 precision ${a.precision} \xB7 recall ${a.recall}`));}s$1&&console.log(h.gray(`
6
+ Capabilities: ${s$1}`)),r&&console.log(h.gray(`Validation: ${r}`));}return t&&t.summary.failedCases>0?1:0}export{Z as a,Qe as b};
@@ -0,0 +1 @@
1
+ import {j,m,e}from'./chunk-LUPKDFQ3.js';import {u}from'./chunk-VQZ5PI5J.js';import {t}from'./chunk-ODK4LCEL.js';import d from'path';import f from'fs-extra';import {parse}from'yaml';import k from'fs';var L=new Set(["backend","desktop","extension","service","frontend","worker","agent","gateway","platform","library","infra","docs","test-suite","unknown"]),O=new Set([".git",".workspai","vendor","node_modules","test","tests","testdata","fixtures","samples","examples","third_party"]),F=new Set([...O,".cache",".venv","build","dist","target"]);async function I(e){let n=0,t=async(o,r)=>{if(r>5)return false;let s;try{s=await f.readdir(o,{withFileTypes:true});}catch{return false}for(let c of s.sort((u,a)=>u.name.localeCompare(a.name))){if(c.isFile()&&c.name==="main.go"){let u=await f.readFile(d.join(o,c.name),"utf8").catch(()=>"");if(/^\s*package\s+main\b/m.test(u)&&(n+=1,n>1))return true}if(c.isDirectory()&&!O.has(c.name)&&await t(d.join(o,c.name),r+1))return true}return false};return t(e,0)}async function M(e,n){if(n!=="c"&&n!=="cpp")return false;let t=new Set,o=async(r,s)=>{if(s>3||t.size>=3)return;let c;try{c=await f.readdir(r,{withFileTypes:true});}catch{return}for(let u of c)if(u.isFile()){let a=u.name.toLowerCase();a==="cmakelists.txt"||a==="meson.build"?t.add("native"):a==="pyproject.toml"||a==="setup.py"?t.add("python"):a==="description"&&d.basename(r).toLowerCase()==="r"?t.add("r"):a.endsWith(".gemspec")?t.add("ruby"):a==="pom.xml"||a==="build.gradle"||a==="build.gradle.kts"?t.add("java"):a==="cargo.toml"?t.add("rust"):a==="go.mod"?t.add("go"):a==="package.json"&&t.add("node");}else u.isDirectory()&&!F.has(u.name)&&await o(d.join(r,u.name),s+1);};return await o(e,0),t.has("native")&&t.size>=3}async function K(e){if((((await f.readFile(d.join(e,"pom.xml"),"utf8").catch(()=>"")).match(/<modules\b[^>]*>([\s\S]*?)<\/modules>/iu)?.[1]??"").match(/<module\b[^>]*>[^<]+<\/module>/giu)??[]).length>=2)return true;for(let o of ["settings.gradle","settings.gradle.kts"]){let r=await f.readFile(d.join(e,o),"utf8").catch(()=>"");if(!r)continue;if(new Set([...r.matchAll(/['"](:[^'"]+)['"]/gu)].map(c=>c[1])).size>=2)return true}return false}async function $(e){for(let n of ["compose.yaml","compose.yml","docker-compose.yaml","docker-compose.yml"]){let t=await f.readFile(d.join(e,n),"utf8").catch(()=>"");if(t)try{let r=parse(t)?.services??{},s=Object.entries(r).map(([i,p])=>{let g=(()=>{if(typeof p?.build=="string")return `${p.build}|Dockerfile`;if(!p?.build||typeof p.build!="object")return null;let l=p.build.context;if(typeof l!="string"||l.length===0)return null;let j="dockerfile"in p.build&&typeof p.build.dockerfile=="string"?p.build.dockerfile:"Dockerfile";return `${l}|${j}`})();return g?{serviceName:i,service:p,identity:g.replaceAll("\\","/").replace(/\/$/,"")}:null}).filter(i=>i!==null);if(new Set(s.map(i=>i.identity)).size<2)continue;let u=new Set(s.map(i=>i.serviceName)),a=new Set(s.filter(({service:i})=>Array.isArray(i.ports)&&i.ports.length>0).map(({identity:i})=>i)),y=s.some(({service:i})=>(Array.isArray(i.depends_on)?i.depends_on:i.depends_on&&typeof i.depends_on=="object"?Object.keys(i.depends_on):[]).some(g=>typeof g=="string"&&u.has(g)));if(a.size>=2||y)return true}catch{}}return false}async function A(e){try{if(!await f.pathExists(e))return null;let n=await f.readJSON(e);return n&&typeof n=="object"?n:null}catch{return null}}async function z(e){for(let n of e){let t=await A(n);if(t)return t}return null}function S(e){if(typeof e!="string")return null;let n=e.trim().toLowerCase();return L.has(n)?n==="service"?"backend":n:null}function re(e){switch(e){case "backend":case "service":case "worker":return "backend";case "agent":return "agent";case "gateway":return "gateway";case "frontend":case "desktop":case "extension":case "library":case "platform":return e;case "infra":return "infrastructure";case "docs":return "documentation";case "test-suite":return "quality";default:return "unknown"}}async function oe(e$1,n,t={}){let o=n??await z(u(e$1,"project.json")),r=j(o)?null:o,s=r===null&&o!==null?m(e$1,null):null,c=S(r?.kind)??S(r?.type);if(c)return c==="worker"&&typeof r?.framework=="string"&&(r.framework.trim().toLowerCase()==="microsoft-agent-framework"||r.framework.trim().toLowerCase()==="openai-agents")?"agent":c;let u$1=typeof r?.kit_name=="string"?r.kit_name:typeof r?.kit=="string"?r.kit:t.kit,a=typeof r?.framework=="string"?r.framework:t.framework??s?.key,y=typeof r?.runtime=="string"?r.runtime:t.runtime??s?.runtime,i=`${typeof u$1=="string"?u$1:""} ${a??""} ${y??""}`.trim().toLowerCase();if(await $(e$1))return "platform";if(/\b(tauri|electron|wails|desktop)\b/.test(i))return "desktop";if(/\b(vscode-extension|visual studio code extension|jetbrains-plugin|browser-extension)\b/.test(i))return "extension";if(typeof u$1=="string"&&u$1.trim().toLowerCase().startsWith("gateway.")||typeof a=="string"&&a.trim().toLowerCase()==="openrouter")return "gateway";let p=await f.readFile(d.join(e$1,"Cargo.toml"),"utf8").catch(()=>""),g=/^\s*\[workspace\]\s*$/m.test(p)&&!/^\s*\[package\]\s*$/m.test(p),l=await A(d.join(e$1,"package.json"));if(l!==null&&(Array.isArray(l.workspaces)||l.workspaces!==null&&typeof l.workspaces=="object")||g||e(e$1))return "platform";if(/\b(frontend|nextjs|next\.js|react|vue|svelte|vite|angular|astro|remix|nuxt)\b/.test(i))return "frontend";if(/\b(fastapi|nestjs|springboot|spring boot|gofiber|gogin|webapi|django|flask|express|fastify|laravel|rails|phoenix|axum|actix|rocket)\b/.test(i))return "backend";if(l){let m={...l.dependencies??{},...l.devDependencies??{}},D=l.scripts??{},b=Object.values(D).filter(w=>typeof w=="string").join(" ").toLowerCase(),_=l.engines??{},N=Array.isArray(l.categories)?l.categories.filter(w=>typeof w=="string"):[];if(m["@tauri-apps/api"]||m["@tauri-apps/cli"]||await f.pathExists(d.join(e$1,"src-tauri","tauri.conf.json"))||await f.pathExists(d.join(e$1,"src-tauri","tauri.conf.json5"))||m.electron||m["@electron-forge/cli"]||b.includes("electron-forge")||b.includes("electron "))return "desktop";if(typeof _.vscode=="string"||N.some(w=>w.toLowerCase()==="extension packs")||l.publisher&&(l.activationEvents||l.contributes))return "extension";if(m.next||m.react||m.vue||m.svelte||m.vite||m["@angular/core"]||b.includes("next ")||b.includes("vite "))return "frontend";if(l.private===true&&!m.express&&!m["@nestjs/core"])return "library"}return g||await K(e$1)||await f.pathExists(d.join(e$1,"go.work"))||await f.pathExists(d.join(e$1,"go.mod"))&&await I(e$1)?"platform":await M(e$1,y)?"library":await f.pathExists(d.join(e$1,"compose.yaml"))||await f.pathExists(d.join(e$1,"compose.yml"))||await f.pathExists(d.join(e$1,"docker-compose.yml"))||await f.pathExists(d.join(e$1,"docker-compose.yaml"))||await f.pathExists(d.join(e$1,"terraform.tf"))?"infra":"backend"}var B={ci:[".github/workflows",".gitlab-ci.yml",".circleci/config.yml","azure-pipelines.yml","bitbucket-pipelines.yml","cloudbuild.yaml","Jenkinsfile",".buildkite/pipeline.yml","prow"],release:[".changeset",".releaserc",".releaserc.json","release.config.js",".goreleaser.yml",".goreleaser.yaml","RELEASING.md","RELEASE.md","tools/release","scripts/release","docs/release","doc/release","build/release.sh","hack/lib/release.sh"],ownership:[".github/CODEOWNERS",".gitlab/CODEOWNERS","CODEOWNERS","docs/CODEOWNERS","OWNERS","OWNERS_ALIASES","MAINTAINERS"]},J=/(?:^|[-_.])(?:release|publish|publishing|distribution)(?:[-_.]|$)/i,V={ci:/\b(?:prow|buildkite|jenkins|teamcity|travis|external ci|test-infra)\b/i,release:/\b(?:release automation|release engineering|release infrastructure|external release)\b/i,ownership:/\b(?:external ownership|central owners|maintainer team|code owners)\b/i};async function U(e,n){let t=[];for(let o of n)try{await k.promises.access(d.join(e,o),k.constants.F_OK),t.push(o);}catch{}return t}async function Y(e,n){let t=["README.md","CONTRIBUTING.md","DEVELOPMENT.md","docs/devel/README.md"],o=[];for(let r of t)try{let s=d.join(e,r),c=await k.promises.stat(s);if(!c.isFile()||c.size>1024*1024)continue;let u=await k.promises.readFile(s,"utf8");n.test(u)&&o.push(r);}catch{}return o}async function q(e){let n=d.join(e,".github","workflows");try{return (await k.promises.readdir(n,{withFileTypes:true})).filter(o=>o.isFile()&&/\.(?:ya?ml)$/i.test(o.name)&&J.test(o.name)).map(o=>`.github/workflows/${o.name}`).sort()}catch{return []}}function H(e,n){let t$1=e?.[n];return t$1?.mode?{status:t$1.mode==="external"?"external-declared":"repository",provider:t$1.provider?.trim()||null,evidence:[t.workspaceContract],reference:t$1.reference?.trim()||null}:null}async function v(e,n,t){let o=H(n,t);if(o)return o;let r=[...await U(e,B[t]),...t==="release"?await q(e):[]];if(r.length>0)return {status:"repository",provider:null,evidence:r,reference:null};let s=await Y(e,V[t]);return s.length>0?{status:"external-observed",provider:null,evidence:s,reference:null}:{status:"unknown",provider:null,evidence:[],reference:null}}async function ue(e){let[n,t,o]=await Promise.all([v(e.projectPath,e.declaration,"ci"),v(e.projectPath,e.declaration,"release"),v(e.projectPath,e.declaration,"ownership")]);return {schemaVersion:"workspai.project-governance.v1",ci:n,release:t,ownership:o}}export{re as a,oe as b,ue as c};
@@ -0,0 +1 @@
1
+ import v from'os';import t from'path';import d from'fs-extra';function j(e=process.platform){return e==="win32"?"windows":e==="linux"?"linux":e==="darwin"?"macos":"other"}function c(e=process.platform){return j(e)==="windows"}function W(e=process.platform){return c(e)}var A=new Set(["npx","npm","yarn","pnpm"]);function N(e){return e==="npx"?"npx-cli.js":"npm-cli.js"}function S(e){return c(e)?t.win32:t.posix}function b(e,n,o){let r=n.npm_execpath;if(!r)return null;let i=S(o),s=i.basename(r).toLowerCase();if(e==="npx"&&s!=="npx-cli.js"){let p=i.join(i.dirname(r),"npx-cli.js");return d.existsSync(p)?p:null}if(e==="npm"&&s==="npx-cli.js"){let p=i.join(i.dirname(r),"npm-cli.js");return d.existsSync(p)?p:null}return d.existsSync(r)?r:null}function E(e,n,o){if(e!=="npm"&&e!=="npx")return [];let r=N(e),i=S(o),s=i.dirname(n),p=i.dirname(s);return [i.join(s,"node_modules","npm","bin",r),i.join(p,"lib","node_modules","npm","bin",r),i.join(p,"lib64","node_modules","npm","bin",r),i.join("/usr","lib","node_modules","npm","bin",r),i.join("/usr","local","lib","node_modules","npm","bin",r),i.join("/usr","share","nodejs","npm","bin",r)]}function B(e,n=process.platform){return k(e,n).command}function k(e,n=process.platform,o=process.env,r=process.execPath){let i=e.trim();if(!A.has(i))return {command:i,prefixArgs:[]};if(i==="npm"||i==="npx"){let l=b(i,o,n);if(l)return {command:r,prefixArgs:[l]};for(let u of E(i,r,n))if(d.existsSync(u))return {command:r,prefixArgs:[u]}}let s=S(n),p=s.dirname(r),a=c(n)?".cmd":"",g=[s.join(p,`${i}${a}`),s.join(p,i)];for(let l of g)if(d.existsSync(l))return {command:l,prefixArgs:[]};return i==="npm"?{command:"corepack",prefixArgs:["npm"]}:{command:i,prefixArgs:[]}}function R(e,n=process.platform,o=process.execPath){let r=c(n)?";":":",i=S(n).dirname(o),s=(e??process.env.PATH??"").split(r).filter(Boolean);return s.includes(i)||s.unshift(i),s.join(r)}var J=["npm_config_package","npm_config__package"];function _(e=process.env,n=process.platform,o=process.execPath){let r=t.join(v.tmpdir(),"rapidkit-corepack"),i={...e,PATH:R(e.PATH,n,o),COREPACK_HOME:e.COREPACK_HOME??r};for(let s of J)delete i[s];return i}function U(e=process.env,n=process.platform,o=process.execPath){return {..._(e,n,o),npm_config_engine_strict:"true"}}function I(e=process.platform){return c(e)?"python":"python3"}function G(e=process.platform){return c(e)?["python","py","python3"]:["python3","python"]}function M(e=14,n=10,o=process.platform){let r=[];if(c(o)){for(let i=e;i>=n;i-=1)r.push({command:"py",args:[`-3.${i}`,"--version"]});return r.push({command:"py",args:["-3","--version"]}),r.push({command:"python",args:["--version"]}),r}for(let i=e;i>=n;i-=1)r.push({command:`python3.${i}`,args:["--version"]});return r.push({command:"python3",args:["--version"]}),r.push({command:"python",args:["--version"]}),r}function $(e,n=process.platform){return c(n)?t.join(e,"Scripts"):t.join(e,"bin")}function D(e,n=process.platform){return c(n)?t.join(e,"Scripts","python.exe"):t.join(e,"bin","python")}function y(e,n=process.platform){return c(n)?t.join(e,"Scripts","pip.exe"):t.join(e,"bin","pip")}var w="WORKSPAI_PYTHON";function m(e,n){let o=t.relative(t.resolve(e),t.resolve(n));return o===""||!o.startsWith("..")&&!t.isAbsolute(o)}function P(e){try{return d.statSync(e).isFile()}catch{return false}}function C(e){let n=t.resolve(e);for(let o=0;o<8;o+=1){if(d.existsSync(t.join(n,".workspai","project.json")))return n;let r=t.dirname(n);if(r===n)break;n=r;}return t.resolve(e)}function x(e,n){let o=D(e,n);return P(o)?{interpreter:o,pipAvailable:P(y(e,n))}:null}function Y(e){let n=e.platform??process.platform,o=e.env??process.env,r=t.resolve(e.unitRoot),i=t.resolve(e.projectRoot??C(r)),s=t.join(i,".venv"),p=t.join(r,".venv"),a=o[w]?.trim();if(a&&P(a)&&(m(s,a)||m(p,a))){let f=m(s,a)?s:p;return {interpreter:a,source:"configured",venvPath:f,venvExists:true,pipAvailable:P(y(f,n))||m(f,a),usedForDependencyInstall:true}}let g=x(s,n);if(g)return {interpreter:g.interpreter,source:"project-venv",venvPath:s,venvExists:true,pipAvailable:g.pipAvailable,usedForDependencyInstall:true};let l=x(p,n);if(l)return {interpreter:l.interpreter,source:"unit-venv",venvPath:p,venvExists:true,pipAvailable:l.pipAvailable,usedForDependencyInstall:true};let u=o.VIRTUAL_ENV?.trim();if(u){let f=x(u,n);if(f&&(m(i,u)||m(r,u)))return {interpreter:f.interpreter,source:"active-project-venv",venvPath:u,venvExists:true,pipAvailable:f.pipAvailable,usedForDependencyInstall:true}}return {interpreter:I(n),source:"system",venvPath:s,venvExists:false,pipAvailable:false,usedForDependencyInstall:false}}function z(e,n){return t.relative(e,n).split(t.sep).join("/")||"."}function X(e,n,o=process.platform){let r=t.relative(e,n);return r?c(o)?r:r.split(t.sep).join("/"):"."}function q(e,n=process.platform){return c(n)?t.join(e,"Scripts","rapidkit.exe"):t.join(e,"bin","rapidkit")}function Q(e,n=process.platform){return c(n)?t.join(e,"Scripts","activate"):t.join(e,"bin","activate")}function Z(e,n=process.platform){return c(n)?[t.join(e,"workspai.cmd"),t.join(e,".workspai","rapidkit.cmd"),t.join(e,"rapidkit.cmd"),t.join(e,".rapidkit","rapidkit.cmd")]:[t.join(e,"workspai"),t.join(e,".workspai","rapidkit"),t.join(e,"rapidkit"),t.join(e,".rapidkit","rapidkit")]}function O(e=process.env,n=process.platform){let o=h(e);if(o)return o;let r=e.HOME||e.USERPROFILE||v.homedir();return t.join(r,".workspai")}function L(e=process.env,n=process.platform){let o=h(e);if(o)return t.join(o,"legacy");let r=e.HOME||e.USERPROFILE||v.homedir();return t.join(r,".rapidkit")}function ee(e=process.env,n=process.platform){let o=[t.join(O(e,n),"workspaces.json"),t.join(L(e,n),"workspaces.json")];if(h(e))return [...new Set(o)];if(c(n)){let r=e.XDG_CONFIG_HOME||e.APPDATA;r&&(o.push(t.join(r,"workspai","workspaces.json")),o.push(t.join(r,"rapidkit","workspaces.json")));}return [...new Set(o)]}function h(e){let n=e.WORKSPAI_STATE_DIR?.trim();return n&&t.isAbsolute(n)?t.normalize(n):null}function ne(e=process.env,n=process.platform){let o=[];return c(n)?(e.USERPROFILE&&o.push(t.join(e.USERPROFILE,".local","bin")),e.APPDATA&&o.push(t.join(e.APPDATA,"Python","Scripts")),e.LOCALAPPDATA&&o.push(t.join(e.LOCALAPPDATA,"Programs","Python","Scripts"))):o.push(t.join(v.homedir(),".local","bin")),[...new Set(o.filter(Boolean))]}export{j as a,c as b,W as c,B as d,k as e,R as f,_ as g,U as h,I as i,G as j,M as k,$ as l,D as m,y as n,w as o,C as p,Y as q,z as r,X as s,q as t,Q as u,Z as v,O as w,L as x,ee as y,ne as z};
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-A5FBGRJA.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {s as s$1}from'./chunk-RGNCL5OB.js';import {k,v,e,a as a$2,u,f as f$1}from'./chunk-VQZ5PI5J.js';import {t,s}from'./chunk-ODK4LCEL.js';import b from'crypto';import P from'fs';import d from'fs/promises';import i from'path';import T from'fs-extra';var x=s.projectWorkspaceLink.schemaVersion,L="workspai.project-workspace-link",l=class extends Error{constructor(r,a,o={}){super(a);this.code=r;this.context=o;this.name="ProjectWorkspaceResolutionError";}code;context};function $(e){return P.existsSync(i.join(e,".workspai-workspace"))?".workspai-workspace":".workspai/workspace.json"}function _(e){return b.createHash("sha256").update([e.workspaceName,a(e.workspacePath),e.projectName,a(e.projectPath),e.relativePath.replace(/\\/g,"/"),e.relationship].join("\0")).digest("hex")}function I(e){let t=i.resolve(e);for(;;){if(k(t))return t;let r=i.dirname(t);if(r===t)return null;t=r;}}function J(e){let t=i.resolve(e);for(;;){if([...u(t,"project.json"),...u(t,"context.json")].some(a=>P.existsSync(a)))return t;let r=i.dirname(t);if(r===t)return null;t=r;}}function y(e){return JSON.parse(P.readFileSync(e,"utf8"))}function K(e){let t$1=y(e);if(!t$1||typeof t$1!="object"||Array.isArray(t$1))throw new l("project.workspace.link-invalid",`Project workspace link is not a JSON object: ${e}`,{linkPath:e});let r=t$1;if(r.schemaVersion!==x||r.kind!==L||r.state!=="active"||!r.workspace||typeof r.workspace.name!="string"||r.workspace.name.trim().length===0||typeof r.workspace.root!="string"||!i.isAbsolute(r.workspace.root)||![".workspai-workspace",".workspai/workspace.json"].includes(r.workspace.marker??"")||r.workspace.contract!==t.workspaceContract||!r.project||typeof r.project.name!="string"||r.project.name.trim().length===0||typeof r.project.relativePath!="string"||i.isAbsolute(r.project.relativePath)||r.project.relativePath.split(/[\\/]/).includes("..")||!["managed","adopted","imported","linked","restored"].includes(r.project.relationship??"")||!r.integrity||r.integrity.algorithm!=="sha256"||typeof r.integrity.binding!="string"||!/^[a-f0-9]{64}$/.test(r.integrity.binding))throw new l("project.workspace.link-invalid",`Project workspace link does not satisfy ${x}: ${e}`,{linkPath:e});try{a$1(t$1,"contracts/project-workspace-link.v1.json","Project workspace link");}catch(a){throw new l("project.workspace.link-invalid",`Project workspace link does not satisfy ${x}: ${e}`,{linkPath:e,validationError:a instanceof Error?a.message:String(a)})}return r}function f(e,t){let r=i.join(e,".workspai","workspace.contract.json");if(!P.existsSync(r))return null;try{let a$1=y(r);if(!Array.isArray(a$1.projects))return false;let o=a(t);return a$1.projects.some(n=>typeof n.externalPath=="string"?a(n.externalPath)===o:typeof n.relativePath!="string"||n.relativePath.startsWith("external/")?false:a(i.resolve(e,n.relativePath))===o)}catch{return false}}function M(e,t,r){let a$1=a(e),o=new Map;for(let n of s$1(t,r)){if(!P.existsSync(n))continue;let c;try{c=y(n);}catch{continue}if(Array.isArray(c.workspaces))for(let p of c.workspaces){if(!p||typeof p.name!="string"||typeof p.path!="string"||!Array.isArray(p.projects)||!p.projects.some(w=>w&&typeof w.path=="string"&&a(w.path)===a$1))continue;let s=a(p.path);!k(s)||f(s,e)!==true||o.set(s,{name:p.name,path:s});}}return [...o.values()].sort((n,c)=>n.path.localeCompare(c.path))}function m(e,t){if(e)throw t;return null}function te(e$1){let t=e$1.strict===true,r=i.resolve(e$1.startPath),a=e$1.explicitWorkspacePath?i.resolve(e$1.explicitWorkspacePath):null,o=J(r);if(a)return k(a)?e$1.requireProjectMembership===true&&o&&f(a,o)!==true?m(t,new l("project.workspace.membership-missing",`Project is not registered in the explicit workspace contract: ${a}`,{workspacePath:a,projectPath:o})):{workspacePath:a,projectPath:o,source:"explicit",linkPath:o?v(o,e):null,recovered:false}:m(t,new l("project.workspace.explicit-invalid",`Explicit workspace path is not a Workspai workspace: ${a}`,{workspacePath:a,projectPath:o}));let n=I(r);if(n)return e$1.requireProjectMembership===true&&o&&f(n,o)!==true?m(t,new l("project.workspace.membership-missing",`Project is not registered in its parent workspace contract: ${n}`,{workspacePath:n,projectPath:o})):{workspacePath:n,projectPath:o,source:"parent",linkPath:o?v(o,e):null,recovered:false};if(!o)return m(t,new l("project.workspace.unlinked","No Workspai project or workspace could be resolved from the current directory.",{startPath:r}));let c=v(o,e),p=null;if(P.existsSync(c)){let s;try{s=K(c);}catch(O){if(t)throw O;return null}let u=_({workspaceName:s.workspace.name,workspacePath:s.workspace.root,projectName:s.project.name,projectPath:o,relativePath:s.project.relativePath,relationship:s.project.relationship}),w=f(s.workspace.root,o);if(s.integrity.binding===u&&k(s.workspace.root)&&P.existsSync(i.join(s.workspace.root,s.workspace.marker))&&w===true)return {workspacePath:i.resolve(s.workspace.root),projectPath:o,source:"local-link",linkPath:c,recovered:false};p=s;}let h=M(o,e$1.env??process.env,e$1.platform??process.platform);return h.length>1?m(t,new l("project.workspace.ambiguous",`Project is registered in more than one valid workspace: ${h.map(s=>s.name).join(", ")}. Pass --workspace <path> or run project workspace relink.`,{projectPath:o,candidates:h})):h.length===1?{workspacePath:h[0].path,projectPath:o,source:"registry",linkPath:c,recovered:p!==null}:p?m(t,new l("project.workspace.link-stale",`Project workspace link is stale and no valid registry relocation was found: ${p.workspace.root}`,{projectPath:o,linkPath:c,linkedWorkspacePath:p.workspace.root})):m(t,new l("project.workspace.unlinked","This Workspai project is not linked to a valid workspace. Run `npx workspai adopt .` or `npx workspai project workspace relink --workspace <path>`.",{projectPath:o,linkPath:c}))}async function F(e,t){await d.mkdir(i.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${b.randomUUID()}.tmp`;try{await d.writeFile(r,`${JSON.stringify(t,null,2)}
1
+ import {a}from'./chunk-A5FBGRJA.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {y as y$1}from'./chunk-6BO4QHKA.js';import {k,v,e,a as a$2,u,f as f$1}from'./chunk-VQZ5PI5J.js';import {t,s}from'./chunk-ODK4LCEL.js';import b from'crypto';import P from'fs';import d from'fs/promises';import i from'path';import T from'fs-extra';var x=s.projectWorkspaceLink.schemaVersion,L="workspai.project-workspace-link",l=class extends Error{constructor(r,a,o={}){super(a);this.code=r;this.context=o;this.name="ProjectWorkspaceResolutionError";}code;context};function $(e){return P.existsSync(i.join(e,".workspai-workspace"))?".workspai-workspace":".workspai/workspace.json"}function _(e){return b.createHash("sha256").update([e.workspaceName,a(e.workspacePath),e.projectName,a(e.projectPath),e.relativePath.replace(/\\/g,"/"),e.relationship].join("\0")).digest("hex")}function I(e){let t=i.resolve(e);for(;;){if(k(t))return t;let r=i.dirname(t);if(r===t)return null;t=r;}}function J(e){let t=i.resolve(e);for(;;){if([...u(t,"project.json"),...u(t,"context.json")].some(a=>P.existsSync(a)))return t;let r=i.dirname(t);if(r===t)return null;t=r;}}function y(e){return JSON.parse(P.readFileSync(e,"utf8"))}function K(e){let t$1=y(e);if(!t$1||typeof t$1!="object"||Array.isArray(t$1))throw new l("project.workspace.link-invalid",`Project workspace link is not a JSON object: ${e}`,{linkPath:e});let r=t$1;if(r.schemaVersion!==x||r.kind!==L||r.state!=="active"||!r.workspace||typeof r.workspace.name!="string"||r.workspace.name.trim().length===0||typeof r.workspace.root!="string"||!i.isAbsolute(r.workspace.root)||![".workspai-workspace",".workspai/workspace.json"].includes(r.workspace.marker??"")||r.workspace.contract!==t.workspaceContract||!r.project||typeof r.project.name!="string"||r.project.name.trim().length===0||typeof r.project.relativePath!="string"||i.isAbsolute(r.project.relativePath)||r.project.relativePath.split(/[\\/]/).includes("..")||!["managed","adopted","imported","linked","restored"].includes(r.project.relationship??"")||!r.integrity||r.integrity.algorithm!=="sha256"||typeof r.integrity.binding!="string"||!/^[a-f0-9]{64}$/.test(r.integrity.binding))throw new l("project.workspace.link-invalid",`Project workspace link does not satisfy ${x}: ${e}`,{linkPath:e});try{a$1(t$1,"contracts/project-workspace-link.v1.json","Project workspace link");}catch(a){throw new l("project.workspace.link-invalid",`Project workspace link does not satisfy ${x}: ${e}`,{linkPath:e,validationError:a instanceof Error?a.message:String(a)})}return r}function f(e,t){let r=i.join(e,".workspai","workspace.contract.json");if(!P.existsSync(r))return null;try{let a$1=y(r);if(!Array.isArray(a$1.projects))return false;let o=a(t);return a$1.projects.some(n=>typeof n.externalPath=="string"?a(n.externalPath)===o:typeof n.relativePath!="string"||n.relativePath.startsWith("external/")?false:a(i.resolve(e,n.relativePath))===o)}catch{return false}}function M(e,t,r){let a$1=a(e),o=new Map;for(let n of y$1(t,r)){if(!P.existsSync(n))continue;let c;try{c=y(n);}catch{continue}if(Array.isArray(c.workspaces))for(let p of c.workspaces){if(!p||typeof p.name!="string"||typeof p.path!="string"||!Array.isArray(p.projects)||!p.projects.some(w=>w&&typeof w.path=="string"&&a(w.path)===a$1))continue;let s=a(p.path);!k(s)||f(s,e)!==true||o.set(s,{name:p.name,path:s});}}return [...o.values()].sort((n,c)=>n.path.localeCompare(c.path))}function m(e,t){if(e)throw t;return null}function te(e$1){let t=e$1.strict===true,r=i.resolve(e$1.startPath),a=e$1.explicitWorkspacePath?i.resolve(e$1.explicitWorkspacePath):null,o=J(r);if(a)return k(a)?e$1.requireProjectMembership===true&&o&&f(a,o)!==true?m(t,new l("project.workspace.membership-missing",`Project is not registered in the explicit workspace contract: ${a}`,{workspacePath:a,projectPath:o})):{workspacePath:a,projectPath:o,source:"explicit",linkPath:o?v(o,e):null,recovered:false}:m(t,new l("project.workspace.explicit-invalid",`Explicit workspace path is not a Workspai workspace: ${a}`,{workspacePath:a,projectPath:o}));let n=I(r);if(n)return e$1.requireProjectMembership===true&&o&&f(n,o)!==true?m(t,new l("project.workspace.membership-missing",`Project is not registered in its parent workspace contract: ${n}`,{workspacePath:n,projectPath:o})):{workspacePath:n,projectPath:o,source:"parent",linkPath:o?v(o,e):null,recovered:false};if(!o)return m(t,new l("project.workspace.unlinked","No Workspai project or workspace could be resolved from the current directory.",{startPath:r}));let c=v(o,e),p=null;if(P.existsSync(c)){let s;try{s=K(c);}catch(O){if(t)throw O;return null}let u=_({workspaceName:s.workspace.name,workspacePath:s.workspace.root,projectName:s.project.name,projectPath:o,relativePath:s.project.relativePath,relationship:s.project.relationship}),w=f(s.workspace.root,o);if(s.integrity.binding===u&&k(s.workspace.root)&&P.existsSync(i.join(s.workspace.root,s.workspace.marker))&&w===true)return {workspacePath:i.resolve(s.workspace.root),projectPath:o,source:"local-link",linkPath:c,recovered:false};p=s;}let h=M(o,e$1.env??process.env,e$1.platform??process.platform);return h.length>1?m(t,new l("project.workspace.ambiguous",`Project is registered in more than one valid workspace: ${h.map(s=>s.name).join(", ")}. Pass --workspace <path> or run project workspace relink.`,{projectPath:o,candidates:h})):h.length===1?{workspacePath:h[0].path,projectPath:o,source:"registry",linkPath:c,recovered:p!==null}:p?m(t,new l("project.workspace.link-stale",`Project workspace link is stale and no valid registry relocation was found: ${p.workspace.root}`,{projectPath:o,linkPath:c,linkedWorkspacePath:p.workspace.root})):m(t,new l("project.workspace.unlinked","This Workspai project is not linked to a valid workspace. Run `npx workspai adopt .` or `npx workspai project workspace relink --workspace <path>`.",{projectPath:o,linkPath:c}))}async function F(e,t){await d.mkdir(i.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${b.randomUUID()}.tmp`;try{await d.writeFile(r,`${JSON.stringify(t,null,2)}
2
2
  `,{encoding:"utf8",mode:384});try{await d.rename(r,e);}catch(a){let o=a.code;if(o!=="EEXIST"&&o!=="EPERM")throw a;await T.move(r,e,{overwrite:true});}}finally{await d.rm(r,{force:true}).catch(()=>{});}}async function D(e){let t=i.join(e,".gitignore"),r=await d.readFile(t,"utf8").catch(c=>{if(c.code==="ENOENT")return "";throw c});if(r.split(/\r?\n/).map(c=>c.trim()).includes(f$1))return;let n=`${r.length>0&&!r.endsWith(`
3
3
  `)?`
4
4
  `:""}
@@ -1 +1 @@
1
- import {a as a$2}from'./chunk-5K4O3TAW.js';import {j,l as l$1}from'./chunk-FZWLWFR4.js';import {g}from'./chunk-FNVWDXK2.js';import {a as a$1}from'./chunk-K52IQX3J.js';import {v}from'./chunk-66O62XNJ.js';import {j as j$1,e}from'./chunk-RU3UT7GJ.js';import {b,c as c$1}from'./chunk-P36TACKN.js';import {c,d}from'./chunk-PFAGXI3G.js';import {a}from'./chunk-COICGD62.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-SZHRPELL.js';import {k,l,h as h$1,m,n,p as p$1,q as q$1}from'./chunk-GDOO2YZW.js';import {a as a$3}from'./chunk-VWBWDDU2.js';import {o as o$1,r as r$1,u}from'./chunk-LARREYZN.js';import {o,r as r$2,s}from'./chunk-VXFIMEC6.js';import {f,h}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {c as c$2}from'./chunk-EFHSRPW7.js';import {p,q,z,A,y,x}from'./chunk-ODK4LCEL.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(p.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===p.intelligenceRun,`artifactPath must be ${p.intelligenceRun}`),r(t.preflight.length===y.length,`preflight must contain exactly ${y.length} entries`);for(let[d,n]of y.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,z[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===x.length,`stages must contain exactly ${x.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of x.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,A[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y$1=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y$1?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=p.intelligenceRun,Ee=q.intelligenceRun,L=we;function I(t){c$2({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return f(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$1=[],u$1=[],h$3=false,y=async(e,o)=>{let c=[...z[e]];if(h$3){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...A[e].produces];if(h$3){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u$1.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u$1.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u$1.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o$1=await o({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o$1.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await r$1({workspacePath:s$1,includeEvidence:true}),build:o$1({mode:"full",engineStatus:"disabled"})},await u(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,p.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h$1(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e=await m({workspacePath:s$1,fromPath:p.snapshot,model:d$1()});return await n(e,s$1),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e=await p$1({workspacePath:s$1,fromPath:p.diff});return await q$1(e,s$1),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await v({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$2({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:p.impact});await g$1(e$1,s$1);let o=h$2(e$1,{strict:t.strict===true});return await j$1(s$1,e(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c$1=await a$3(s$1);if(c$1.status==="miss"){if(c$1.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c$1.reason}).`);p$2={...await r$1({workspacePath:s$1,includeEvidence:true}),build:o$1({mode:"full",engineStatus:"disabled"})},await u(p$2,s$1);let f=await c({workspacePath:s$1,model:p$2,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$1(e,s$1);let o=t.strict===true?u$1.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u$1.some(e=>e.status==="blocked"),G=h$3?"failed":me?"blocked":"passed",fe=h$3?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u$1,artifactPath:L};ue(b$1),await h(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await h(s$1,p.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
1
+ import {a as a$2}from'./chunk-TGNPMOM6.js';import {j,l as l$1}from'./chunk-J2MPBSQJ.js';import {g}from'./chunk-GLBFY7AB.js';import {a as a$1}from'./chunk-223SWPTL.js';import {v}from'./chunk-SC43A6LH.js';import {j as j$1,e}from'./chunk-RU3UT7GJ.js';import {b,c as c$1}from'./chunk-47UR6ZH4.js';import {c,d}from'./chunk-JVZA35OL.js';import {a}from'./chunk-COICGD62.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-3SQIV3F4.js';import {k,l,h as h$1,m,n,p as p$1,q as q$1}from'./chunk-3EPR3D5Q.js';import {a as a$3}from'./chunk-4CXV3PPV.js';import {o as o$1,r as r$1,u}from'./chunk-SEZTSMRR.js';import {o,r as r$2,s}from'./chunk-IHWS3ALP.js';import {f,h}from'./chunk-BLEIUQL6.js';import {b as b$1}from'./chunk-VN2MKTQO.js';import {c as c$2}from'./chunk-EFHSRPW7.js';import {p,q,z,A,y,x}from'./chunk-ODK4LCEL.js';import ge from'path';import pe from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function de(t,s){return t.length===s.length&&t.every((m,u)=>m===s[u])}function ue(t){b$1(p.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===p.intelligenceRun,`artifactPath must be ${p.intelligenceRun}`),r(t.preflight.length===y.length,`preflight must contain exactly ${y.length} entries`);for(let[d,n]of y.entries()){let a=t.preflight[d];r(a?.id===n,`preflight[${d}].id must be ${n}`),r(de(a.artifacts,z[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===x.length,`stages must contain exactly ${x.length} canonical steps`);let m=t.preflight[0],u=m?.status==="failed";for(let[d,n]of x.entries()){let a=t.stages[d];r(a?.id===n,`stages[${d}].id must be ${n}`),r(de(a.artifacts,A[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),d===0&&((m?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(m?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let h=t.preflight.some(d=>d.status==="failed")||t.stages.some(d=>d.status==="failed"),y$1=t.stages.some(d=>d.status==="blocked"),l=h?"failed":y$1?"blocked":"passed",p$1=l==="failed"?1:l==="blocked"?2:0;r(t.status===l,`status must be ${l}`),r(t.exitCode===p$1,`exitCode must be ${p$1}`);}var we=p.intelligenceRun,Ee=q.intelligenceRun,L=we;function I(t){c$2({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function Ue(t){let s=ge.resolve(t.workspacePath);return f(s,L,()=>ye({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function ye(t){let s$1=t.workspacePath,m$1=[],u$1=[],h$3=false,y=async(e,o)=>{let c=[...z[e]];if(h$3){I({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),m$1.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:c,message:"skipped because a required upstream operation failed"});return}let k=Date.now();I({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let i=await o();I({id:e,kind:"preflight",status:"passed",message:i.message}),m$1.push({id:e,status:"passed",result:i.result,durationMs:Date.now()-k,artifacts:c,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"preflight",status:"failed",message:f}),m$1.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-k,artifacts:c,message:f});}},l$2=async(e,o)=>{let c=[...A[e].produces];if(h$3){I({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u$1.push({id:e,status:"skipped",durationMs:0,artifacts:c,exitCode:0,message:"skipped because a required upstream stage failed"});return}let k=Date.now();I({id:e,kind:"stage",status:"started",message:`${e} started`});try{let i=await o(),f=i.exitCode??0,w=i.blocked||f!==0?"blocked":"passed";I({id:e,kind:"stage",status:w,message:i.message}),u$1.push({id:e,status:w,durationMs:Date.now()-k,artifacts:c,exitCode:f,message:i.message});}catch(i){h$3=true;let f=i instanceof Error?i.message:String(i);I({id:e,kind:"stage",status:"failed",message:f}),u$1.push({id:e,status:"failed",durationMs:Date.now()-k,artifacts:c,exitCode:1,message:f});}};await y("sync",async()=>{let e=await g(s$1,true),o$1=await o({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${o$1.contract.projects.length} projects`}});let p$2,d$1=()=>{if(!p$2)throw new Error("canonical workspace model is unavailable");return p$2};await l$2("model",async()=>(p$2={...await r$1({workspacePath:s$1,includeEvidence:true}),build:o$1({mode:"full",engineStatus:"disabled"})},await u(p$2,s$1),{message:`${p$2.summary.projectCount} projects modeled`}));let n$1=ge.join(s$1,p.snapshot),a$4=false;await y("baseline",async()=>{if(!await pe.pathExists(n$1)){let c=await k({workspacePath:s$1,model:d$1()});return await l(c,s$1),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await pe.readJson(n$1),o=h$1(e);return o?(await l(o,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await l$2("diff",async()=>{let e=await m({workspacePath:s$1,fromPath:p.snapshot,model:d$1()});return await n(e,s$1),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await l$2("impact",async()=>{let e=await p$1({workspacePath:s$1,fromPath:p.diff});return await q$1(e,s$1),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await l$2("doctor-evidence",async()=>{let e=await v({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await l$2("contract-evidence",async()=>{let e=await r$2({workspacePath:s$1,strict:true});return await s({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await l$2("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await l$2("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await l$2("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:p.impact});await g$1(e$1,s$1);let o=h$2(e$1,{strict:t.strict===true});return await j$1(s$1,e(e$1,o.passed)),{blocked:!o.passed,exitCode:o.exitCode,message:`${e$1.summary.verdict}; gate ${o.passed?"passed":"blocked"}`}}),await l$2("context",async()=>{let e=await c({workspacePath:s$1,model:d$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await l$2("agent-sync",async()=>{let e=await l$1({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),o=false,c$1=await a$3(s$1);if(c$1.status==="miss"){if(c$1.reason!=="live-input-mismatch")throw new Error(`Agent grounding left canonical evidence invalid (${c$1.reason}).`);p$2={...await r$1({workspacePath:s$1,includeEvidence:true}),build:o$1({mode:"full",engineStatus:"disabled"})},await u(p$2,s$1);let f=await c({workspacePath:s$1,model:p$2,agent:t.agent??"generic",includeEvidence:true});await d(f,s$1);let w=await l$1({workspacePath:s$1,agent:t.agent??"generic",targets:["all"],write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"});e={...w,writtenFiles:[...new Set([...e.writtenFiles,...w.writtenFiles])].sort(),strictViolations:[...new Set([...e.strictViolations??[],...w.strictViolations??[]])].sort()};let O=await a$3(s$1);if(O.status==="miss")throw new Error(`Agent grounding reconciliation did not produce fresh canonical evidence (${O.reason}).`);o=true;}let k=e.strictViolations??[],i=t.strict===true&&k.length>0;return {blocked:i,exitCode:i?2:0,message:i?`${e.writtenFiles.length} grounding files written; ${k.length} strict grounding violation(s): ${k.join("; ")}`:`${e.writtenFiles.length} grounding files written; portable entry surfaces prepared for all supported hosts${o?"; canonical Model/Graph freshness sealed":""}`}}),await l$2("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$1(e,s$1);let o=t.strict===true?u$1.filter(c=>c.status==="blocked").map(c=>c.id):[];return {message:o.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${o.join(", ")}. ${e.summary}`:e.summary}});let me=u$1.some(e=>e.status==="blocked"),G=h$3?"failed":me?"blocked":"passed",fe=h$3?1:G==="blocked"?2:0,b$1={schemaVersion:Ee,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$4,preflight:m$1,status:G,exitCode:fe,stages:u$1,artifactPath:L};ue(b$1),await h(s$1,L,b$1);let ke=await j({workspacePath:s$1});return await h(s$1,p.agentIndex,ke),b$1}export{we as a,Ee as b,Ue as c};
@@ -1,4 +1,4 @@
1
- import {b}from'./chunk-3N27P3KO.js';import {a as a$1,e}from'./chunk-BR6QIYQS.js';import {a as a$3}from'./chunk-COOVCORC.js';import {g,a,h}from'./chunk-BLEIUQL6.js';import {p,s}from'./chunk-ODK4LCEL.js';import a$2 from'chalk';import re from'fs';import b$1 from'path';import {execa}from'execa';var V="autopilot-release-last-run.json",G="autopilot-release.json";function $(r){try{return JSON.parse(r)}catch{return null}}function Se(r){let e=b$1.resolve(r),n=a$3(e);if(!n)throw new Error("No Workspai workspace found in current directory or parents");return n}async function S(r,e){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let o=await execa(process.execPath,[n,...r],{cwd:e,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr,crashed:false}}catch(o){return {exitCode:1,stdout:"",stderr:o instanceof Error?o.message:String(o),crashed:true}}}function oe(r){let e=r.toLowerCase();return e==="pass"?"pass":e==="warn"?"warn":e==="fail"?"fail":"warn"}function ae(r){return r.summary.failed>0||r.gates.results.some(e=>e.status==="fail")?"fail":r.gates.results.some(e=>e.status==="warn")?"warn":"pass"}function be(r){let e=r.filter(o=>o.status!=="skipped");if(e.length===0)return 100;let n=e.reduce((o,t)=>t.status==="pass"?o+1:t.status==="warn"?o+.6:o,0);return Math.round(n/e.length*100)}function Ae(r){return r.executionError?["Re-run: npx workspai autopilot release --mode audit --json","Inspect .workspai/reports/autopilot-release-last-run.json for execution failure details"]:r.blockers.length>0?["Run: npx workspai doctor workspace --plan","Run: npx workspai readiness --json --strict","Run: npx workspai workspace run test --affected --strict"]:r.hasWarnings&&r.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx workspai autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function xe(r,e){await re.promises.mkdir(b$1.dirname(r),{recursive:true}),await re.promises.writeFile(r,`${JSON.stringify(e,null,2)}
1
+ import {b}from'./chunk-WC2K5QFI.js';import {a as a$1,e}from'./chunk-P5LI5DL3.js';import {a as a$3}from'./chunk-SVO2GGTV.js';import {g,a,h}from'./chunk-BLEIUQL6.js';import {p,s}from'./chunk-ODK4LCEL.js';import a$2 from'chalk';import re from'fs';import b$1 from'path';import {execa}from'execa';var V="autopilot-release-last-run.json",G="autopilot-release.json";function $(r){try{return JSON.parse(r)}catch{return null}}function Se(r){let e=b$1.resolve(r),n=a$3(e);if(!n)throw new Error("No Workspai workspace found in current directory or parents");return n}async function S(r,e){let n=process.argv[1];if(!n)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for autopilot execution.",crashed:true};try{let o=await execa(process.execPath,[n,...r],{cwd:e,reject:false,env:{...process.env,RAPIDKIT_AUTOPILOT_CHILD:"1"}});return {exitCode:Number(o.exitCode??1),stdout:o.stdout,stderr:o.stderr,crashed:false}}catch(o){return {exitCode:1,stdout:"",stderr:o instanceof Error?o.message:String(o),crashed:true}}}function oe(r){let e=r.toLowerCase();return e==="pass"?"pass":e==="warn"?"warn":e==="fail"?"fail":"warn"}function ae(r){return r.summary.failed>0||r.gates.results.some(e=>e.status==="fail")?"fail":r.gates.results.some(e=>e.status==="warn")?"warn":"pass"}function be(r){let e=r.filter(o=>o.status!=="skipped");if(e.length===0)return 100;let n=e.reduce((o,t)=>t.status==="pass"?o+1:t.status==="warn"?o+.6:o,0);return Math.round(n/e.length*100)}function Ae(r){return r.executionError?["Re-run: npx workspai autopilot release --mode audit --json","Inspect .workspai/reports/autopilot-release-last-run.json for execution failure details"]:r.blockers.length>0?["Run: npx workspai doctor workspace --plan","Run: npx workspai readiness --json --strict","Run: npx workspai workspace run test --affected --strict"]:r.hasWarnings&&r.mode!=="enforce"?["Review warning-level findings in autopilot report","Optionally run: npx workspai autopilot release --mode safe-fix"]:["Workspace is release-ready based on current autopilot policy"]}async function xe(r,e){await re.promises.mkdir(b$1.dirname(r),{recursive:true}),await re.promises.writeFile(r,`${JSON.stringify(e,null,2)}
2
2
  `,"utf-8");}async function ze(r){let e$1=Se(r.workspacePath),n=r.mode,o=[],t=[],L,H,N,q,Q,X=0,f=false,I=0,_=0,W=-1,T=-1,c="skipped",d="skipped",ne=n==="enforce"?["doctor","workspace","--json","--strict"]:["doctor","workspace","--json","--ci"];if(r.skipPipelineStages)o.push({name:"doctor-workspace",status:"skipped",durationMs:0,summary:"doctor stage skipped (pipeline already executed)"},{name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped (pipeline already executed)"},{name:"readiness",status:"skipped",durationMs:0,summary:"readiness stage skipped (pipeline already executed)"});else {let s=Date.now(),l=await S([...ne],e$1),m=Date.now()-s;if(c="pass",l.crashed)c="fail",f=true,t.push(`doctor workspace execution error: ${l.stderr||"unknown error"}`);else if(l.exitCode===1)c="fail",t.push("doctor workspace command failed or reported errors");else if(l.exitCode===2)c="warn",t.push("doctor workspace reported warnings");else if(l.exitCode!==0)c="fail",t.push("doctor workspace command failed");else {let p=$(l.stdout),E=p&&p.healthScore&&typeof p.healthScore=="object"?p.healthScore:{},k=Number(E.errors??0),C=Number(E.warnings??0);Number.isFinite(k)&&k>0?(c="fail",t.push(`doctor workspace reports ${k} error(s)`)):Number.isFinite(C)&&C>0&&(c="warn");}W=o.push({name:"doctor-workspace",status:c,durationMs:m,summary:c==="pass"?"doctor workspace passed":c==="warn"?"doctor workspace reported warnings":"doctor workspace reported errors"})-1,n==="enforce"&&c==="warn"&&t.push("doctor workspace reported warnings under enforce mode");let g$1=Date.now(),w=await S(["analyze","--json"],e$1),P=Date.now()-g$1;H=await g(e$1,p.analyze)??a(e$1,p.analyze);let i="pass";if(w.crashed)i="fail",f=true,t.push(`analyze execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)i=w.exitCode===2?"warn":"fail",t.push(w.exitCode===2?"analyze reported needs-attention verdict":"analyze command failed or reported blocked verdict");else {let p=$(w.stdout),E=p&&p.summary&&typeof p.summary=="object"?p.summary:{},k=String(E.verdict??"ready");k==="blocked"?(i="fail",t.push("analyze reported blocked verdict")):k==="needs-attention"&&(i="warn");}o.push({name:"analyze",status:i,durationMs:P,summary:i==="pass"?"analyze passed":i==="warn"?"analyze reported needs-attention":"analyze reported blocked verdict"}),n==="enforce"&&i==="warn"&&t.push("analyze reported warnings under enforce mode");let v=Date.now(),h=await S(["readiness","--json"],e$1),y=Date.now()-v;if(d="fail",h.crashed)d="fail",f=true,t.push(`readiness execution error: ${h.stderr||"unknown error"}`);else if(h.exitCode!==0)d="fail",t.push("readiness command failed");else {let p=$(h.stdout),E=String(p?.overallStatus??"fail");if(d=oe(E),typeof p?.evidencePath=="string"&&p.evidencePath.trim().length>0&&(L=p.evidencePath),d==="fail"){let k=Array.isArray(p?.blockingReasons)?p?.blockingReasons.filter(C=>typeof C=="string"):[];k.length>0?t.push(...k.map(C=>`readiness: ${C}`)):t.push("readiness overall status is fail");}}T=o.push({name:"readiness",status:d,durationMs:y,summary:`readiness overall status is ${d}`})-1,n==="enforce"&&d==="warn"&&t.push("readiness reported warnings under enforce mode");}let ie=Date.now(),D=await S(["doctor","workspace","--plan","--json"],e$1),le=Date.now()-ie,R="warn";if(D.crashed)R="fail",f=true,t.push(`doctor remediation plan execution error: ${D.stderr||"unknown error"}`);else if(D.exitCode!==0)R="fail",t.push("doctor remediation plan command failed");else {let s=$(D.stdout),l=s&&s.remediationPlan&&typeof s.remediationPlan=="object"?s.remediationPlan:null,m=Number(l?.totalSteps??0),g=Number(l?.executableSteps??0);Number.isFinite(m)&&m>0&&(I=m),Number.isFinite(g)&&g>0&&(_=g),Number.isFinite(m)&&m===0?R="pass":R="warn";}if(o.push({name:"remediation-plan",status:R,durationMs:le,summary:R==="pass"?"no remediation steps required":"remediation steps available"}),n==="enforce"&&R==="warn"&&t.push("remediation plan has pending steps under enforce mode"),n==="safe-fix"){let s=Date.now(),l=await S(["doctor","workspace","--apply"],e$1),m=Date.now()-s,g=l.crashed||l.exitCode!==0?"fail":"pass";if(l.crashed)f=true,t.push(`doctor remediation apply execution error: ${l.stderr||"unknown error"}`);else if(g==="fail")t.push("doctor remediation apply failed");else {X=_>0?_:I>0?I:1;let w=await S(["doctor","workspace","--json"],e$1);if(w.crashed)c="fail",f=true,t.push(`post-apply doctor execution error: ${w.stderr||"unknown error"}`);else if(w.exitCode!==0)c="fail",t.push("post-apply doctor workspace command failed");else {let i=$(w.stdout),v=i&&i.healthScore&&typeof i.healthScore=="object"?i.healthScore:{},h=Number(v.errors??0),y=Number(v.warnings??0);Number.isFinite(h)&&h>0?(c="fail",t.push(`post-apply doctor reports ${h} error(s)`)):Number.isFinite(y)&&y>0?c="warn":c="pass";}W>=0&&(o[W].status=c,o[W].summary=`doctor workspace post-apply status is ${c}`);let P=await S(["readiness","--json"],e$1);if(P.crashed)d="fail",f=true,t.push(`post-apply readiness execution error: ${P.stderr||"unknown error"}`);else if(P.exitCode!==0)d="fail",t.push("post-apply readiness command failed");else {let i=$(P.stdout),v=String(i?.overallStatus??"fail");if(d=oe(v),typeof i?.evidencePath=="string"&&i.evidencePath.trim().length>0&&(L=i.evidencePath),d==="fail"){let h=Array.isArray(i?.blockingReasons)?i?.blockingReasons.filter(y=>typeof y=="string"):[];h.length>0?t.push(...h.map(y=>`post-apply readiness: ${y}`)):t.push("post-apply readiness overall status is fail");}}T>=0&&(o[T].status=d,o[T].summary=`readiness post-apply overall status is ${d}`);}o.push({name:"remediation-apply",status:g,durationMs:m,summary:g==="pass"?"safe remediation apply completed":"safe remediation apply failed"});}else o.push({name:"remediation-apply",status:"skipped",durationMs:0,summary:"remediation apply is skipped for this mode"});let ce=Date.now(),A="pass",x="workspace test/build completed for selected projects";try{let s=await b({workspacePath:e$1,stage:"test",affected:true,since:r.since,parallel:r.parallel,maxWorkers:r.maxWorkers,strict:true,json:true,enforceGates:false});N=a(e$1,b$1.join(".workspai","reports",a$1)),await e(e$1,s),q=N;let l=ae(s);if(l==="fail")A="fail",x="workspace test stage failed for selected projects",t.push("workspace run test failed for selected projects");else {l==="warn"&&(A="warn",x="workspace test stage completed with warnings",n==="enforce"&&t.push("workspace run test reported warnings under enforce mode"));let m=await b({workspacePath:e$1,stage:"build",affected:true,since:r.since,parallel:r.parallel,maxWorkers:r.maxWorkers,strict:true,json:true,enforceGates:false});await e(e$1,m),Q=N;let g=ae(m);g==="fail"?(A="fail",x="workspace build stage failed for selected projects",t.push("workspace run build failed for selected projects")):g==="warn"&&(A="warn",x="workspace test/build completed with warnings",n==="enforce"&&t.push("workspace run test/build reported warnings under enforce mode"));}}catch(s){A="fail",x="workspace test/build orchestration failed",f=true,t.push(`workspace run orchestration error: ${s instanceof Error?s.message:String(s)}`);}let pe=Date.now()-ce;o.push({name:"workspace-run-test-build",status:A,durationMs:pe,summary:x});let M=o.filter(s=>s.status==="warn").length,ue=o.filter(s=>s.status==="fail").length,F=n==="enforce"?o.some(s=>s.status==="warn"||s.status==="fail"):ue>0,j=[...new Set(t)],O=f||F?Math.max(1,j.length):0,de=O>0?j:[],fe=O===0?j:[],me=be(o),ge=f||F?"blocked":M>0?"partial":"approved",we=f?3:F?1:M>0?2:0,he=Ae({mode:n,executionError:f,blockers:j,hasWarnings:M>0}),Y=a(e$1,".workspai/reports"),ke=b$1.join(Y,V),ye=b$1.join(Y,G),u={schemaVersion:s.autopilotReleaseLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:e$1,mode:n,summary:{releaseScore:me,verdict:ge,blockers:O,warnings:M,safeFixesApplied:X,manualActions:j.length,exitCode:we},stages:o,blockingReasons:de,warningReasons:fe,nextActions:he,artifacts:{reportPath:ke,aliasEvidencePath:ye,analyzeEvidencePath:H,readinessEvidencePath:L,workspaceRunEvidencePath:N,workspaceRunTestPath:q,workspaceRunBuildPath:Q},enterpriseControls:{jsonReady:true,evidencePath:`.workspai/reports/${V}`,aliasEvidencePath:`.workspai/reports/${G}`}};if(await h(e$1,`.workspai/reports/${V}`,u),await h(e$1,`.workspai/reports/${G}`,u),r.output&&await xe(b$1.resolve(r.output),u),!r.json){console.log(a$2.bold.cyan(`
3
3
  \u{1F680} Workspai Autopilot Release
4
4
  `)),console.log(a$2.bold(`Workspace: ${a$2.cyan(b$1.basename(e$1))}`)),console.log(a$2.gray(`Path: ${e$1}`)),console.log(a$2.white(`Mode: ${n}`)),console.log(a$2.white(`Verdict: ${u.summary.verdict==="approved"?a$2.green("approved"):u.summary.verdict==="partial"?a$2.yellow("partial"):a$2.red("blocked")}`)),console.log(a$2.white(`Release score: ${u.summary.releaseScore}`));for(let s of u.stages){let l=s.status==="pass"?a$2.green("PASS"):s.status==="warn"?a$2.yellow("WARN"):s.status==="skipped"?a$2.gray("SKIP"):a$2.red("FAIL");console.log(` - ${s.name}: ${l} ${s.summary} (${s.durationMs}ms)`);}if(u.blockingReasons.length>0){console.log(a$2.bold.red(`
@@ -1,8 +1,8 @@
1
- import {c}from'./chunk-N4B2M44I.js';import {a}from'./chunk-A5FBGRJA.js';import {a as a$2}from'./chunk-NMXGSVMD.js';import {b}from'./chunk-VN2MKTQO.js';import {q,r,s as s$1}from'./chunk-RGNCL5OB.js';import {h}from'./chunk-EFHSRPW7.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {u,t}from'./chunk-VQZ5PI5J.js';import {t as t$1,s}from'./chunk-ODK4LCEL.js';import {promises}from'fs';import {randomUUID}from'crypto';import n from'path';import p from'chalk';import le from'fs-extra';import N from'ora';import {execa}from'execa';var de=3e4,me=45e3;async function ge(e){try{let r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,env:a$1()});return r.stdout.trim()?n.resolve(e,r.stdout.trim()):null}catch{return null}}async function re(e,r,t){if(await ge(e)){r.warn("Git initialization skipped because target is already inside a git worktree");return}r.start("Initializing git repository...");try{await execa("git",["init"],{cwd:e,env:a$1()}),await execa("git",["add","."],{cwd:e,env:a$1()}),await execa("git",["-c","user.name=Workspai","-c","user.email=workspai@localhost","commit","-m",t],{cwd:e,env:a$1()}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}function G(e){let r=a(e.path),t=Array.isArray(e.projects)?e.projects:[],o=[],a$1=new Set;for(let s of t){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let i=a(s.path);a$1.has(i)||(a$1.add(i),o.push({name:s.name,path:i}));}return {name:e.name,path:r,mode:e.mode,projects:o}}function I(e){let r=[],t=new Set;for(let o of e.workspaces||[]){if(!o||typeof o.name!="string"||typeof o.path!="string")continue;let a=G(o);t.has(a.path)||(t.add(a.path),r.push(a));}return {workspaces:r}}async function ue(e){let r;try{r=await promises.readFile(e,"utf8");}catch(t){if(t.code==="ENOENT")return {workspaces:[]};throw t}try{let t=JSON.parse(r);if(!t||!Array.isArray(t.workspaces))throw new Error("missing workspaces array");return I(t)}catch(t){throw new Error(`Workspace registry is invalid: ${e}`,{cause:t})}}async function ke(e){let r;try{r=await promises.readFile(e,"utf8");}catch(o){if(o.code==="ENOENT")return {workspaces:[]};throw o}let t;try{t=JSON.parse(r);}catch(o){throw new Error(`Workspace registry is invalid: ${e}`,{cause:o})}if(!t||typeof t!="object"||!Array.isArray(t.workspaces))throw new Error(`Workspace registry is invalid: ${e}`);for(let o of t.workspaces)if(!o||typeof o.name!="string"||typeof o.path!="string"||o.mode!==void 0&&typeof o.mode!="string"||o.projects!==void 0&&!Array.isArray(o.projects)||Array.isArray(o.projects)&&o.projects.some(a=>!a||typeof a.name!="string"||typeof a.path!="string"))throw new Error(`Workspace registry contains an invalid entry: ${e}`);return I(t)}async function z(){let e={workspaces:[]},r=new Set;for(let t of s$1()){let o=await ue(t);for(let a of o.workspaces)r.has(a.path)||(r.add(a.path),e.workspaces.push(a));}return e}async function oe(e=s$1()){let r={workspaces:[]},t=new Set;for(let o of e){let a=await ke(o);for(let s of a.workspaces)t.has(s.path)||(t.add(s.path),r.workspaces.push(s));}return r}function fe(e){let r=e?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}async function ae(e){try{await e.sync();}catch(r){if(!fe(r))throw r}}async function X(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${n.basename(e)}.`,a=Date.now();for(let i of await promises.readdir(t)){if(!i.startsWith(o)||!i.endsWith(".tmp"))continue;let c=n.join(t,i),d=await promises.stat(c).catch(()=>null);d&&a-d.mtimeMs>3e4&&await promises.rm(c,{force:true}).catch(()=>{});}let s=await promises.readFile(e,"utf8").catch(()=>null);if(s!==null){let i=false;try{let c=JSON.parse(s);i=Array.isArray(c.workspaces);}catch{i=false;}if(!i){let c=`${e}.corrupt-${Date.now()}`;await promises.copyFile(e,c);}}await se(e,`${JSON.stringify(I(r),null,2)}
1
+ import {c}from'./chunk-N4B2M44I.js';import {a}from'./chunk-A5FBGRJA.js';import {a as a$2}from'./chunk-NMXGSVMD.js';import {b}from'./chunk-VN2MKTQO.js';import {w,x,y}from'./chunk-6BO4QHKA.js';import {h}from'./chunk-EFHSRPW7.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {u,t}from'./chunk-VQZ5PI5J.js';import {t as t$1,s}from'./chunk-ODK4LCEL.js';import {promises}from'fs';import {randomUUID}from'crypto';import n from'path';import p from'chalk';import le from'fs-extra';import N from'ora';import {execa}from'execa';var de=3e4,me=45e3;async function ge(e){try{let r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,env:a$1()});return r.stdout.trim()?n.resolve(e,r.stdout.trim()):null}catch{return null}}async function re(e,r,t){if(await ge(e)){r.warn("Git initialization skipped because target is already inside a git worktree");return}r.start("Initializing git repository...");try{await execa("git",["init"],{cwd:e,env:a$1()}),await execa("git",["add","."],{cwd:e,env:a$1()}),await execa("git",["-c","user.name=Workspai","-c","user.email=workspai@localhost","commit","-m",t],{cwd:e,env:a$1()}),r.succeed("Git repository initialized");}catch{r.warn("Could not initialize git repository");}}function G(e){let r=a(e.path),t=Array.isArray(e.projects)?e.projects:[],o=[],a$1=new Set;for(let s of t){if(!s||typeof s.name!="string"||typeof s.path!="string")continue;let i=a(s.path);a$1.has(i)||(a$1.add(i),o.push({name:s.name,path:i}));}return {name:e.name,path:r,mode:e.mode,projects:o}}function I(e){let r=[],t=new Set;for(let o of e.workspaces||[]){if(!o||typeof o.name!="string"||typeof o.path!="string")continue;let a=G(o);t.has(a.path)||(t.add(a.path),r.push(a));}return {workspaces:r}}async function ue(e){let r;try{r=await promises.readFile(e,"utf8");}catch(t){if(t.code==="ENOENT")return {workspaces:[]};throw t}try{let t=JSON.parse(r);if(!t||!Array.isArray(t.workspaces))throw new Error("missing workspaces array");return I(t)}catch(t){throw new Error(`Workspace registry is invalid: ${e}`,{cause:t})}}async function ke(e){let r;try{r=await promises.readFile(e,"utf8");}catch(o){if(o.code==="ENOENT")return {workspaces:[]};throw o}let t;try{t=JSON.parse(r);}catch(o){throw new Error(`Workspace registry is invalid: ${e}`,{cause:o})}if(!t||typeof t!="object"||!Array.isArray(t.workspaces))throw new Error(`Workspace registry is invalid: ${e}`);for(let o of t.workspaces)if(!o||typeof o.name!="string"||typeof o.path!="string"||o.mode!==void 0&&typeof o.mode!="string"||o.projects!==void 0&&!Array.isArray(o.projects)||Array.isArray(o.projects)&&o.projects.some(a=>!a||typeof a.name!="string"||typeof a.path!="string"))throw new Error(`Workspace registry contains an invalid entry: ${e}`);return I(t)}async function z(){let e={workspaces:[]},r=new Set;for(let t of y()){let o=await ue(t);for(let a of o.workspaces)r.has(a.path)||(r.add(a.path),e.workspaces.push(a));}return e}async function oe(e=y()){let r={workspaces:[]},t=new Set;for(let o of e){let a=await ke(o);for(let s of a.workspaces)t.has(s.path)||(t.add(s.path),r.workspaces.push(s));}return r}function fe(e){let r=e?.code;return process.platform==="win32"&&(r==="EPERM"||r==="EINVAL"||r==="ENOSYS")}async function ae(e){try{await e.sync();}catch(r){if(!fe(r))throw r}}async function X(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${n.basename(e)}.`,a=Date.now();for(let i of await promises.readdir(t)){if(!i.startsWith(o)||!i.endsWith(".tmp"))continue;let c=n.join(t,i),d=await promises.stat(c).catch(()=>null);d&&a-d.mtimeMs>3e4&&await promises.rm(c,{force:true}).catch(()=>{});}let s=await promises.readFile(e,"utf8").catch(()=>null);if(s!==null){let i=false;try{let c=JSON.parse(s);i=Array.isArray(c.workspaces);}catch{i=false;}if(!i){let c=`${e}.corrupt-${Date.now()}`;await promises.copyFile(e,c);}}await se(e,`${JSON.stringify(I(r),null,2)}
2
2
  `);}async function se(e,r){let t=n.dirname(e);await promises.mkdir(t,{recursive:true});let o=`${e}.${process.pid}.${randomUUID()}.tmp`;try{await promises.writeFile(o,r);let a=await promises.open(o,"r");try{await ae(a);}finally{await a.close();}try{await promises.rename(o,e);}catch(s){let i=s.code;if(i!=="EEXIST"&&i!=="EPERM")throw s;await le.move(o,e,{overwrite:true});}}finally{await promises.rm(o,{force:true}).catch(()=>{});}}async function Z(e){try{return {exists:true,content:await promises.readFile(e)}}catch(r){if(r.code==="ENOENT")return {exists:false};throw r}}async function ee(e,r){if(!r.exists){await promises.rm(e,{force:true});return}await se(e,r.content);}async function we(e,r){let t=n.join(e,"workspaces.json.lock"),o=randomUUID();await promises.mkdir(e,{recursive:true});let a=Date.now(),s;for(;!s;)try{s=await promises.open(t,"wx"),await s.writeFile(`${JSON.stringify({pid:process.pid,lockId:o,createdAt:new Date().toISOString()})}
3
- `),await ae(s);}catch(i){if(i.code!=="EEXIST")throw i;let c=await promises.stat(t).catch(()=>null);if(c&&Date.now()-c.mtimeMs>de){let d=await promises.readFile(t,"utf8").then(g=>JSON.parse(g)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(g){f=g.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>me)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(c=>JSON.parse(c).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function S(e){let r$1=q(),t=n.join(r$1,"workspaces.json"),o=n.join(r(),"workspaces.json"),a=[...new Set(s$1())];return we(r$1,async()=>{let[s,i]=await Promise.all([Z(t),Z(o)]),c=await oe(a);await e(c);let d=I(c);try{await X(t,d),await X(o,d);}catch(u){let g=(await Promise.allSettled([ee(t,s),ee(o,i)])).filter(k=>k.status==="rejected").map(k=>k.reason);throw g.length>0?new AggregateError([u,...g],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ie(e,r){let t=a(e);await S(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function He(e){let r=a(e),o=(await oe()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ke(e,r){let t=a(e);await S(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=G(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function qe(e){let r=a(e);await S(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function he(e,r){try{await ie(e,r);}catch{console.warn(p.gray("Note: Could not register workspace in shared registry"));}}async function Qe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await z(),s=a$1.workspaces.find(k=>k.path===t);if(!s){if(await he(t,n.basename(n.resolve(e))),a$1=await z(),s=a$1.workspaces.find(k=>k.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,c=0,d=[],u$1=[],f=[e],g=new Set;for(;f.length>0;){let k=f.shift();if(!k||g.has(k))continue;g.add(k);let w=await promises.readdir(k,{withFileTypes:true});for(let h of w){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let v=n.join(k,h.name),y=a(v);try{let x=false;for(let P of [...u(y,"context.json"),...u(y,"project.json")])try{await promises.access(P),x=true;break}catch{}if(x){let P=n.basename(y),m=s.projects.some($=>$.path===y);u$1.push({name:P,path:y}),m?c++:(s.projects.push({name:P,path:y}),i++,d.push(y),r||console.log(`\u2714 Added: ${n.relative(e,y)}`));continue}}catch{}f.push(v);}}return await S(k=>{let w=k.workspaces.find(y=>y.path===t);if(!w)return;let h=`${t}${n.sep}`,v=(w.projects||[]).filter(y=>y.path!==t&&!y.path.startsWith(h));w.projects=G({...w,projects:[...v,...u$1]}).projects;}),i>0?r||console.log(`
3
+ `),await ae(s);}catch(i){if(i.code!=="EEXIST")throw i;let c=await promises.stat(t).catch(()=>null);if(c&&Date.now()-c.mtimeMs>de){let d=await promises.readFile(t,"utf8").then(g=>JSON.parse(g)).catch(()=>null),u=Number(d?.pid),f=false;if(Number.isInteger(u)&&u>0)try{process.kill(u,0),f=true;}catch(g){f=g.code==="EPERM";}if(!f){await promises.rm(t,{force:true}).catch(()=>{});continue}}if(Date.now()-a>me)throw new Error(`Timed out waiting for workspace registry lock: ${t}`);await new Promise(d=>setTimeout(d,25));}try{return await r()}finally{await s.close().catch(()=>{}),await promises.readFile(t,"utf8").then(c=>JSON.parse(c).lockId===o).catch(()=>false)&&await promises.rm(t,{force:true}).catch(()=>{});}}async function S(e){let r=w(),t=n.join(r,"workspaces.json"),o=n.join(x(),"workspaces.json"),a=[...new Set(y())];return we(r,async()=>{let[s,i]=await Promise.all([Z(t),Z(o)]),c=await oe(a);await e(c);let d=I(c);try{await X(t,d),await X(o,d);}catch(u){let g=(await Promise.allSettled([ee(t,s),ee(o,i)])).filter(k=>k.status==="rejected").map(k=>k.reason);throw g.length>0?new AggregateError([u,...g],"Workspace registry transaction failed and could not be fully restored"):u}return d})}async function ie(e,r){let t=a(e);await S(o=>{let a=o.workspaces.find(s=>s.path===t);if(a){a.name=r,a.mode=a.mode||"full",a.projects=Array.isArray(a.projects)?a.projects:[];return}o.workspaces.push({name:r,path:t,mode:"full",projects:[]});});}async function He(e){let r=a(e),o=(await oe()).workspaces.find(a=>a.path===r);return o?{...o,projects:o.projects.map(a=>({...a}))}:null}async function Ke(e,r){let t=a(e);await S(o=>{let a=o.workspaces.findIndex(i=>i.path===t);if(!r){a>=0&&o.workspaces.splice(a,1);return}let s=G(r);a>=0?o.workspaces[a]=s:o.workspaces.push(s);});}async function qe(e){let r=a(e);await S(t=>{t.workspaces=t.workspaces.filter(o=>o.path!==r);});}async function he(e,r){try{await ie(e,r);}catch{console.warn(p.gray("Note: Could not register workspace in shared registry"));}}async function Qe(e,r=false){let t=a(e),o={workspacePath:t,workspaceFound:false,added:[],skipped:0};try{let a$1=await z(),s=a$1.workspaces.find(k=>k.path===t);if(!s){if(await he(t,n.basename(n.resolve(e))),a$1=await z(),s=a$1.workspaces.find(k=>k.path===t),!s)return r||console.log("\u26A0\uFE0F Workspace could not be registered in registry"),o;r||console.log("\u2714 Registered workspace in shared registry");}Array.isArray(s.projects)||(s.projects=[]);let i=0,c=0,d=[],u$1=[],f=[e],g=new Set;for(;f.length>0;){let k=f.shift();if(!k||g.has(k))continue;g.add(k);let w=await promises.readdir(k,{withFileTypes:true});for(let h of w){if(!h.isDirectory()||h.name.startsWith(".")||["node_modules","dist","build","target","coverage","htmlcov"].includes(h.name))continue;let v=n.join(k,h.name),y=a(v);try{let x=false;for(let P of [...u(y,"context.json"),...u(y,"project.json")])try{await promises.access(P),x=true;break}catch{}if(x){let P=n.basename(y),m=s.projects.some($=>$.path===y);u$1.push({name:P,path:y}),m?c++:(s.projects.push({name:P,path:y}),i++,d.push(y),r||console.log(`\u2714 Added: ${n.relative(e,y)}`));continue}}catch{}f.push(v);}}return await S(k=>{let w=k.workspaces.find(y=>y.path===t);if(!w)return;let h=`${t}${n.sep}`,v=(w.projects||[]).filter(y=>y.path!==t&&!y.path.startsWith(h));w.projects=G({...w,projects:[...v,...u$1]}).projects;}),i>0?r||console.log(`
4
4
  \u2705 Synced ${i} project(s) to registry`):r||console.log(`
5
- \u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-ZFSFWAW3.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
5
+ \u2705 All projects already registered (${c} found)`),{workspacePath:t,workspaceFound:true,added:d,skipped:c}}catch(a){return r||console.error("\u274C Failed to sync projects:",a.message),o}}async function ye(e,r,t){let o=a(e),a$1=a(t);await S(s=>{let i=s.workspaces.find(u=>u.path===o);if(!i)throw new Error(`Workspace is not registered: ${o}`);i.projects=Array.isArray(i.projects)?i.projects:[];let c=i.projects.findIndex(u=>u.path===a$1||u.name===r),d={name:r,path:a$1};c>=0?i.projects[c]=d:i.projects.push(d);});}async function Xe(e,r,t){try{await ye(e,r,t);}catch{}}async function Ze(e,r){let t=N("Creating Workspai workspace...").start();try{await promises.mkdir(e,{recursive:true}),await promises.mkdir(n.join(e,".workspai"),{recursive:true});let o={workspace_name:r.name,author:r.author,rapidkit_version:h(),created_at:new Date().toISOString(),type:"workspace"};await promises.writeFile(n.join(e,".workspai","config.json"),JSON.stringify(o,null,2));let{syncWorkspaceFoundationFiles:a}=await import('./create-YPAZJYCE.js');await a(e,{workspaceName:r.name,installMethod:"venv",writeMarker:true,writeGitignore:false,onlyIfMissing:true});let s=$e();await promises.writeFile(n.join(e,"rapidkit"),s),await promises.chmod(n.join(e,"rapidkit"),493);let i=je();await promises.writeFile(n.join(e,"rapidkit.cmd"),i);let c=ve(r.name);await promises.writeFile(n.join(e,"README.md"),c),await promises.writeFile(n.join(e,".gitignore"),`# Workspai workspace
6
6
  .env
7
7
  .env.*
8
8
  !.env.example
@@ -17,7 +17,7 @@ Thumbs.db
17
17
 
18
18
  # Logs
19
19
  *.log
20
- `),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-Y3ET36NH.js');await u(e),console.log(`
20
+ `),await _e(e),t.succeed("Workspace created!"),r.skipGit||await re(e,N(),"Initial commit: Workspai workspace"),await ie(e,r.name);let{publishWorkspaceRegistrySummary:u}=await import('./workspace-registry-summary-M4WMFDQ4.js');await u(e),console.log(`
21
21
  ${p.green("\u2728 Workspai workspace created successfully!")}
22
22
 
23
23
  ${p.bold("\u{1F4C2} Workspace structure:")}
@@ -651,7 +651,7 @@ ${p.bold("\u{1F310} API endpoints:")}
651
651
  http://localhost:8000/examples/notes # Example API
652
652
 
653
653
  ${p.gray("\u{1F4A1} Tip: Install globally (npm i -g workspai) to use without npx")}
654
- `);}catch(s){throw a.fail(`Failed to create ${o} project`),s}}async function ne(e,r,t){let o=await promises.readdir(e,{withFileTypes:true});for(let a of o){let s=n.join(e,a.name),i=a.name.replace(/\.j2$/,""),c=n.join(r,i);if(a.isDirectory())await promises.mkdir(c,{recursive:true}),await ne(s,c,t);else {let d=await promises.readFile(s,"utf-8");a.name.endsWith(".j2")&&(d=Pe(d,t)),await promises.writeFile(c,d),(i==="rapidkit"||i==="activate"||i.endsWith(".py")&&(c.includes(".workspai")||c.includes(".rapidkit")))&&await promises.chmod(c,493);}}}function Pe(e,r){let t=e;for(let[o,a]of Object.entries(r)){let s=new RegExp(`\\{\\{\\s*${o}\\s*\\}\\}`,"g");t=t.replace(s,String(a));let i=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(i,(u,f,g)=>String(a).replace(new RegExp(f,"g"),g));let c=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(c,String(a).toLowerCase());let d=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(d,(u,f,g)=>String(a).replace(new RegExp(f,"g"),g).toLowerCase());}return t}async function tt(e={}){let r=q(),t=n.join(r,"workspaces.json"),o=await z();if(o.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:false}},null,2));return}console.log(p.yellow(`
654
+ `);}catch(s){throw a.fail(`Failed to create ${o} project`),s}}async function ne(e,r,t){let o=await promises.readdir(e,{withFileTypes:true});for(let a of o){let s=n.join(e,a.name),i=a.name.replace(/\.j2$/,""),c=n.join(r,i);if(a.isDirectory())await promises.mkdir(c,{recursive:true}),await ne(s,c,t);else {let d=await promises.readFile(s,"utf-8");a.name.endsWith(".j2")&&(d=Pe(d,t)),await promises.writeFile(c,d),(i==="rapidkit"||i==="activate"||i.endsWith(".py")&&(c.includes(".workspai")||c.includes(".rapidkit")))&&await promises.chmod(c,493);}}}function Pe(e,r){let t=e;for(let[o,a]of Object.entries(r)){let s=new RegExp(`\\{\\{\\s*${o}\\s*\\}\\}`,"g");t=t.replace(s,String(a));let i=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\}\\}`,"g");t=t.replace(i,(u,f,g)=>String(a).replace(new RegExp(f,"g"),g));let c=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(c,String(a).toLowerCase());let d=new RegExp(`\\{\\{\\s*${o}\\s*\\|\\s*replace\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*['"]([^'"]*)['"]\\s*\\)\\s*\\|\\s*lower\\s*\\}\\}`,"g");t=t.replace(d,(u,f,g)=>String(a).replace(new RegExp(f,"g"),g).toLowerCase());}return t}async function tt(e={}){let r=w(),t=n.join(r,"workspaces.json"),o=await z();if(o.workspaces.length===0){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:false}},null,2));return}console.log(p.yellow(`
655
655
  \u26A0\uFE0F No workspaces registered yet.
656
656
  `)),console.log(p.gray(`Create a workspace with: npx workspai <workspace-name>
657
657
  `));return}try{let a=o;if(!a||typeof a!="object"||!Array.isArray(a.workspaces)){if(e.json){console.log(JSON.stringify({schemaVersion:"rapidkit-workspace-list-v1",registryPath:t,workspaces:[],summary:{total:0,missing:0,registryExists:true,registryValid:false},error:{code:"workspace.registry.invalid",message:"Workspace registry is invalid."}},null,2));return}console.log(p.yellow(`
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-HCFOVANQ.js';import {n,h,i}from'./chunk-LARREYZN.js';import {B}from'./chunk-E42IFQFR.js';import {d as d$1}from'./chunk-ROOPODG6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {d,c}from'./chunk-EWZZUQBR.js';import {p,t}from'./chunk-ODK4LCEL.js';import u from'path';import {createHash}from'crypto';import {createReadStream}from'fs';import {execFile}from'child_process';import {promisify}from'util';import _ from'fs-extra';import {parseAllDocuments}from'yaml';var Bs=p.knowledgeGraph;function Ls(e,t){if(e.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e.source.kind}).`);if(e.source.artifact!==p.model)throw new Error(`Workspace knowledge graph source artifact is ${e.source.artifact}; expected ${p.model}.`);if(e.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e.source.hashAlgorithm}; expected sha256.`);let s=d(t);if(e.source.hash!==s)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e.workspace.name!==t.workspace.name||(e.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let o=n(t);if(!o)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let i=n=>({...n,generatedAt:"<ignored>"});if(c(i(e.projectTopology))!==c(i(o)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}function jt(e){return {path:e.path,...e.runtime!==void 0?{runtime:e.runtime}:{},...e.runtimeCandidates!==void 0?{runtimeCandidates:e.runtimeCandidates}:{},...e.framework!==void 0?{framework:e.framework}:{},...e.kit!==void 0?{kit:e.kit}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.category!==void 0?{category:e.category}:{},...e.governance?{governanceCiStatus:e.governance.ci.status,governanceReleaseStatus:e.governance.release.status,governanceOwnershipStatus:e.governance.ownership.status,governanceProviders:[e.governance.ci.provider,e.governance.release.provider,e.governance.ownership.provider].filter(t=>!!t)}:{}}}var Dt=5e5,qt=2e6;function ke(e,t){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let s=process.env[t];if(!s)return;let o=Number.parseInt(s,10);return Number.isFinite(o)&&o>0?o:void 0}var It=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","venv","vendor","node_modules","dist","build","target","coverage",".next",".turbo",".cache",".vscode-test","graphify-out",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".gradle","fixture","fixtures","__fixtures__","testdata"]),Et=new Set(["AGENTS.md","CLAUDE.md","GEMINI.md","QWEN.md"]),Ct=new Set([".workspai-workspace"]),Zt=[/(?:^|\/)\.agents\/skills\/workspai-[^/]+\//u,/(?:^|\/)\.amazonq\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.claude\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.cursor\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.grok\/(?:rules|skills)\/workspai-[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/agents\/workspai-[^/]+\.agent\.md$/u,/(?:^|\/)\.github\/(?:instructions|prompts|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/copilot-instructions\.md$/u,/(?:^|\/)\.windsurf\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.windsurfrules$/u,/(?:^|\/)\.vscode\/(?:workspai|rapidkit)-agent-hooks\.json$/u];function Ke(e,t){let s=D(u.relative(e,t));return Et.has(u.posix.basename(s))||Ct.has(u.posix.basename(s))||Zt.some(o=>o.test(s))}var Ht=new Set(["test","tests","spec","specs","e2e","integration","integration-tests","integration_tests","__tests__","fixture","fixtures","__fixtures__","testdata"]),Ut=new Set(["examples","samples","worked"]);function Ge(e,t){let s=u.relative(e,t).split(u.sep).map(i=>i.toLowerCase()),o=u.basename(t).toLowerCase();return s.some(i=>Ht.has(i))||/(?:\.test|\.spec|_test)\.[a-z0-9]+$/i.test(o)||/^test_.+\.[a-z0-9]+$/i.test(o)||/(?:tests?|specs?)\.(?:cs|fs|vb|java|kt|kts)$/i.test(o)}function De(e,t){return u.relative(e,t).split(u.sep).map(s=>s.toLowerCase()).some(s=>Ut.has(s))}function ee(e,t){return Ge(e,t)||De(e,t)}function he(e,t){return u.relative(e,t).split(u.sep).some(s=>s.toLowerCase()==="generated")}var Le=new Set(["package.json","pyproject.toml","requirements.txt","Pipfile","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","CMakeLists.txt","deno.json","deno.jsonc","project.clj","deps.edn","build.sbt","BUILD","BUILD.bazel","WORKSPACE.bazel"]),Jt=new Set([...Le,"go.work","go.work.sum"]),Vt=new Set(["get","put","post","delete","options","head","patch","trace"]),te=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".cjs",".cts",".js",".jsx",".kt",".kts",".mjs",".mts",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]),nt=new Set([...te,".adb",".ads",".asm",".bash",".bat",".cl",".cob",".cu",".cuh",".erl",".f",".f03",".f08",".f77",".f90",".f95",".fish",".for",".gql",".graphql",".groovy",".hip",".hrl",".hs",".hlsl",".jl",".ll",".m",".metal",".mir",".mlir",".mm",".nim",".pas",".pl",".pm",".proto",".ps1",".s",".sh",".sol",".sql",".sv",".td",".thrift",".v",".vhd",".vhdl",".zig",".zsh"]);function J(e,t){let s=u.extname(e).toLowerCase();return s===".h"&&t==="cpp"?"cpp":{".c":"c",".adb":"ada",".ads":"ada",".asm":"assembly",".bash":"shell",".bat":"batch",".cc":"cpp",".cl":"opencl",".cob":"cobol",".cpp":"cpp",".cs":"csharp",".cu":"cuda",".cuh":"cuda",".dart":"dart",".erl":"erlang",".ex":"elixir",".exs":"elixir",".f":"fortran",".f03":"fortran",".f08":"fortran",".f77":"fortran",".f90":"fortran",".f95":"fortran",".fish":"shell",".for":"fortran",".gql":"graphql",".go":"go",".graphql":"graphql",".groovy":"groovy",".h":"c",".hip":"hip",".hpp":"cpp",".hrl":"erlang",".hs":"haskell",".hlsl":"hlsl",".java":"java",".jl":"julia",".cjs":"javascript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".mts":"typescript",".php":"php",".py":"python",".r":"r",".rb":"ruby",".rs":"rust",".scala":"scala",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescript",".vue":"vue",".clj":"clojure",".cljs":"clojure",".fs":"fsharp",".fsx":"fsharp",".lua":"lua",".ll":"llvm-ir",".m":"objective-c",".metal":"metal",".mir":"llvm-mir",".mlir":"mlir",".mm":"objective-cpp",".nim":"nim",".pas":"pascal",".pl":"perl",".pm":"perl",".proto":"protobuf",".ps1":"powershell",".s":"assembly",".sh":"shell",".sol":"solidity",".sql":"sql",".sv":"systemverilog",".td":"tablegen",".thrift":"thrift",".v":"verilog",".vb":"visual-basic",".vhd":"vhdl",".vhdl":"vhdl",".zig":"zig",".zsh":"shell"}[s]??s.slice(1)}var Yt=new Set(["external","third_party","third-party","vendor","vendors","vendored"]),Qt=new Set(["app","apps","cli","cmd","core","extensions","internal","lib","packages","services","src"]);function at(e,t){let o=D(u.relative(t,e)).split("/").filter(Boolean),i=o[0]?.toLowerCase()??"";return (o.some(l=>Yt.has(l.toLowerCase()))?1e3:0)+(Qt.has(i)?-100:0)+Math.min(o.length,20)}function Xt(e,t,s){if(e.length<=t)return [...e];let o=[...e].sort((c,r)=>at(c,s)-at(r,s)||c.localeCompare(r)),i=new Map;for(let c of o){let r=J(c),d=i.get(r)??[];d.push(c),i.set(r,d);}let n=new Set,l=Math.max(1,Math.min(25,Math.floor(t/Math.max(i.size,1))));for(let c of [...i.values()])for(let r of c.slice(0,l))n.add(r);for(let c of o){if(n.size>=t)break;n.add(c);}return [...n].sort((c,r)=>c.localeCompare(r))}function eo(e,t){let s=D(u.relative(t,e)).split("/").filter(Boolean);if(s.length===0)return "<root>";let o=s[0].toLowerCase();return ["app","apps","cmd","components","crates","modules","packages","plugins","services"].includes(o)&&s[1]?`${o}/${s[1].toLowerCase()}`:o}function $e(e,t,s){let o=[...new Set(e)].sort((d,a)=>d.localeCompare(a));if(o.length<=t)return o;let i=new Set,n=o.filter(d=>Jt.has(u.basename(d))).sort((d,a)=>D(u.relative(s,d)).split("/").length-D(u.relative(s,a)).split("/").length||d.localeCompare(a));for(let d of n){if(i.size>=t)break;i.add(d);}let l=new Map;for(let d of o){if(i.has(d))continue;let a=`${eo(d,s)}\0${J(d)}`,p=l.get(a)??[];p.push(d),l.set(a,p);}let c=[...l.entries()].sort(([d],[a])=>d.localeCompare(a)),r=0;for(;i.size<t;){let d=false;for(let[,a]of c){let p=a[r];if(p&&(i.add(p),d=true,i.size>=t))break}if(!d)break;r+=1;}return [...i].sort((d,a)=>d.localeCompare(a))}function to(e){let t=Math.max(0,e.eligibleFiles),s=Math.min(25e3,Math.max(5e3,Math.ceil(t*.2))),o=Math.max(100,Math.min(e.deepOverride??s,Math.max(t,100),1e5)),i=Math.min(1e5,Math.max(25e3,o*4,Math.ceil(t*.6))),n=Math.max(o,Math.min(e.semanticOverride??i,Math.max(t,o),25e4)),l=Math.min(2e4,Math.max(2e3,Math.ceil(Math.min(t,o)*.25))),c=Math.max(100,Math.min(e.sourceOverride??l,o,5e4));return {semanticFileBudget:n,deepFileBudget:o,sourceExtractionFileBudget:c}}function Oe(e,t,s){let o=[],i=e.split(/\r?\n/);for(let n=0;n<i.length&&o.length<s;n+=1)for(let l of t){let r=i[n].match(l.pattern)?.[1]?.trim();if(r){o.push({name:r,line:n+1,detail:l.detail});break}}return o}var oo=[{pattern:/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,detail:"function"},{pattern:/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface|enum|type)\s+([A-Za-z_$][\w$]*)/,detail:"type"},{pattern:/^\s*(?:export\s+)?(?:declare\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/,detail:"value"},{pattern:/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*class\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*type\s+([A-Za-z_]\w*)\s+/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+)*(?:class|interface|record|enum)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public|protected|internal)\s+(?:(?:static|virtual|override|abstract|async|sealed|final|synchronized|native|unsafe|partial|extern|new)\s+)*(?:<[^>]+>\s*)?[A-Za-z_$][\w$<>,.?\[\]: ]*\s+([A-Za-z_$][\w$]*)\s*\(/,detail:"method"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|trait|enum|type)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+)?function\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:class|module|struct|protocol|mixin)\s+([A-Za-z_]\w*)/,detail:"type"}],Rt=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"}],St=[{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"}],so=[{pattern:/^\s*#\s*include\s*["<]([^">]+)[">]/,detail:"include"}],io=[{pattern:/^\s*use\s+([A-Za-z0-9_:*.-]+)/,detail:"use"}],ro=[{pattern:/^\s*import\s+(?:static\s+)?([A-Za-z0-9_.*]+)\s*;?/,detail:"import"}],no=[{pattern:/^\s*(?:global\s+)?using\s+([A-Za-z0-9_.]+)/,detail:"using"}],ao=[{pattern:/^\s*import\s+(?:[A-Za-z0-9_.]+\s+)?["']([^"']+)["']/,detail:"import"}],At=[{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}],co=[{pattern:/^\s*use\s+([A-Za-z0-9_\\]+)/,detail:"use"}],lo=[{pattern:/^\s*(?:alias|import|require|use)\s+([A-Za-z0-9_.]+)/,detail:"import"}],po=[{pattern:/^\s*import\s+["']([^"']+)["']/,detail:"import"}],uo=[{pattern:/\brequire\s*\(?\s*["']([^"']+)["']/,detail:"require"}],fo=[{pattern:/^\s*(?:library|require)\s*\(\s*["']?([^"')\s]+)["']?/,detail:"import"}],go=[...Rt,...St,{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},...At];function mo(e){let t=u.extname(e).toLowerCase();return [".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx",".vue",".svelte"].includes(t)?Rt:t===".py"?St:[".c",".cc",".cpp",".h",".hpp"].includes(t)?so:t===".rs"?io:[".java",".kt",".kts",".scala"].includes(t)?ro:[".cs",".fs",".fsx",".vb"].includes(t)?no:t===".go"?ao:t===".rb"?At:t===".php"?co:[".ex",".exs"].includes(t)?lo:t===".dart"?po:t===".lua"?uo:t===".r"?fo:go}function ho(e,t,s,o,i){let n=u.extname(e).toLowerCase()===".py",l=[];if(n){let r=t.match(/^\.+/)?.[0].length??0,d=r>0?u.dirname(e):u.resolve(o??"");for(let p=1;p<r;p+=1)d=u.dirname(d);let a=t.slice(r).replace(/\./g,u.sep);l.push(a?u.join(d,a):d);}else if(t.startsWith("."))l.push(u.resolve(u.dirname(e),t));else if(i==="include")l.push(u.resolve(u.dirname(e),t)),o&&l.push(u.resolve(o,t));else return null;let c=new Set;for(let r of l){c.add(r);let d=u.extname(r).toLowerCase(),a=te.has(d);if(n&&(c.add(`${r}.py`),c.add(u.join(r,"__init__.py"))),a){let p=r.slice(0,-d.length);if([".js",".jsx",".mjs"].includes(d))for(let f of [".ts",".tsx",".js",".jsx",".mjs"])c.add(`${p}${f}`);}else for(let p of te)c.add(`${r}${p}`),c.add(u.join(r,`index${p}`));}return [...c].find(r=>s.has(u.resolve(r)))??null}function vo(e,t){let s=t.trimStart(),o=u.extname(e).toLowerCase();return [".py",".rb",".sh",".bash",".zsh"].includes(o)?s.startsWith("#"):[".sql",".lua",".hs"].includes(o)?s.startsWith("--"):s.startsWith("//")||s.startsWith("/*")||s.startsWith("*")}function yo(e,t){if(u.extname(e).toLowerCase()!==".py")return t;let s=null;return t.split(/\r?\n/).map(o=>{let i=0,n="";for(;i<o.length;){if(s){let a=o.indexOf(s,i);if(a<0)return n;i=a+3,s=null;continue}let l=o.indexOf("'''",i),c=o.indexOf('"""',i),r=o.indexOf("#",i),d=l<0?c:c<0?l:Math.min(l,c);if(r>=0&&(d<0||r<d)){n+=o.slice(i,r);break}if(d<0){n+=o.slice(i);break}n+=o.slice(i,d),s=o.startsWith("'''",d)?"'''":'"""',i=d+3;}return n}).join(`
1
+ import {a}from'./chunk-HCFOVANQ.js';import {n,h,i}from'./chunk-SEZTSMRR.js';import {B}from'./chunk-O3TVVQ6X.js';import {d as d$1}from'./chunk-ROOPODG6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {d,c}from'./chunk-EWZZUQBR.js';import {p,t}from'./chunk-ODK4LCEL.js';import u from'path';import {createHash}from'crypto';import {createReadStream}from'fs';import {execFile}from'child_process';import {promisify}from'util';import _ from'fs-extra';import {parseAllDocuments}from'yaml';var Bs=p.knowledgeGraph;function Ls(e,t){if(e.source.kind!=="workspace-model")throw new Error(`Workspace knowledge graph is not bound to the canonical workspace model (source: ${e.source.kind}).`);if(e.source.artifact!==p.model)throw new Error(`Workspace knowledge graph source artifact is ${e.source.artifact}; expected ${p.model}.`);if(e.source.hashAlgorithm!=="sha256")throw new Error(`Workspace knowledge graph source hash algorithm is ${e.source.hashAlgorithm}; expected sha256.`);let s=d(t);if(e.source.hash!==s)throw new Error("Workspace knowledge graph is stale: its source hash does not match the canonical workspace model.");if(e.workspace.name!==t.workspace.name||(e.workspace.profile??void 0)!==(t.workspace.profile??void 0))throw new Error("Workspace knowledge graph identity does not match the canonical workspace model.");let o=n(t);if(!o)throw new Error("Canonical workspace model has no project topology for the workspace knowledge graph.");let i=n=>({...n,generatedAt:"<ignored>"});if(c(i(e.projectTopology))!==c(i(o)))throw new Error("Workspace knowledge graph project topology does not match the canonical workspace model.")}function jt(e){return {path:e.path,...e.runtime!==void 0?{runtime:e.runtime}:{},...e.runtimeCandidates!==void 0?{runtimeCandidates:e.runtimeCandidates}:{},...e.framework!==void 0?{framework:e.framework}:{},...e.kit!==void 0?{kit:e.kit}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.category!==void 0?{category:e.category}:{},...e.governance?{governanceCiStatus:e.governance.ci.status,governanceReleaseStatus:e.governance.release.status,governanceOwnershipStatus:e.governance.ownership.status,governanceProviders:[e.governance.ci.provider,e.governance.release.provider,e.governance.ownership.provider].filter(t=>!!t)}:{}}}var Dt=5e5,qt=2e6;function ke(e,t){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let s=process.env[t];if(!s)return;let o=Number.parseInt(s,10);return Number.isFinite(o)&&o>0?o:void 0}var It=new Set([".git",".hg",".svn",".workspai",".rapidkit",".venv","venv","vendor","node_modules","dist","build","target","coverage",".next",".turbo",".cache",".vscode-test","graphify-out",".pytest_cache",".mypy_cache",".ruff_cache",".tox",".gradle","fixture","fixtures","__fixtures__","testdata"]),Et=new Set(["AGENTS.md","CLAUDE.md","GEMINI.md","QWEN.md"]),Ct=new Set([".workspai-workspace"]),Zt=[/(?:^|\/)\.agents\/skills\/workspai-[^/]+\//u,/(?:^|\/)\.amazonq\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.claude\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.cursor\/(?:rules|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.grok\/(?:rules|skills)\/workspai-[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/agents\/workspai-[^/]+\.agent\.md$/u,/(?:^|\/)\.github\/(?:instructions|prompts|skills)\/(?:workspai-|rapidkit-)[^/]+(?:\/|$)/u,/(?:^|\/)\.github\/copilot-instructions\.md$/u,/(?:^|\/)\.windsurf\/rules\/workspai-[^/]+\.md$/u,/(?:^|\/)\.windsurfrules$/u,/(?:^|\/)\.vscode\/(?:workspai|rapidkit)-agent-hooks\.json$/u];function Ke(e,t){let s=D(u.relative(e,t));return Et.has(u.posix.basename(s))||Ct.has(u.posix.basename(s))||Zt.some(o=>o.test(s))}var Ht=new Set(["test","tests","spec","specs","e2e","integration","integration-tests","integration_tests","__tests__","fixture","fixtures","__fixtures__","testdata"]),Ut=new Set(["examples","samples","worked"]);function Ge(e,t){let s=u.relative(e,t).split(u.sep).map(i=>i.toLowerCase()),o=u.basename(t).toLowerCase();return s.some(i=>Ht.has(i))||/(?:\.test|\.spec|_test)\.[a-z0-9]+$/i.test(o)||/^test_.+\.[a-z0-9]+$/i.test(o)||/(?:tests?|specs?)\.(?:cs|fs|vb|java|kt|kts)$/i.test(o)}function De(e,t){return u.relative(e,t).split(u.sep).map(s=>s.toLowerCase()).some(s=>Ut.has(s))}function ee(e,t){return Ge(e,t)||De(e,t)}function he(e,t){return u.relative(e,t).split(u.sep).some(s=>s.toLowerCase()==="generated")}var Le=new Set(["package.json","pyproject.toml","requirements.txt","Pipfile","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts","composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","CMakeLists.txt","deno.json","deno.jsonc","project.clj","deps.edn","build.sbt","BUILD","BUILD.bazel","WORKSPACE.bazel"]),Jt=new Set([...Le,"go.work","go.work.sum"]),Vt=new Set(["get","put","post","delete","options","head","patch","trace"]),te=new Set([".c",".cc",".cpp",".cs",".dart",".ex",".exs",".go",".h",".hpp",".java",".cjs",".cts",".js",".jsx",".kt",".kts",".mjs",".mts",".php",".py",".r",".rb",".rs",".scala",".svelte",".swift",".ts",".tsx",".vue",".clj",".cljs",".fs",".fsx",".lua",".vb"]),nt=new Set([...te,".adb",".ads",".asm",".bash",".bat",".cl",".cob",".cu",".cuh",".erl",".f",".f03",".f08",".f77",".f90",".f95",".fish",".for",".gql",".graphql",".groovy",".hip",".hrl",".hs",".hlsl",".jl",".ll",".m",".metal",".mir",".mlir",".mm",".nim",".pas",".pl",".pm",".proto",".ps1",".s",".sh",".sol",".sql",".sv",".td",".thrift",".v",".vhd",".vhdl",".zig",".zsh"]);function J(e,t){let s=u.extname(e).toLowerCase();return s===".h"&&t==="cpp"?"cpp":{".c":"c",".adb":"ada",".ads":"ada",".asm":"assembly",".bash":"shell",".bat":"batch",".cc":"cpp",".cl":"opencl",".cob":"cobol",".cpp":"cpp",".cs":"csharp",".cu":"cuda",".cuh":"cuda",".dart":"dart",".erl":"erlang",".ex":"elixir",".exs":"elixir",".f":"fortran",".f03":"fortran",".f08":"fortran",".f77":"fortran",".f90":"fortran",".f95":"fortran",".fish":"shell",".for":"fortran",".gql":"graphql",".go":"go",".graphql":"graphql",".groovy":"groovy",".h":"c",".hip":"hip",".hpp":"cpp",".hrl":"erlang",".hs":"haskell",".hlsl":"hlsl",".java":"java",".jl":"julia",".cjs":"javascript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".kt":"kotlin",".kts":"kotlin",".mjs":"javascript",".mts":"typescript",".php":"php",".py":"python",".r":"r",".rb":"ruby",".rs":"rust",".scala":"scala",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescript",".vue":"vue",".clj":"clojure",".cljs":"clojure",".fs":"fsharp",".fsx":"fsharp",".lua":"lua",".ll":"llvm-ir",".m":"objective-c",".metal":"metal",".mir":"llvm-mir",".mlir":"mlir",".mm":"objective-cpp",".nim":"nim",".pas":"pascal",".pl":"perl",".pm":"perl",".proto":"protobuf",".ps1":"powershell",".s":"assembly",".sh":"shell",".sol":"solidity",".sql":"sql",".sv":"systemverilog",".td":"tablegen",".thrift":"thrift",".v":"verilog",".vb":"visual-basic",".vhd":"vhdl",".vhdl":"vhdl",".zig":"zig",".zsh":"shell"}[s]??s.slice(1)}var Yt=new Set(["external","third_party","third-party","vendor","vendors","vendored"]),Qt=new Set(["app","apps","cli","cmd","core","extensions","internal","lib","packages","services","src"]);function at(e,t){let o=D(u.relative(t,e)).split("/").filter(Boolean),i=o[0]?.toLowerCase()??"";return (o.some(l=>Yt.has(l.toLowerCase()))?1e3:0)+(Qt.has(i)?-100:0)+Math.min(o.length,20)}function Xt(e,t,s){if(e.length<=t)return [...e];let o=[...e].sort((c,r)=>at(c,s)-at(r,s)||c.localeCompare(r)),i=new Map;for(let c of o){let r=J(c),d=i.get(r)??[];d.push(c),i.set(r,d);}let n=new Set,l=Math.max(1,Math.min(25,Math.floor(t/Math.max(i.size,1))));for(let c of [...i.values()])for(let r of c.slice(0,l))n.add(r);for(let c of o){if(n.size>=t)break;n.add(c);}return [...n].sort((c,r)=>c.localeCompare(r))}function eo(e,t){let s=D(u.relative(t,e)).split("/").filter(Boolean);if(s.length===0)return "<root>";let o=s[0].toLowerCase();return ["app","apps","cmd","components","crates","modules","packages","plugins","services"].includes(o)&&s[1]?`${o}/${s[1].toLowerCase()}`:o}function $e(e,t,s){let o=[...new Set(e)].sort((d,a)=>d.localeCompare(a));if(o.length<=t)return o;let i=new Set,n=o.filter(d=>Jt.has(u.basename(d))).sort((d,a)=>D(u.relative(s,d)).split("/").length-D(u.relative(s,a)).split("/").length||d.localeCompare(a));for(let d of n){if(i.size>=t)break;i.add(d);}let l=new Map;for(let d of o){if(i.has(d))continue;let a=`${eo(d,s)}\0${J(d)}`,p=l.get(a)??[];p.push(d),l.set(a,p);}let c=[...l.entries()].sort(([d],[a])=>d.localeCompare(a)),r=0;for(;i.size<t;){let d=false;for(let[,a]of c){let p=a[r];if(p&&(i.add(p),d=true,i.size>=t))break}if(!d)break;r+=1;}return [...i].sort((d,a)=>d.localeCompare(a))}function to(e){let t=Math.max(0,e.eligibleFiles),s=Math.min(25e3,Math.max(5e3,Math.ceil(t*.2))),o=Math.max(100,Math.min(e.deepOverride??s,Math.max(t,100),1e5)),i=Math.min(1e5,Math.max(25e3,o*4,Math.ceil(t*.6))),n=Math.max(o,Math.min(e.semanticOverride??i,Math.max(t,o),25e4)),l=Math.min(2e4,Math.max(2e3,Math.ceil(Math.min(t,o)*.25))),c=Math.max(100,Math.min(e.sourceOverride??l,o,5e4));return {semanticFileBudget:n,deepFileBudget:o,sourceExtractionFileBudget:c}}function Oe(e,t,s){let o=[],i=e.split(/\r?\n/);for(let n=0;n<i.length&&o.length<s;n+=1)for(let l of t){let r=i[n].match(l.pattern)?.[1]?.trim();if(r){o.push({name:r,line:n+1,detail:l.detail});break}}return o}var oo=[{pattern:/^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,detail:"function"},{pattern:/^\s*(?:export\s+)?(?:abstract\s+)?(?:class|interface|enum|type)\s+([A-Za-z_$][\w$]*)/,detail:"type"},{pattern:/^\s*(?:export\s+)?(?:declare\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/,detail:"value"},{pattern:/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*class\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*type\s+([A-Za-z_]\w*)\s+/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+)*(?:class|interface|record|enum)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public|protected|internal)\s+(?:(?:static|virtual|override|abstract|async|sealed|final|synchronized|native|unsafe|partial|extern|new)\s+)*(?:<[^>]+>\s*)?[A-Za-z_$][\w$<>,.?\[\]: ]*\s+([A-Za-z_$][\w$]*)\s*\(/,detail:"method"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|trait|enum|type)\s+([A-Za-z_]\w*)/,detail:"type"},{pattern:/^\s*(?:public\s+|private\s+|protected\s+)?function\s+([A-Za-z_]\w*)/,detail:"function"},{pattern:/^\s*(?:class|module|struct|protocol|mixin)\s+([A-Za-z_]\w*)/,detail:"type"}],Rt=[{pattern:/^\s*import(?:.+?from\s*)?["']([^"']+)["']/,detail:"import"},{pattern:/require\(["']([^"']+)["']\)/,detail:"require"}],St=[{pattern:/^\s*from\s+([A-Za-z0-9_.]+)\s+import\s+/,detail:"import"},{pattern:/^\s*import\s+([A-Za-z0-9_.]+)(?:\s|$)/,detail:"import"}],so=[{pattern:/^\s*#\s*include\s*["<]([^">]+)[">]/,detail:"include"}],io=[{pattern:/^\s*use\s+([A-Za-z0-9_:*.-]+)/,detail:"use"}],ro=[{pattern:/^\s*import\s+(?:static\s+)?([A-Za-z0-9_.*]+)\s*;?/,detail:"import"}],no=[{pattern:/^\s*(?:global\s+)?using\s+([A-Za-z0-9_.]+)/,detail:"using"}],ao=[{pattern:/^\s*import\s+(?:[A-Za-z0-9_.]+\s+)?["']([^"']+)["']/,detail:"import"}],At=[{pattern:/^\s*require(?:_relative)?\s+["']([^"']+)["']/,detail:"require"}],co=[{pattern:/^\s*use\s+([A-Za-z0-9_\\]+)/,detail:"use"}],lo=[{pattern:/^\s*(?:alias|import|require|use)\s+([A-Za-z0-9_.]+)/,detail:"import"}],po=[{pattern:/^\s*import\s+["']([^"']+)["']/,detail:"import"}],uo=[{pattern:/\brequire\s*\(?\s*["']([^"']+)["']/,detail:"require"}],fo=[{pattern:/^\s*(?:library|require)\s*\(\s*["']?([^"')\s]+)["']?/,detail:"import"}],go=[...Rt,...St,{pattern:/^\s*(?:import|using|use)\s+([A-Za-z0-9_:.*\\/.-]+)/,detail:"import"},...At];function mo(e){let t=u.extname(e).toLowerCase();return [".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx",".vue",".svelte"].includes(t)?Rt:t===".py"?St:[".c",".cc",".cpp",".h",".hpp"].includes(t)?so:t===".rs"?io:[".java",".kt",".kts",".scala"].includes(t)?ro:[".cs",".fs",".fsx",".vb"].includes(t)?no:t===".go"?ao:t===".rb"?At:t===".php"?co:[".ex",".exs"].includes(t)?lo:t===".dart"?po:t===".lua"?uo:t===".r"?fo:go}function ho(e,t,s,o,i){let n=u.extname(e).toLowerCase()===".py",l=[];if(n){let r=t.match(/^\.+/)?.[0].length??0,d=r>0?u.dirname(e):u.resolve(o??"");for(let p=1;p<r;p+=1)d=u.dirname(d);let a=t.slice(r).replace(/\./g,u.sep);l.push(a?u.join(d,a):d);}else if(t.startsWith("."))l.push(u.resolve(u.dirname(e),t));else if(i==="include")l.push(u.resolve(u.dirname(e),t)),o&&l.push(u.resolve(o,t));else return null;let c=new Set;for(let r of l){c.add(r);let d=u.extname(r).toLowerCase(),a=te.has(d);if(n&&(c.add(`${r}.py`),c.add(u.join(r,"__init__.py"))),a){let p=r.slice(0,-d.length);if([".js",".jsx",".mjs"].includes(d))for(let f of [".ts",".tsx",".js",".jsx",".mjs"])c.add(`${p}${f}`);}else for(let p of te)c.add(`${r}${p}`),c.add(u.join(r,`index${p}`));}return [...c].find(r=>s.has(u.resolve(r)))??null}function vo(e,t){let s=t.trimStart(),o=u.extname(e).toLowerCase();return [".py",".rb",".sh",".bash",".zsh"].includes(o)?s.startsWith("#"):[".sql",".lua",".hs"].includes(o)?s.startsWith("--"):s.startsWith("//")||s.startsWith("/*")||s.startsWith("*")}function yo(e,t){if(u.extname(e).toLowerCase()!==".py")return t;let s=null;return t.split(/\r?\n/).map(o=>{let i=0,n="";for(;i<o.length;){if(s){let a=o.indexOf(s,i);if(a<0)return n;i=a+3,s=null;continue}let l=o.indexOf("'''",i),c=o.indexOf('"""',i),r=o.indexOf("#",i),d=l<0?c:c<0?l:Math.min(l,c);if(r>=0&&(d<0||r<d)){n+=o.slice(i,r);break}if(d<0){n+=o.slice(i);break}n+=o.slice(i,d),s=o.startsWith("'''",d)?"'''":'"""',i=d+3;}return n}).join(`
2
2
  `)}function bo(e,t){if(![".js",".jsx",".mjs",".ts",".tsx"].includes(u.extname(e).toLowerCase()))return t;let s=false,o=false;return t.split(/\r?\n/).map(i=>{let n="",l=null,c=false;for(let r=0;r<i.length;r+=1){let d=i[r],a=i[r+1];if(s){n+=" ",d==="*"&&a==="/"&&(n+=" ",r+=1,s=false);continue}if(o){n+=" ",d==="`"&&!c&&(o=false),c=d==="\\"&&!c,d!=="\\"&&(c=false);continue}if(l){n+=d,d===l&&!c&&(l=null),c=d==="\\"&&!c,d!=="\\"&&(c=false);continue}if(d==="/"&&a==="/")return n.padEnd(i.length," ");if(d==="/"&&a==="*"){n+=" ",r+=1,s=true;continue}if(d==="`"){n+=" ",o=true,c=false;continue}(d==="'"||d==='"')&&(l=d),n+=d;}return n}).join(`
3
3
  `)}function Ft(e,t){return bo(e,yo(e,t))}var we=[{pattern:/@(?:Get|Post|Put|Delete|Patch|Options|Head)\s*\(\s*["']([^"']*)["']/i,detail:"decorated route"},{pattern:/\b(?:app|router|server|api|route|fastify|fiber)\.(?:get|post|put|delete|patch|options|head)\s*\(\s*["']([^"']+)["']/i,detail:"router route"},{pattern:/@(?:GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*\([^"']*["']([^"']*)["']/,detail:"mapped route"},{pattern:/\[Http(?:Get|Post|Put|Delete|Patch)\s*\(\s*["']([^"']*)["']/i,detail:"HTTP route"},{pattern:/^\s*(?:get|post|put|delete|patch)\s+["']([^"']+)["']/i,detail:"HTTP route"}],ko=[{pattern:/@Router\s+([^\s]+)\s+\[(?:get|post|put|delete|patch|options|head)\]/i,detail:"swagger route"},{pattern:/\b[A-Za-z_]\w*\.(?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD)\s*\(\s*["']([^"']+)["']/,detail:"go router route"}],wo=[{pattern:/\.route\s*\(\s*["']([^"']+)["']\s*,\s*(?:routing::)?(?:get|post|put|delete|patch|options|head)\s*\(/i,detail:"rust router route"}],Po=[{pattern:/\b[A-Za-z_]\w*\.Map(?:Get|Post|Put|Delete|Patch|Methods)\s*\(\s*["']([^"']+)["']/i,detail:"dotnet route"},{pattern:/\b[A-Za-z_]\w*\.MapHealthChecks\s*\(\s*["']([^"']+)["']/i,detail:"dotnet health route"}];function $o(e){let t=u.extname(e).toLowerCase();return t===".go"?[...we,...ko]:t===".rs"?[...we,...wo]:t===".cs"?[...we,...Po]:we}function jo(e,t){return t==="swagger route"?e.match(/\[(get|post|put|delete|patch|options|head)\]/i)?.[1]?.toUpperCase()??"HTTP":t==="rust router route"?e.match(/,\s*(?:routing::)?(get|post|put|delete|patch|options|head)\s*\(/i)?.[1]?.toUpperCase()??"HTTP":t==="dotnet health route"?"GET":t==="dotnet route"?e.match(/\.Map(Get|Post|Put|Delete|Patch|Methods)\s*\(/i)?.[1]?.toUpperCase()??"HTTP":e.match(/(?:@|\.|\[|^\s*)(get|post|put|delete|patch|options|head)/i)?.[1]?.toUpperCase()??"HTTP"}function je(e){return createHash("sha256").update(e).digest("hex")}function R(e,t){return `wkg:${e}:${je(`${e}\0${t}`).slice(0,20)}`}function D(e){return e.replace(/\\/g,"/")}function me(e){let t=D(e).replace(/^\.\//,"");return !t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")?"unknown":t}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function P(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function H(e){if(Array.isArray(e))return e.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).sort();let t=C(e);return t?Object.keys(t).map(s=>s.trim()).filter(Boolean).sort():[]}function Io(e){if(Array.isArray(e))return e.map(s=>typeof s=="string"?s.split("=",1)[0]?.trim():"").filter(s=>!!s).sort();let t=C(e);return t?Object.keys(t).sort():[]}function Eo(e){return Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0).sort(([t],[s])=>t.localeCompare(s)))}async function Co(e,t,s=[]){let o=[],i=[e],n=s.map(r=>u.resolve(r)),l=r=>{let d=u.resolve(r);return n.some(a=>d===a||d.startsWith(`${a}${u.sep}`))},c=0;for(;c<i.length&&o.length<t;){let r=i[c++],d;try{d=await _.readdir(r,{withFileTypes:true});}catch{continue}d.sort((a,p)=>a.name.localeCompare(p.name));for(let a of d){if(o.length>=t)break;if(a.isSymbolicLink())continue;let p=u.join(r,a.name);l(p)||(a.isDirectory()?!It.has(a.name)&&!a$1(a.name)&&i.push(p):a.isFile()&&(Ke(e,p)||o.push(p)));}}return o.sort((r,d)=>r.localeCompare(d))}function ve(e,t,s){let o=s?.projects.find(i=>i.relativePath===t.path||t.id!==void 0&&(i.slug===t.id||i.relativePath===`external/${t.id}`));return d$1(e,t.path,{...t.absolutePath||o?.externalPath?{absolutePath:t.absolutePath??o?.externalPath}:{}})}async function qe(e){return new Promise(t=>{let s=createHash("sha256"),o=createReadStream(e);o.on("data",i=>s.update(i)),o.on("error",i=>{t(`unreadable:${i.code??"unknown"}`);}),o.on("end",()=>t(s.digest("hex")));})}var Ro=promisify(execFile);async function Z(e,t){let s=await Ro("git",t,{cwd:e,encoding:"buffer",maxBuffer:268435456,windowsHide:true});return Buffer.isBuffer(s.stdout)?s.stdout:Buffer.from(s.stdout)}function Ze(){return [".",...[...It].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}/**`),...[...Et].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}`),...[...Ct].sort((e,t)=>e.localeCompare(t)).map(e=>`:(exclude,glob)**/${e}`),":(exclude,glob)**/.agents/skills/workspai-*/**",":(exclude,glob)**/.amazonq/rules/workspai-*.md",":(exclude,glob)**/.claude/rules/workspai-*.md",":(exclude,glob)**/.claude/rules/rapidkit-*.md",":(exclude,glob)**/.claude/skills/workspai-*/**",":(exclude,glob)**/.cursor/rules/workspai-*.*",":(exclude,glob)**/.cursor/rules/rapidkit-*.*",":(exclude,glob)**/.cursor/skills/workspai-*/**",":(exclude,glob)**/.grok/rules/workspai-*.md",":(exclude,glob)**/.grok/skills/workspai-*/**",":(exclude,glob)**/.github/agents/workspai-*.agent.md",":(exclude,glob)**/.github/copilot-instructions.md",":(exclude,glob)**/.github/instructions/workspai-*.md",":(exclude,glob)**/.github/instructions/rapidkit-*.md",":(exclude,glob)**/.github/prompts/workspai-*.md",":(exclude,glob)**/.github/prompts/rapidkit-*.md",":(exclude,glob)**/.github/skills/workspai-*/**",":(exclude,glob)**/.github/skills/rapidkit-*/**",":(exclude,glob)**/.windsurf/rules/workspai-*.md",":(exclude,glob)**/.windsurfrules",":(exclude,glob)**/.vscode/workspai-agent-hooks.json",":(exclude,glob)**/.vscode/rapidkit-agent-hooks.json"]}function We(e){return e.toString("utf8").split("\0").filter(Boolean).map(t=>t.replace(/\\/gu,"/"))}async function So(e,t,s=[]){try{await Z(e,["rev-parse","--show-toplevel"]);let o=Ze(),[i,n,l]=await Promise.all([Z(e,["ls-files","--stage","-z","--",...o]),Z(e,["ls-files","--deleted","-z","--",...o]),Z(e,["ls-files","--others","--exclude-standard","-z","--",...o])]),c=new Set(We(n)),r=i.toString("utf8").split("\0").filter(Boolean).flatMap(v=>{let m=v.match(/^(\d{6}) [0-9a-f]+ \d\t([\s\S]+)$/u);if(!m)return [];let[,h,y]=m,b=y.replace(/\\/gu,"/");return h==="120000"||h==="160000"||c.has(b)?[]:[b]}),p=(await Ce([...new Set([...r,...We(l)])],64,async v=>{let m=u.normalize(v);if(u.isAbsolute(m)||m===".."||m.startsWith(`..${u.sep}`))return null;let h=u.resolve(e,m);try{let y=await _.lstat(h);return y.isFile()&&!y.isSymbolicLink()?v:null}catch{return null}})).filter(v=>v!==null).map(v=>u.resolve(e,...v.split("/").filter(Boolean))).filter(v=>!Ke(e,v)).filter(v=>!s.some(m=>v===u.resolve(m)||v.startsWith(`${u.resolve(m)}${u.sep}`))).sort((v,m)=>v.localeCompare(m)),f=p.length>t;return {files:f?$e(p,t,e):p,eligibleFileCount:p.length,eligibleFileCountExact:true,truncated:f,fileLimit:t,strategy:"git-index-worktree-v1"}}catch{return null}}async function ye(e,t,s=[]){let o=await So(e,t,s);if(o)return o;let i=await Co(e,t+1,s),n=i.length>t;return {files:n?$e(i,t,e):i,eligibleFileCount:i.length,eligibleFileCountExact:!n,truncated:n,fileLimit:t,strategy:"filesystem-bfs-v1"}}async function Ao(e){try{let t=(await Z(e.root,["rev-parse","--show-prefix"])).toString("utf8").trim().replace(/\\/gu,"/"),s=t?`${t.replace(/^\/+|\/+$/gu,"")}/`:"";if(u.posix.isAbsolute(s)||s==="../"||s.startsWith("../")||s.includes("/../"))return null;let o=Ze(),[i,n,l,c,r,d]=await Promise.all([Z(e.root,["ls-files","--full-name","-s","--",...o]),Z(e.root,["diff","--no-ext-diff","--no-textconv","--binary","HEAD","--",...o]),Z(e.root,["ls-files","--full-name","--others","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","--full-name","--others","--ignored","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","-v","--",...o]),Z(e.root,["ls-files","--full-name","-s","--",...o])]);if(r.toString("utf8").split(/\r?\n/u).some(y=>/^[a-z] /u.test(y)))return null;let a=e.files.map(y=>{let b=D(u.relative(e.root,y));return `${s}${b}`});if(d.toString("utf8").split(/\r?\n/u).filter(y=>y.startsWith("160000 ")).map(y=>y.split(" ",2)[1]).filter(y=>!!y).map(y=>y.replace(/\\/gu,"/").replace(/\/$/u,"")).some(y=>a.some(b=>b.startsWith(`${y}/`))))return null;let f=new Set(a),v=Buffer.concat([l,c]).toString("utf8").split("\0").filter(Boolean).map(y=>y.replace(/\\/gu,"/")).filter(y=>f.has(y)),m=await Ce([...new Set(v)].sort((y,b)=>y.localeCompare(b)),16,async y=>{let b=s?y.slice(s.length):y;return {path:b,hash:await qe(u.resolve(e.root,...b.split("/").filter(Boolean)))}}),h=createHash("sha256");h.update(`git-worktree-v2\0${e.kind}\0${e.id}\0${e.fileLimit}\0`),h.update(i),h.update(createHash("sha256").update(n).digest());for(let y of m)h.update(`${y.path}\0${y.hash}\0`);return {kind:e.kind,id:e.id,strategy:"git-worktree-v2",hash:h.digest("hex"),fileCount:e.files.length,fileLimit:e.fileLimit,truncated:e.files.length>=e.fileLimit}}catch{return null}}async function Fo(e){try{let t=(await Z(e.root,["rev-parse","--show-prefix"])).toString("utf8").trim().replace(/\\/gu,"/"),s=t?`${t.replace(/^\/+|\/+$/gu,"")}/`:"";if(u.posix.isAbsolute(s)||s==="../"||s.startsWith("../")||s.includes("/../"))return null;let o=Ze(),[i,n,l,c]=await Promise.all([Z(e.root,["ls-files","--full-name","-s","--",...o]),Z(e.root,["diff","--no-ext-diff","--no-textconv","--binary","HEAD","--",...o]),Z(e.root,["ls-files","--full-name","--others","--exclude-standard","-z","--",...o]),Z(e.root,["ls-files","-v","--",...o])]);if(c.toString("utf8").split(/\r?\n/u).some(p=>/^[a-z] /u.test(p)))return null;let r=(e.excludedRoots??[]).map(p=>u.resolve(p)),d=(await Ce([...new Set(We(l))].sort((p,f)=>p.localeCompare(f)),16,async p=>{if(s&&!p.startsWith(s))return null;let f=s?p.slice(s.length):p,v=u.normalize(f);if(!f||u.isAbsolute(v)||v===".."||v.startsWith(`..${u.sep}`))return null;let m=u.resolve(e.root,v);if(r.some(h=>m===h||m.startsWith(`${h}${u.sep}`))||Ke(e.root,m))return null;try{let h=await _.lstat(m);if(!h.isFile()||h.isSymbolicLink())return null}catch{return null}return {path:f,hash:await qe(m)}})).filter(p=>p!==null),a=createHash("sha256");a.update(`git-worktree-v2\0${e.kind}\0${e.id}\0${e.fileLimit}\0`),a.update(i),a.update(createHash("sha256").update(n).digest());for(let p of d)a.update(`${p.path}\0${p.hash}\0`);return a.digest("hex")===e.expectedHash}catch{return null}}async function Ce(e,t,s){let o=new Array(e.length),i=0,n=Array.from({length:Math.min(t,Math.max(e.length,1))},async()=>{for(;i<e.length;){let l=i++;o[l]=await s(e[l]);}});return await Promise.all(n),o}async function xe(e){let t=[...new Set(e.files)].sort((d,a)=>d.localeCompare(a)),s=e.eligibleFileCount??t.length,o=s>e.fileLimit||t.length>e.fileLimit,i=t.slice(0,e.fileLimit),n=await Ao({...e,files:i}),l={eligibleFileCount:s,eligibleFileCountExact:e.eligibleFileCountExact??!o,inventoryMode:o?"emergency-bounded":"complete",...e.inventoryStrategy?{inventoryStrategy:e.inventoryStrategy}:{},...e.selection?{selection:e.selection}:{}};if(n)return {...n,fileCount:i.length,truncated:o,...l};let c=await Ce(i,16,async d=>({path:D(u.relative(e.root,d)),hash:await qe(d)}));c.sort((d,a)=>d.path.localeCompare(a.path));let r=createHash("sha256");r.update(`content-merkle-v1\0${e.kind}\0${e.id}\0${e.fileLimit}\0`);for(let d of c)r.update(`${d.path}\0${d.hash}\0`);return {kind:e.kind,id:e.id,strategy:"content-merkle-v1",hash:r.digest("hex"),fileCount:c.length,fileLimit:e.fileLimit,truncated:o,...l}}async function _o(e){let t=u.resolve(e.workspacePath),s=[...e.projects].sort((r,d)=>r.id.localeCompare(d.id)),o=s.map(r=>ve(t,r)),i=e.inventories?.workspaceInventory??(e.inventories?.workspaceFiles?{files:[...e.inventories.workspaceFiles],eligibleFileCount:e.inventories.workspaceFiles.length,eligibleFileCountExact:e.inventories.workspaceFiles.length<=e.workspaceFileLimit,truncated:e.inventories.workspaceFiles.length>e.workspaceFileLimit,fileLimit:e.workspaceFileLimit,strategy:"filesystem-bfs-v1"}:await ye(t,e.workspaceFileLimit,o)),n=i.files.filter(r=>!o.some(d=>r===d||r.startsWith(`${d}${u.sep}`))),l={...i,files:n,eligibleFileCount:i.eligibleFileCountExact&&!i.truncated?n.length:i.eligibleFileCount},c=await Promise.all([xe({kind:"workspace",id:"workspace",root:t,files:l.files,fileLimit:e.workspaceFileLimit,eligibleFileCount:l.eligibleFileCount,eligibleFileCountExact:l.eligibleFileCountExact,inventoryStrategy:l.strategy}),...s.map(async r=>{let d=ve(t,r),a=e.inventories?.projectFiles?.get(r.id),p=e.inventories?.projectInventories?.get(r.id)??(a?{files:[...a],eligibleFileCount:a.length,eligibleFileCountExact:a.length<=e.projectFileLimit,strategy:"filesystem-bfs-v1"}:await ye(d,e.projectFileLimit)),f=e.inventories?.scanBudgetsByProject?.get(r.id);return xe({kind:"project",id:r.id,root:d,files:p.files,fileLimit:e.projectFileLimit,eligibleFileCount:p.eligibleFileCount,eligibleFileCountExact:p.eligibleFileCountExact,inventoryStrategy:p.strategy,...f?{selection:{strategy:"component-language-round-robin-v1",semanticFileCount:Math.min(p.files.length,f.semanticFileBudget),semanticFileBudget:f.semanticFileBudget,deepFileCount:Math.min(p.files.length,f.deepFileBudget),deepFileBudget:f.deepFileBudget,sourceExtractionFileBudget:f.sourceExtractionFileBudget}}:{}})})]);return c.sort((r,d)=>r.kind.localeCompare(d.kind)||r.id.localeCompare(d.id)),_t(c)}function _t(e){let t=[...e].sort((o,i)=>o.kind.localeCompare(i.kind)||o.id.localeCompare(i.id)),s=createHash("sha256");s.update("workspace-knowledge-graph-inputs.v1\0hybrid-git-content-v2\0");for(let o of t)s.update(`${o.kind}\0${o.id}\0${o.hash}\0${o.fileCount}\0${o.fileLimit}\0${o.truncated}\0${o.eligibleFileCount??o.fileCount}\0${o.eligibleFileCountExact??!o.truncated}\0${o.inventoryMode??(o.truncated?"emergency-bounded":"complete")}\0${o.inventoryStrategy??"unknown"}\0${o.selection?c(o.selection):""}\0`);return {schemaVersion:"workspace-knowledge-graph-inputs.v1",strategy:"hybrid-git-content-v2",hashAlgorithm:"sha256",hash:s.digest("hex"),scopes:t}}async function Ws(e){if(_t(e.expected.scopes).hash!==e.expected.hash)return false;let t=u.resolve(e.workspacePath),s=[...e.projects].sort((n,l)=>n.id.localeCompare(l.id)),o=s.map(n=>ve(t,n)),i=new Map(s.map(n=>[n.id,n]));for(let n of e.expected.scopes){let l=n.kind==="project"?i.get(n.id):void 0;if(n.kind==="project"&&!l)return false;let c$1=l?ve(t,l):t;if(n.strategy==="git-worktree-v2"){let v=await Fo({kind:n.kind,id:n.id,root:c$1,fileLimit:n.fileLimit,expectedHash:n.hash,...n.kind==="workspace"?{excludedRoots:o}:{}});if(v!==null){if(!v)return false;continue}}let r=await ye(c$1,n.fileLimit,n.kind==="workspace"?o:[]),d=n.kind==="workspace"?r.files.filter(v=>!o.some(m=>v===m||v.startsWith(`${m}${u.sep}`))):r.files,a={...r,files:d,eligibleFileCount:r.eligibleFileCountExact&&!r.truncated?d.length:r.eligibleFileCount},p=n.selection?{strategy:"component-language-round-robin-v1",semanticFileCount:Math.min(a.files.length,n.selection.semanticFileBudget),semanticFileBudget:n.selection.semanticFileBudget,deepFileCount:Math.min(a.files.length,n.selection.deepFileBudget),deepFileBudget:n.selection.deepFileBudget,sourceExtractionFileBudget:n.selection.sourceExtractionFileBudget}:void 0,f=await xe({kind:n.kind,id:n.id,root:c$1,files:a.files,fileLimit:n.fileLimit,eligibleFileCount:a.eligibleFileCount,eligibleFileCountExact:a.eligibleFileCountExact,inventoryStrategy:a.strategy,...p?{selection:p}:{}});if(c(f)!==c(n))return false}return true}async function ae(e){let t=await _.readFile(e,"utf8");if(e.toLowerCase().endsWith(".json")){let s=JSON.parse(t),o=C(s);return o?[o]:[]}return parseAllDocuments(t,{logLevel:"silent"}).map(s=>C(s.toJSON())).filter(s=>s!==null)}function ue(e){return [...new Set([...e.workspaceFiles,...e.projects.flatMap(t=>e.filesByProject.get(t.id)??[])])].sort((t,s)=>t.localeCompare(s))}function Ie(e){return /^(?:openapi|swagger)(?:\.[^.]+)?\.(?:json|ya?ml)$/i.test(u.basename(e))}function ct(e){let t=u.basename(e).toLowerCase();return /\.(?:graphql|gql|proto)$/.test(t)||/^asyncapi(?:\.[^.]+)?\.(?:json|ya?ml)$/.test(t)}function dt(e){let t=u.basename(e),s=D(e);return !/(?:^|\/)\.devcontainer(?:\/|$)/i.test(s)&&/^Dockerfile(?:\..+)?$/i.test(t)||/\.tf$/i.test(t)||t==="Chart.yaml"}function lt(e){return /(?:^|[\\/])(?:README|ARCHITECTURE|CONTRIBUTING|SECURITY)\.md$/i.test(e)}function To(e,t){let s=D(u.relative(e,t));return /^\.github\/workflows\/.+\.ya?ml$/i.test(s)||/^(?:\.gitlab-ci\.ya?ml|azure-pipelines\.ya?ml|Jenkinsfile|bitbucket-pipelines\.ya?ml|\.woodpecker\.ya?ml|\.drone\.ya?ml|\.travis\.ya?ml|appveyor\.ya?ml)$/i.test(s)||/^\.circleci\/config\.ya?ml$/i.test(s)||/^\.buildkite\/pipeline\.ya?ml$/i.test(s)||/^\.tekton\/.+\.ya?ml$/i.test(s)||/^prow\/[^/]+\.(?:sh|py)$/i.test(s)}function pt(e,t){let s=D(u.relative(e,t));return /(?:^|\/)(?:adr|adrs|decisions)(?:\/).+\.md$/i.test(s)||/(?:^|\/)ADR[-_0-9].+\.md$/i.test(s)}async function ut(e){let t=new Set;for(let s of [e.workspacePath,...e.projects.map(o=>o.root)])for(let o of ["compose.yml","compose.yaml","docker-compose.yml","docker-compose.yaml"]){let i=u.join(s,o);await _.pathExists(i)&&t.add(i);}for(let s of ue(e))/^(?:docker-)?compose(?:\.[a-z0-9_-]+)*\.ya?ml$/i.test(u.basename(s))&&t.add(s);return [...t].sort((s,o)=>s.localeCompare(o))}async function ft(e){let s=[e.workspacePath,...e.projects.map(i=>i.root)].flatMap(i=>[u.join(i,"CODEOWNERS"),u.join(i,".github","CODEOWNERS"),u.join(i,".gitlab","CODEOWNERS"),u.join(i,"docs","CODEOWNERS")]);for(let i of ue(e))u.basename(i)==="OWNERS"&&s.push(i);let o=await Promise.all(s.map(async i=>await _.pathExists(i)?i:null));return [...new Set(o.filter(i=>!!i))].sort((i,n)=>i.localeCompare(n))}function gt(e){let t=[{root:e.workspacePath,files:e.workspaceFiles},...e.projects.map(s=>({root:s.root,files:e.filesByProject.get(s.id)??[]}))];return [...new Set(t.flatMap(s=>s.files.filter(o=>To(s.root,o))))].sort((s,o)=>s.localeCompare(o))}async function mt(e){let t=[];for(let s of ue(e))if(/\.ya?ml$/i.test(s))try{(await ae(s)).some(i=>{let n=C(i.metadata);return !!(P(i.apiVersion)&&P(i.kind)&&P(n?.name))})&&t.push(s);}catch{}return t.sort((s,o)=>s.localeCompare(o))}function ie(e,t){let s=u.resolve(t);return e.filter(o=>s===o.root||s.startsWith(`${o.root}${u.sep}`)).sort((o,i)=>i.root.length-o.root.length)[0]??null}var ze=class{constructor(t,s,o){this.workspacePath=t;this.now=s;this.workspaceName=o;}workspacePath;now;workspaceName;entities=new Map;relations=new Map;proofs=new Map;providers=[];diagnostics=[];contentHashes=new Map;attributeConflicts=new Set;emptyLabelDiagnostics=new Set;artifactPath(t,s){if(s){let o=D(u.relative(s.root,t));return me(u.posix.join(s.artifactPrefix,o))}return me(u.relative(this.workspacePath,t))}async addProof(t){let s;if(t.absolutePath){if(!this.contentHashes.has(t.absolutePath))try{this.contentHashes.set(t.absolutePath,je(await _.readFile(t.absolutePath)));}catch{this.contentHashes.set(t.absolutePath,null);}s=this.contentHashes.get(t.absolutePath)??void 0;}let o=me(t.artifact),i=R("proof",[t.provider,o,t.pointer??"",t.line??"",t.detail??""].join("\0"));return this.proofs.has(i)||this.proofs.set(i,{id:i,provider:t.provider,artifact:o,...t.pointer?{pointer:t.pointer}:{},...t.line?{line:t.line}:{},...t.column?{column:t.column}:{},...s?{contentHash:s}:{},observedAt:this.now.toISOString(),derivation:t.derivation??"extracted",trust:t.trust??"observed",confidence:t.confidence??"high",freshness:"fresh",...t.detail?{detail:t.detail}:{}}),i}addEntity(t){let s=R(t.kind,t.key),o=Eo(t.attributes??{}),i=this.entities.get(s),n=t.label.trim(),l=n||i?.label||t.key.trim()||t.kind;!n&&!this.emptyLabelDiagnostics.has(s)&&(this.emptyLabelDiagnostics.add(s),this.diagnostics.push({code:"graph.knowledge.empty_label_normalized",severity:"warning",message:`An empty ${t.kind} label was normalized to ${l}.`,entityIds:[s],recommendation:"Inspect the provider proof and preserve a non-empty source identifier before publishing the entity."}));let c={...i?.attributes??{}};for(let[a,p]of Object.entries(o)){if(a in c&&JSON.stringify(c[a])!==JSON.stringify(p)){if(t.mergeArrayAttributes?.includes(a)&&Array.isArray(c[a])&&Array.isArray(p)){c[a]=p;continue}let f=`${s}\0${a}`;this.attributeConflicts.has(f)||(this.attributeConflicts.add(f),this.diagnostics.push({code:"graph.knowledge.attribute_conflict",severity:"warning",message:`Conflicting ${a} values were observed for ${t.kind} ${l}.`,entityIds:[s],recommendation:"Inspect the entity proof paths and make the authoritative source explicit."}));continue}c[a]=p;}let r=[...new Set([...i?.identity.aliases??[],...t.aliases??[]].map(a=>a.trim()).filter(Boolean))].sort(),d=[...new Set([...i?.proofIds??[],...t.proofIds??[]])].sort();return this.entities.set(s,{id:s,kind:t.kind,label:l,...t.projectId?{projectId:t.projectId}:{},identity:{key:t.key,scope:t.projectId?"project":"workspace",aliases:r,fingerprint:je(JSON.stringify({kind:t.kind,key:t.key,attributes:c}))},attributes:c,proofIds:d}),s}addRelation(t){let s=R("relation",`${t.from}\0${t.kind}\0${t.to}`),o=this.relations.get(s),i=[...new Set([...o?.proofIds??[],...t.proofIds])].sort(),n=new Set(i.map(r=>this.proofs.get(r)?.provider).filter(Boolean)).size,l=t.trust??o?.trust??"observed",c=n>=2&&l!=="ambiguous"?"corroborated":l;return this.relations.set(s,{id:s,from:t.from,to:t.to,kind:t.kind,derivation:t.derivation??o?.derivation??"extracted",trust:c,confidence:c==="corroborated"?"high":t.confidence??o?.confidence??"high",proofIds:i}),s}};function pe(e){let t=[],s=null;for(let o of e.split(/\r?\n/)){let i=o.match(/^\s*\[\[([^\]]+)\]\]\s*(?:#.*)?$/)?.[1]?.trim()??o.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/)?.[1]?.trim();if(i){s&&t.push({name:s.name,body:s.lines.join(`
4
4
  `)}),s={name:i,lines:[]};continue}s?.lines.push(o);}return s&&t.push({name:s.name,body:s.lines.join(`