workspai 0.52.2 → 0.53.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 (132) hide show
  1. package/README.md +2 -0
  2. package/contracts/artifact-remediation-plan.v1.json +1 -0
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +36 -0
  4. package/contracts/extension-cli-compatibility.v1.json +24 -2
  5. package/contracts/pipeline-last-run.v1.json +6 -1
  6. package/contracts/published-contract-catalog.v1.json +113 -2
  7. package/contracts/runtime-command-surface.v1.json +216 -5
  8. package/contracts/studio-card-repair-capabilities.v1.json +378 -0
  9. package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +78 -0
  10. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +249 -0
  11. package/contracts/workspace-intelligence-chain.v1.json +6 -0
  12. package/contracts/workspace-repair-capabilities.v1.json +316 -0
  13. package/dist/analyze-AAZEJ4FC.js +1 -0
  14. package/dist/artifact-remediation-plan-CJSPCMWA.js +1 -0
  15. package/dist/autopilot-release-LZWNQQLY.js +1 -0
  16. package/dist/chunk-27AXFTKW.js +1 -0
  17. package/dist/{chunk-OTDGTAZJ.js → chunk-2FJW6GSW.js} +1 -1
  18. package/dist/chunk-3DONU3DU.js +1 -0
  19. package/dist/chunk-44VJHNZB.js +1 -0
  20. package/dist/chunk-5XDPQ3CB.js +1 -0
  21. package/dist/chunk-7AR5PDLD.js +1 -0
  22. package/dist/chunk-7KKP7RNB.js +3 -0
  23. package/dist/chunk-AMB42V2F.js +1 -0
  24. package/dist/chunk-BYVTHIC3.js +2 -0
  25. package/dist/chunk-E5YYVFM2.js +1 -0
  26. package/dist/{chunk-6PBSAAS5.js → chunk-EBKYSDCX.js} +1 -1
  27. package/dist/chunk-FQLB4BIC.js +7 -0
  28. package/dist/{chunk-ICLYL3N5.js → chunk-FZCYTRBQ.js} +1 -1
  29. package/dist/{chunk-ZVOEPWQM.js → chunk-GDU7VP6G.js} +1 -1
  30. package/dist/chunk-H7P7SSUW.js +75 -0
  31. package/dist/chunk-HOVJUP7K.js +8 -0
  32. package/dist/{chunk-MZFSINY7.js → chunk-HRN5J6PW.js} +12 -12
  33. package/dist/chunk-HY3RMPW5.js +10 -0
  34. package/dist/chunk-KFKZOPZC.js +1 -0
  35. package/dist/{chunk-HPWLSLMC.js → chunk-KVUYAYTY.js} +1 -1
  36. package/dist/chunk-MQ73VS4E.js +2 -0
  37. package/dist/{chunk-2OIBHUVH.js → chunk-MRFN5ZQP.js} +1 -1
  38. package/dist/{chunk-4UVGTFOX.js → chunk-NYHVCFBT.js} +1 -1
  39. package/dist/{chunk-IO54DFWR.js → chunk-OLX6LX77.js} +1 -1
  40. package/dist/chunk-OUBBBC7T.js +36 -0
  41. package/dist/{chunk-WJY7ZXVJ.js → chunk-P7K5RHJC.js} +1 -1
  42. package/dist/chunk-QZ7PNMVP.js +1 -0
  43. package/dist/chunk-RA24WQLF.js +1 -0
  44. package/dist/chunk-RMXXK64P.js +4 -0
  45. package/dist/{chunk-PTTZPDLX.js → chunk-S7Z4DP3P.js} +1 -1
  46. package/dist/chunk-SJLUE6AY.js +1 -0
  47. package/dist/chunk-SUV7Y2FH.js +3 -0
  48. package/dist/chunk-T6JI7GYZ.js +88 -0
  49. package/dist/chunk-USMLRNZ7.js +5 -0
  50. package/dist/chunk-WD2XDMGB.js +1 -0
  51. package/dist/chunk-WIO6L24E.js +2 -0
  52. package/dist/{chunk-QURMI7ID.js → chunk-WZA5ISAQ.js} +1 -1
  53. package/dist/chunk-XVRJVKOX.js +1 -0
  54. package/dist/{create-ESK3CQPK.js → create-R6A7EHQZ.js} +1 -1
  55. package/dist/{doctor-MYRJ5BFF.js → doctor-KNIYGDM7.js} +1 -1
  56. package/dist/index.d.ts +92 -23
  57. package/dist/index.js +246 -244
  58. package/dist/pipeline-PVCLAQDI.js +5 -0
  59. package/dist/{project-intelligence-lens-Q4SZDI2N.js → project-intelligence-lens-ZOAWXYC5.js} +1 -1
  60. package/dist/project-test-coverage-44ZPCOPV.js +1 -0
  61. package/dist/{verified-goal-23HZPMRK.js → verified-goal-MCSNMA3P.js} +1 -1
  62. package/dist/{workspace-LSOZM2CG.js → workspace-B53XH35L.js} +1 -1
  63. package/dist/{workspace-agent-sync-RZBQXCNJ.js → workspace-agent-sync-446AXPHJ.js} +1 -1
  64. package/dist/{workspace-archive-ZOWQXWJ6.js → workspace-archive-VHUPOBAV.js} +1 -1
  65. package/dist/{workspace-context-IYJKO5BN.js → workspace-context-XSECHC7O.js} +1 -1
  66. package/dist/{workspace-contract-AZFISDLS.js → workspace-contract-AYFTZIKM.js} +1 -1
  67. package/dist/workspace-explain-SZI2WAAD.js +1 -0
  68. package/dist/workspace-explain-contract-N2XQHAPM.js +1 -0
  69. package/dist/{workspace-feedback-LIHEWTNV.js → workspace-feedback-WXE7NVMV.js} +1 -1
  70. package/dist/{workspace-foundation-H5UTAUXQ.js → workspace-foundation-FFNCK5ZD.js} +1 -1
  71. package/dist/{workspace-graph-stream-KUDOZE73.js → workspace-graph-stream-AJPS45FD.js} +1 -1
  72. package/dist/{workspace-history-HULG5EFN.js → workspace-history-YY7YRDOH.js} +1 -1
  73. package/dist/{workspace-intelligence-A4UE4DZK.js → workspace-intelligence-FWRB47EJ.js} +1 -1
  74. package/dist/{workspace-intelligence-evaluation-AOLGHYHC.js → workspace-intelligence-evaluation-UP2K3L35.js} +1 -1
  75. package/dist/{workspace-intelligence-runner-VYGSASDP.js → workspace-intelligence-runner-JNCQLUH7.js} +1 -1
  76. package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +1 -0
  77. package/dist/{workspace-knowledge-graph-LEM6X5CM.js → workspace-knowledge-graph-BMMM2FUE.js} +1 -1
  78. package/dist/{workspace-mcp-serve-N2QPR7VJ.js → workspace-mcp-serve-COA4FMCA.js} +1 -1
  79. package/dist/{workspace-model-FJXX3NET.js → workspace-model-MNJOGBPP.js} +1 -1
  80. package/dist/{workspace-onboarding-IKFISWWY.js → workspace-onboarding-2B7CYZ5H.js} +1 -1
  81. package/dist/{workspace-readme-E2M35RJH.js → workspace-readme-4S6PJ74A.js} +1 -1
  82. package/dist/{workspace-registry-summary-HOQ3OBNT.js → workspace-registry-summary-GPJEL7K7.js} +1 -1
  83. package/dist/workspace-repair-engine-SRWECKZO.js +3 -0
  84. package/dist/workspace-run-3U77TMKX.js +1 -0
  85. package/dist/{workspace-verify-32AWCJQG.js → workspace-verify-C6HWHRLJ.js} +1 -1
  86. package/dist/{workspace-watch-4WVNB26E.js → workspace-watch-DLPHLF5R.js} +1 -1
  87. package/docs/README.md +2 -0
  88. package/docs/commands-reference.md +10 -8
  89. package/docs/contracts/ARTIFACT_CATALOG.md +27 -22
  90. package/docs/contracts/README.md +3 -0
  91. package/docs/contracts/RUNTIME_ACCEPTANCE_MATRIX.md +20 -11
  92. package/docs/doctor-command.md +10 -4
  93. package/docs/workspace-intelligence-runner.md +2 -1
  94. package/docs/workspace-knowledge-graph.md +6 -1
  95. package/docs/workspace-operations.md +3 -1
  96. package/docs/workspace-repair-engine.md +113 -0
  97. package/docs/workspace-run.md +17 -14
  98. package/package.json +3 -2
  99. package/scripts/enterprise-package-smoke.mjs +9 -6
  100. package/dist/analyze-J7VNZMDH.js +0 -1
  101. package/dist/artifact-remediation-plan-2UKY4TKO.js +0 -3
  102. package/dist/autopilot-release-34H5BSI2.js +0 -1
  103. package/dist/chunk-23JDMHSD.js +0 -86
  104. package/dist/chunk-2E6WGUN6.js +0 -1
  105. package/dist/chunk-3D3PFPP5.js +0 -1
  106. package/dist/chunk-4D7DIGAB.js +0 -1
  107. package/dist/chunk-5XJRCP3D.js +0 -36
  108. package/dist/chunk-62K2H72S.js +0 -1
  109. package/dist/chunk-7MQZQ4UU.js +0 -1
  110. package/dist/chunk-AL237TSJ.js +0 -7
  111. package/dist/chunk-AYHNNPPH.js +0 -8
  112. package/dist/chunk-B4CPDK6J.js +0 -2
  113. package/dist/chunk-CZC5P2MF.js +0 -1
  114. package/dist/chunk-DZ4VKAXB.js +0 -75
  115. package/dist/chunk-FUPHQOJB.js +0 -1
  116. package/dist/chunk-GHB6QMQH.js +0 -1
  117. package/dist/chunk-JIUWK4ML.js +0 -1
  118. package/dist/chunk-KHEJO3JU.js +0 -4
  119. package/dist/chunk-LOCPNNSK.js +0 -1
  120. package/dist/chunk-LPCL4U4L.js +0 -1
  121. package/dist/chunk-MBRU3VWJ.js +0 -2
  122. package/dist/chunk-P4OSLAVD.js +0 -3
  123. package/dist/chunk-Q6CUJ3WF.js +0 -10
  124. package/dist/chunk-SQTV2OYU.js +0 -4
  125. package/dist/chunk-ULR66OJR.js +0 -2
  126. package/dist/chunk-XHRHNVCZ.js +0 -1
  127. package/dist/pipeline-FOZ46ELQ.js +0 -5
  128. package/dist/project-test-coverage-A677ZLW3.js +0 -1
  129. package/dist/workspace-explain-26UGV7L4.js +0 -1
  130. package/dist/workspace-explain-contract-GIWPCCEF.js +0 -1
  131. package/dist/workspace-intelligence-runtime-registry-YOQ5GFFJ.js +0 -1
  132. package/dist/workspace-run-GUW4EOYB.js +0 -1
@@ -1 +0,0 @@
1
- var A="artifact-remediation-plan-v1";export{A as a};
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-62K2H72S.js';var r=".workspai/skills";var e=a$1.skillsIndex,a=a$1.explain,_=".workspai/reports/workspace-why-last-run.json",c=".workspai/reports/workspace-trace-last-run.json",O=".workspai/AGENT-GROUNDING.md",P=".rapidkit/AGENT-GROUNDING.md",I=".cursor/rules/workspai-grounding.mdc",A=".cursor/rules/rapidkit-grounding.mdc",T=".claude/rules/workspai-evidence.md",E=".claude/rules/rapidkit-evidence.md",R=".github/instructions/workspai-workspace.instructions.md",L=".github/instructions/rapidkit-workspace.instructions.md",d=".github/instructions/workspai-evidence.instructions.md",S=".github/instructions/rapidkit-evidence.instructions.md",C=".github/prompts/workspai-diagnose.prompt.md",k=".github/prompts/rapidkit-diagnose.prompt.md",l=".github/prompts/workspai-repair.prompt.md",m=".github/prompts/rapidkit-repair.prompt.md",N=".github/prompts/workspai-release-readiness.prompt.md",u=".github/prompts/rapidkit-release-readiness.prompt.md",g=".github/prompts/workspai-project-onboard.prompt.md",K=".github/prompts/rapidkit-project-onboard.prompt.md",G=".github/prompts/workspai-adopt-project.prompt.md",w=".github/prompts/rapidkit-adopt-project.prompt.md",x=".github/skills/workspai-grounding/SKILL.md",H=".github/skills/rapidkit-grounding/SKILL.md",D=".github/skills/workspai-workspace-intelligence/SKILL.md",W=".github/skills/rapidkit-workspace-intelligence/SKILL.md",h=".workspai/reports/workspai-mcp-design.json",U=".workspai/reports/rapidkit-mcp-design.json",b=".vscode/workspai-agent-hooks.json",Y=".vscode/rapidkit-agent-hooks.json";function M(t){let s=t.trim();if(!s||s.includes("..")||s.includes("/"))throw new Error(`Invalid operational skill id: ${t}`);return `${r}/${s}.md`}var f={"workspai-diagnose-api-failure":"workspai-diagnose","workspai-release-readiness":"workspai-release-readiness","workspai-safe-schema-migration":"workspai-safe-schema-migration","workspai-dependency-upgrade":"workspai-dependency-upgrade","workspai-rename-contract":"workspai-rename-contract"};export{H as A,D as B,W as C,h as D,U as E,b as F,Y as G,M as H,f as I,r as a,e as b,a as c,_ as d,c as e,O as f,P as g,I as h,A as i,T as j,E as k,R as l,L as m,d as n,S as o,C as p,k as q,l as r,m as s,N as t,u,g as v,K as w,G as x,w as y,x as z};
@@ -1 +0,0 @@
1
- import {a}from'./chunk-2OIBHUVH.js';import {a as a$1}from'./chunk-GR6442P7.js';import {f,e}from'./chunk-MBRU3VWJ.js';import {createHash}from'crypto';import c from'path';import {execa}from'execa';import u from'fs-extra';var L="workspai.project-test-coverage.v1",k=".workspai/reports/project-test-coverage-last-run.json",I=["package.json","pyproject.toml","requirements.txt","go.mod","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","composer.json","Gemfile","mix.exs","deps.edn","project.clj","build.sbt","CMakeLists.txt","meson.build","deno.json","deno.jsonc"];function p(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function g(e,t,o=0){let n=p(e),r=Math.min(p(t),n),i=p(o);return {total:n,covered:r,skipped:i,percent:n>0?Math.round(r/n*1e4)/100:null}}function S(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;return g(t.total,t.covered,t.skipped)}function y(e,t){let o=c.isAbsolute(t)?t:c.resolve(e,t),n=c.relative(e,o);return n&&!n.startsWith("..")?n.split(c.sep).join("/"):t}async function x(e){return createHash("sha256").update(await u.readFile(e)).digest("hex")}async function $(e){let t=c.resolve(e);for(;;){if(await u.pathExists(c.join(t,".workspai","project.json"))||await u.pathExists(c.join(t,".rapidkit","project.json"))||(await Promise.all(I.map(r=>u.pathExists(c.join(t,r))))).some(Boolean))return t;let n=c.dirname(t);if(n===t)return c.resolve(e);t=n;}}async function V(e){if(await u.pathExists(c.join(e,"deno.json"))||await u.pathExists(c.join(e,"deno.jsonc")))return "deno";if(await u.pathExists(c.join(e,"bun.lock"))||await u.pathExists(c.join(e,"bun.lockb")))return "bun";if(await u.pathExists(c.join(e,"package.json")))return "node";if(await u.pathExists(c.join(e,"pyproject.toml"))||await u.pathExists(c.join(e,"requirements.txt")))return "python";if(await u.pathExists(c.join(e,"go.mod")))return "go";let t=await u.pathExists(c.join(e,"pom.xml"))||await u.pathExists(c.join(e,"build.gradle"))||await u.pathExists(c.join(e,"build.gradle.kts"));return t&&(await P(e,o=>o.endsWith(".kt")||o.endsWith(".kts")&&o!=="build.gradle.kts"&&o!=="settings.gradle.kts",4)).length>0?"kotlin":t?"java":await u.pathExists(c.join(e,"Cargo.toml"))?"rust":await u.pathExists(c.join(e,"composer.json"))?"php":await u.pathExists(c.join(e,"Gemfile"))?"ruby":await u.pathExists(c.join(e,"mix.exs"))?"elixir":await u.pathExists(c.join(e,"deps.edn"))||await u.pathExists(c.join(e,"project.clj"))?"clojure":await u.pathExists(c.join(e,"build.sbt"))?"scala":await u.pathExists(c.join(e,"CMakeLists.txt"))?(await P(e,n=>/\.(c|cc|cpp|cxx)$/.test(n),3)).some(n=>/\.(cc|cpp|cxx)$/.test(n))?"cpp":"c":(await P(e,o=>/\.(sln|csproj)$/.test(o),2)).length>0?"dotnet":"unknown"}async function P(e,t,o=5){let n=[],r=[{dir:e,depth:0}],i=new Set([".git",".workspai",".rapidkit","node_modules",".venv","vendor","deps"]);for(;r.length>0;){let s=r.shift();if(!s)break;let a=await u.readdir(s.dir,{withFileTypes:true}).catch(()=>[]);for(let l of a){if(i.has(l.name)||a$1(l.name))continue;let d=c.join(s.dir,l.name),m=c.relative(e,d).split(c.sep).join("/");l.isFile()&&t(l.name,m)&&n.push(d),l.isDirectory()&&s.depth<o&&r.push({dir:d,depth:s.depth+1});}}return n}async function W(e,t){let o=await u.readJson(t),n=o.total??o,r={};for(let s of ["lines","branches","functions","statements"]){let a=S(n[s]);a&&(r[s]=a);}let i=[];for(let[s,a]of Object.entries(o)){if(s==="total"||!a||typeof a!="object"||Array.isArray(a))continue;let l=a,d={};for(let m of ["lines","branches","functions","statements"]){let b=S(l[m]);b&&(d[m]=b);}i.push({path:y(e,s),metrics:d});}return {metrics:r,files:i,source:{format:"istanbul-json",path:t,sha256:await x(t)}}}async function H(e,t){let o=await u.readJson(t),n=o.totals??{},r={lines:g(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(r.branches=g(n.num_branches,n.covered_branches));let i=[];for(let[s,a]of Object.entries(o.files??{})){let l=a?.summary??{};i.push({path:y(e,s),metrics:{lines:g(l.num_statements,l.covered_lines),...p(l.num_branches)>0?{branches:g(l.num_branches,l.covered_branches)}:{}}});}return {metrics:r,files:i,source:{format:"coverage-py-json",path:t,sha256:await x(t)}}}function j(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=p(t.count),n=p(t.covered);return o>0?g(o,n):void 0}async function D(e,t){let o=await u.readJson(t),n=Array.isArray(o.data)?o.data[0]??{}:o,r=n.totals??{},i={};i.lines=j(r.lines),i.functions=j(r.functions),i.branches=j(r.branches),i.statements=j(r.regions);let s=[];for(let a of Array.isArray(n.files)?n.files:[]){if(!a||typeof a!="object"||Array.isArray(a))continue;let l=a,d=l.summary??{};s.push({path:y(e,String(l.filename??"unknown")),metrics:{lines:j(d.lines),functions:j(d.functions),branches:j(d.branches),statements:j(d.regions)}});}return {metrics:i,files:s,source:{format:"llvm-cov-json",path:t,sha256:await x(t)}}}async function M(e,t){let o=await u.readFile(t,"utf8"),n=[],r="",i=0,s=0,a=0,l=0,d=0,m=0,b=v=>{r&&(n.push({path:y(e,r),metrics:{lines:g(v.lineTotal,v.lineCovered),functions:g(v.functionTotal,v.functionCovered),branches:g(v.branchTotal,v.branchCovered)}}),i+=v.lineTotal,s+=v.lineCovered,a+=v.functionTotal,l+=v.functionCovered,d+=v.branchTotal,m+=v.branchCovered);},h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0};for(let v of o.split(/\r?\n/))v.startsWith("SF:")?r=v.slice(3):v.startsWith("LF:")?h.lineTotal=p(v.slice(3)):v.startsWith("LH:")?h.lineCovered=p(v.slice(3)):v.startsWith("FNF:")?h.functionTotal=p(v.slice(4)):v.startsWith("FNH:")?h.functionCovered=p(v.slice(4)):v.startsWith("BRF:")?h.branchTotal=p(v.slice(4)):v.startsWith("BRH:")?h.branchCovered=p(v.slice(4)):v==="end_of_record"&&(b(h),r="",h={lineTotal:0,lineCovered:0,functionTotal:0,functionCovered:0,branchTotal:0,branchCovered:0});return {metrics:{lines:g(i,s),functions:g(a,l),branches:g(d,m)},files:n,source:{format:"lcov",path:t,sha256:await x(t)}}}async function G(e,t){let o=await u.readFile(t,"utf8"),n=new Map;for(let s of o.split(/\r?\n/).slice(1)){let a=/^(.+?):\d+\.\d+,\d+\.\d+\s+(\d+)\s+(\d+)$/.exec(s.trim());if(!a)continue;let l=n.get(a[1])??{total:0,covered:0},d=p(a[2]);l.total+=d,p(a[3])>0&&(l.covered+=d),n.set(a[1],l);}let r=[...n.entries()].map(([s,a])=>({path:y(e,s),metrics:{statements:g(a.total,a.covered)}})),i=[...n.values()].reduce((s,a)=>({total:s.total+a.total,covered:s.covered+a.covered}),{total:0,covered:0});return {metrics:{statements:g(i.total,i.covered)},files:r,source:{format:"go-coverprofile",path:t,sha256:await x(t)}}}function T(e,t){let n=[...e.matchAll(new RegExp(`<counter\\s+type=["']${t}["']\\s+missed=["'](\\d+)["']\\s+covered=["'](\\d+)["']\\s*\\/?\\s*>`,"gi"))].at(-1);return n?g(Number(n[1])+Number(n[2]),n[2]):void 0}async function C(e,t){let o=await u.readFile(e,"utf8"),n={};if(t==="cobertura-xml"){let r=/<coverage\b([^>]*)>/i.exec(o)?.[1]??"",i=/\bline-rate=["']([\d.]+)["']/i.exec(r)?.[1],s=/\bbranch-rate=["']([\d.]+)["']/i.exec(r)?.[1];i&&(n.lines=g(1e4,Math.round(Number(i)*1e4))),s&&(n.branches=g(1e4,Math.round(Number(s)*1e4)));}if(t==="clover-xml"){let i=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",s=m=>p(new RegExp(`\\b${m}=["'](\\d+)["']`,"i").exec(i)?.[1]),a=s("statements"),l=s("methods"),d=s("conditionals");a>0&&(n.statements=g(a,s("coveredstatements"))),l>0&&(n.functions=g(l,s("coveredmethods"))),d>0&&(n.branches=g(d,s("coveredconditionals")));}return n.lines??=T(o,"LINE"),n.branches??=T(o,"BRANCH"),n.functions??=T(o,"METHOD"),n.statements??=T(o,"INSTRUCTION"),{metrics:n,files:[],source:{format:t,path:e,sha256:await x(e)}}}async function q(e){let t=await u.readFile(e,"utf8"),o=/<scoverage\b([^>]*)>/i.exec(t)?.[1]??"",n=b=>p(new RegExp(`\\b${b}=["']([\\d.]+)["']`,"i").exec(o)?.[1]),r=n("statement-count"),i=n("statements-invoked"),s=n("branch-count"),a=n("branches-invoked"),l=n("statement-rate"),d=n("branch-rate"),m={};return r>0?m.statements=g(r,i):l>0&&(m.statements=g(1e4,Math.round(l*100))),s>0?m.branches=g(s,a):d>0&&(m.branches=g(1e4,Math.round(d*100))),{metrics:m,files:[],source:{format:"scoverage-xml",path:e,sha256:await x(e)}}}async function z(e,t){let o=await u.readJson(t),n=new Map;for(let s of Object.values(o)){let a=s?.coverage;if(!(!a||typeof a!="object"||Array.isArray(a)))for(let[l,d]of Object.entries(a)){if(!Array.isArray(d))continue;let m=n.get(l)??[];d.forEach((b,h)=>{typeof b=="number"&&(m[h]=Math.max(m[h]??0,b));}),n.set(l,m);}}let r=[...n.entries()].map(([s,a])=>{let l=a.filter(d=>typeof d=="number");return {path:y(e,s),metrics:{lines:g(l.length,l.filter(d=>d>0).length)}}}),i=r.reduce((s,a)=>{let l=a.metrics.lines;return {total:s.total+(l?.total??0),covered:s.covered+(l?.covered??0)}},{total:0,covered:0});return {metrics:{lines:g(i.total,i.covered)},files:r,source:{format:"simplecov-json",path:t,sha256:await x(t)}}}async function B(e){let t=[{relativePath:"coverage/coverage-summary.json",parser:r=>W(e,r)},{relativePath:"coverage.json",parser:async r=>{let i=await u.readJson(r);return Array.isArray(i.data)?D(e,r):H(e,r)}},{relativePath:"coverage/lcov.info",parser:r=>M(e,r)},{relativePath:"cover/lcov.info",parser:r=>M(e,r)},{relativePath:"lcov.info",parser:r=>M(e,r)},{relativePath:"coverage.out",parser:r=>G(e,r)},{relativePath:"target/site/jacoco/jacoco.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"build/reports/jacoco/test/jacocoTestReport.xml",parser:r=>C(r,"jacoco-xml")},{relativePath:"coverage.xml",parser:r=>C(r,"clover-xml")},{relativePath:".resultset.json",parser:r=>z(e,r)}];for(let r of t){let i=c.join(e,r.relativePath);if(await u.pathExists(i))return r.parser(i)}let n=(await P(e,(r,i)=>r==="coverage.cobertura.xml"||r==="jacoco.xml"||r==="clover.xml"||r==="scoverage.xml"||i.endsWith("/coverage-summary.json"),7)).sort()[0];return n?n.endsWith("coverage-summary.json")?W(e,n):n.endsWith("jacoco.xml")?C(n,"jacoco-xml"):n.endsWith("coverage.cobertura.xml")?C(n,"cobertura-xml"):n.endsWith("scoverage.xml")?q(n):C(n,"clover-xml"):null}async function U(e){return u.readJson(c.join(e,"package.json")).catch(()=>null)}async function K(e,t){let o=(n,r)=>({cwd:e,executable:n,args:r});if(t==="node"||t==="bun"){let r=(await U(e))?.scripts??{},i=["test:coverage","test:cov","coverage"].find(a=>typeof r[a]=="string"),s=t==="bun"?"bun":await u.pathExists(c.join(e,"pnpm-lock.yaml"))?"pnpm":await u.pathExists(c.join(e,"yarn.lock"))?"yarn":"npm";if(i)return {runner:String(r[i]).split(/\s+/)[0]||s,invocations:[o(s,s==="yarn"?[i]:["run",i])],diagnostics:[]};if(typeof r.test=="string"){let a=s==="yarn"?["test","--coverage"]:s==="bun"?["test","--coverage","--coverage-reporter=lcov"]:["test","--","--coverage"];return {runner:String(r.test).split(/\s+/)[0]||s,invocations:[o(s,a)],diagnostics:[]}}return {runner:null,invocations:[],diagnostics:["No project-owned test or coverage script was detected."]}}if(t==="deno")return {runner:"deno",invocations:[o("deno",["test","--coverage=coverage"]),o("deno",["coverage","--lcov","--output=coverage/lcov.info","coverage"])],diagnostics:[]};if(t==="python")return {runner:"pytest-cov",invocations:[o(await u.pathExists(c.join(e,".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"))?c.join(".venv",process.platform==="win32"?"Scripts":"bin",process.platform==="win32"?"python.exe":"python"):process.platform==="win32"?"python":"python3",["-m","pytest","--cov=.","--cov-report=json:coverage.json"])],diagnostics:[]};if(t==="go")return {runner:"go test",invocations:[o("go",["test","./...","-coverprofile=coverage.out"])],diagnostics:[]};if(t==="java"){let n=await u.pathExists(c.join(e,"gradlew")),r=await u.pathExists(c.join(e,"gradlew.bat")),i=n||r,s=await u.pathExists(c.join(e,"mvnw")),a=await u.pathExists(c.join(e,"mvnw.cmd")),l=i?process.platform==="win32"&&r?".\\gradlew.bat":"./gradlew":await u.pathExists(c.join(e,"pom.xml"))?process.platform==="win32"&&a?".\\mvnw.cmd":s?"./mvnw":"mvn":"gradle";return {runner:i?"jacoco/gradle":"jacoco/maven",invocations:[o(l,i?["test","jacocoTestReport"]:["test","jacoco:report"])],diagnostics:[]}}return t==="dotnet"?{runner:"dotnet coverlet",invocations:[o("dotnet",["test","--collect:XPlat Code Coverage"])],diagnostics:[]}:t==="rust"?{runner:"cargo llvm-cov",invocations:[o("cargo",["llvm-cov","--json","--output-path","coverage.json"])],diagnostics:["cargo-llvm-cov must be available in the project toolchain."]}:t==="php"?{runner:"phpunit",invocations:[o(process.platform==="win32"?"vendor\\bin\\phpunit.bat":"vendor/bin/phpunit",["--coverage-clover","coverage.xml"])],diagnostics:[]}:t==="ruby"?{runner:"simplecov",invocations:[o("bundle",["exec","rspec"])],diagnostics:["The test suite must enable SimpleCov to emit .resultset.json."]}:t==="elixir"?{runner:"mix cover",invocations:[o("mix",["test","--cover"])],diagnostics:["Configure ExCoveralls for JSON or LCOV interchange when machine-readable coverage is required."]}:t==="clojure"?{runner:"cloverage",invocations:[o("clojure",["-M:coverage"])],diagnostics:["The project must declare a coverage alias such as cloverage."]}:t==="scala"?{runner:"sbt-scoverage",invocations:[o("sbt",["clean","coverage","test","coverageReport"])],diagnostics:["The project must declare the scoverage plugin."]}:t==="kotlin"?{runner:"jacoco/gradle",invocations:[o(await u.pathExists(c.join(e,process.platform==="win32"?"gradlew.bat":"gradlew"))?process.platform==="win32"?".\\gradlew.bat":"./gradlew":"gradle",["test","jacocoTestReport"])],diagnostics:["The project must declare the JaCoCo Gradle plugin."]}:t==="c"||t==="cpp"?{runner:"CTest/LLVM coverage",invocations:[o("ctest",["--test-dir","build","--output-on-failure"])],diagnostics:["The native build must be instrumented for coverage and export LCOV, Cobertura, or LLVM JSON evidence."]}:{runner:null,invocations:[],diagnostics:["Project runtime could not be detected."]}}function X(e,t){let o=e?c.relative(e,t).split(c.sep).join("/"):c.resolve(t),n=c.basename(t).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"project",r=createHash("sha256").update(o).digest("hex").slice(0,12);return `${n}--${r}`}function Q(e){return e.lines?"lines":e.statements?"statements":e.branches?"branches":"functions"}async function ie(e$1={}){let t=await $(e$1.projectPath??process.cwd()),o=a(t),n=await V(t),r=Math.max(0,Math.min(100,Math.round(e$1.target??80))),i=await K(t,n),s=[],a$1=Date.now();if(e$1.run)for(let f of i.invocations){let w=await execa(f.executable,f.args,{cwd:f.cwd,reject:false,timeout:6e5}).catch(()=>({exitCode:1}));if(s.push(Number(w.exitCode??1)),Number(w.exitCode??1)!==0)break}let l=await B(t).catch(()=>null),d=l?Q(l.metrics):"lines",m=l?.metrics[d]?.percent??null,b=e$1.run&&s.some(f=>f!==0)?"failed":m===null?"unavailable":m>=r?"passed":"below-target",h=X(o,t),v=c.join(t,k),E=o?`.workspai/reports/projects/${h}/project-test-coverage-last-run.json`:null,R={schemaVersion:L,generatedAt:new Date().toISOString(),status:b,project:{id:h,name:c.basename(t),path:t,workspacePath:o},runtime:n,runner:i.runner,target:{metric:d,percent:r},metrics:l?.metrics??{},files:l?.files??[],lowCoverageFiles:(l?.files??[]).map(f=>{let w=f.metrics[d]??f.metrics.lines??f.metrics.statements;return {path:f.path,percent:w?.percent??null,uncovered:Math.max(0,(w?.total??0)-(w?.covered??0))}}).filter(f=>f.percent===null||f.percent<r).sort((f,w)=>w.uncovered-f.uncovered||f.path.localeCompare(w.path)),source:l?.source??{format:"unknown",path:null,sha256:null},execution:{requested:e$1.run===true,invocations:i.invocations,exitCodes:s,durationMs:Date.now()-a$1},diagnostics:[...i.diagnostics,...l?[]:["No supported machine-readable coverage artifact was found."]],artifactPaths:{project:v,workspaceLatest:o?c.join(o,k):null,workspaceProject:o&&E?c.join(o,E):null}};return o&&E&&await f(o,k,[{relativePath:k,payload:R},{relativePath:E,payload:R}]),await e(t,k,R),R}export{L as a,k as b,ie as c};
@@ -1,36 +0,0 @@
1
- import {b as b$4,a as a$1}from'./chunk-THIOE2PB.js';import {b as b$2,f as f$2,j,k,h as h$2,i,l,m,n,o,p as p$2,q,r,t,v,x,s as s$1,u as u$1,w,y,z,A,B,C,D,E,F,G,H as H$1,a as a$3,I}from'./chunk-3D3PFPP5.js';import {b as b$1,c,d as d$1}from'./chunk-WJY7ZXVJ.js';import {b as b$3}from'./chunk-LPCL4U4L.js';import {d as d$2}from'./chunk-XHRHNVCZ.js';import {h,g as g$1}from'./chunk-DZ4VKAXB.js';import {p,k as k$1,f as f$3}from'./chunk-FUPHQOJB.js';import {p as p$1}from'./chunk-B4CPDK6J.js';import {d}from'./chunk-MBRU3VWJ.js';import {a as a$2,b as b$5}from'./chunk-ULR66OJR.js';import {b,a}from'./chunk-62K2H72S.js';import {f,g,h as h$1}from'./chunk-MOSXTVPU.js';import s from'path';import f$1 from'fs-extra';var Q=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var kt="workspace-operational-skill.v1";function ft(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ze(e){let t=ft(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:kt,skillId:t,canonicalPath:H$1(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...Q],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var ht=b.skillsIndex;function Qe(e){let t=[...e.skills].sort((n,c)=>n.skillId.localeCompare(c.skillId)),r=e.inputsHash??f$3({skillIds:t.map(n=>n.skillId),paths:t.map(n=>n.canonicalPath)});return {schemaVersion:ht,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(n=>({skillId:n.skillId,path:n.canonicalPath,schemaVersion:n.schemaVersion,title:n.title}))}}var et=[a.agentIndex,b$1,d$2],wt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${a.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${a.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."]},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${a.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${a.verify}\` for verdict and blocking reasons.`,"Read `.workspai/reports/artifact-remediation-plan-last-run.json` when a Studio or agent repair path is needed.","List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."]},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Require project-scoped test/build commands before promoting the migration.","Document rollback and verification signals."]},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Prefer workspace run test/build for affected projects.","Re-run `workspace verify` after evidence refresh."]},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:["Read `.workspai/workspace.contract.json` for publishes/consumes/owns edges.","List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."]}];function ee(e){return `npx workspai ${e}`.trim()}function At(e){let t=[`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",...et.map(r=>`- \`${r}\``),"","## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",ee("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
- `)}function Pt(e){return e?.safeCommands?.length?e.safeCommands.slice(0,8).map(t=>t.display):[ee("workspace verify --json"),ee("doctor workspace --json")]}function Rt(e){return e?.projects?.length?e.projects.slice(0,12).map(r=>{let n=r.contracts?.owns?.join(", ")||"none",c=r.contracts?.publishes?.join(", ")||"none",l=r.contracts?.consumes?.join(", ")||"none";return `- **${r.slug}**: owns \`${n}\`; publishes \`${c}\`; consumes \`${l}\``}).join(`
3
- `):void 0}function tt(e){let t=e.model.workspace.name,r=e.model.projects.map(l=>l.name).sort(),n=Pt(e.context??null),c=Rt(e.contract??null);return wt.map(l=>{let p=At({template:l,workspaceName:t,scopedProjects:r,verificationCommands:n,contractSummary:c});return Ze({skillId:l.skillId,title:l.title,triggers:l.triggers,requiredReports:[...et],scopedProjects:r,verificationCommands:n,promptStem:I[l.skillId],markdown:p})})}async function rt(e){let t=s.resolve(e.workspacePath),r=[],n=f$3({skills:e.skills.map(l=>({id:l.skillId,path:l.canonicalPath,hash:f$3({markdown:l.markdown})}))}),c=Qe({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n});if(e.write){for(let p of e.skills){let o=s.join(t,p.canonicalPath);await f$1.ensureDir(s.dirname(o)),await f$1.writeFile(o,p.markdown,"utf8"),r.push(p.canonicalPath);}let l=s.join(t,b$2);await f$1.ensureDir(s.dirname(l)),await f$1.writeJson(l,c,{spaces:2}),r.push(b$2);}return {skills:e.skills,index:c,writtenPaths:r}}function nt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",ee("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
- `)}var St={"workspai-diagnose-api-failure":p$2,"workspai-release-readiness":t},xe="## Workspace verification (hydrated)";function yt(e){let t=[xe,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`
5
- `)}async function at(e){let t=s.resolve(e.workspacePath),r=[];for(let n of e.skills){let c=St[n.skillId];if(!c)continue;let l=s.join(t,c);if(!await f$1.pathExists(l))continue;let p=await f$1.readFile(l,"utf8"),o=yt(n),A=p.includes(xe)?p.replace(new RegExp(`${xe}[\\s\\S]*$`),o.trimEnd()):`${p.trimEnd()}
6
-
7
- ${o}`;e.write&&await f$1.writeFile(l,`${A.trimEnd()}
8
- `,"utf8"),r.push(c);}return r}var Ct="workspai-agent-customization-pack-capabilities.v1";function ot(){return {schemaVersion:Ct,presets:{minimal:{meaning:"Generate the portable grounding index, AGENTS.md, and provider-specific lightweight instructions.",requiredOutputs:[a.agentIndex,a.agentCustomizationPack,a.agents]},enterprise:{meaning:"Generate the full VS Code-native pack: instructions, prompts, skills, custom agents, and validation metadata.",requiredOutputs:[a.agentIndex,a.agentCustomizationPack,a.agents,l,p$2,B,".github/agents/workspai-advisor.agent.md",D,b$2]}},targets:{all:{meaning:"Generate every supported customization surface.",outputFamilies:["portable","vscode","copilot","cursor","claude"]},vscode:{meaning:"Generate VS Code-native customizations for Copilot Chat and agent workflows.",outputFamilies:["instructions","prompts","skills","agents","hooks"]},agents:{meaning:"Generate portable AGENTS.md grounding for any agent.",outputFamilies:["portable"]},copilot:{meaning:"Generate GitHub Copilot instructions, prompts, and skills.",outputFamilies:["instructions","prompts","skills"]},cursor:{meaning:"Generate Cursor rules.",outputFamilies:["rules"]},claude:{meaning:"Generate Claude Code grounding files.",outputFamilies:["rules","portable"]},codex:{meaning:"Use AGENTS.md and the report index as the Codex grounding layer.",outputFamilies:["portable"]},orca:{meaning:"Use AGENTS.md and the report index as the Orca/Grok grounding layer.",outputFamilies:["portable"]}},standardAnswerContract:[...Q],requiredReports:$.map(e=>({path:e.relativePath,label:e.label,required:e.required})),strictRules:["Required reports must exist.","Generated report paths must stay inside the workspace root.","Generated customization text must be English-only.","Agent answers must not claim pass, ready, or healthy without cited evidence.","Commands must distinguish display guidance from execution requests.","Agent hook files must be advisory and disabled by default unless the user explicitly enables them.","MCP design artifacts must stay read-mostly until write tools have explicit approval boundaries."],outputKinds:["report","grounding","instruction","prompt","skill","skill-resource","operational-skill","skills-index","explain-report","agent","rule","hook","mcp-design"],pathLayers:{l1CanonicalRoots:[".workspai/reports/",`${a$3}/`],l2PrefixedMirrorRoots:[".github/",".cursor/",".claude/"],l3SharedIndustryFiles:["AGENTS.md",".github/copilot-instructions.md","CLAUDE.md"]}}}var xt=b.agentIndex,Et=b.agentCustomizationPack,H=a.agentIndex,K=a.agentCustomizationPack;var $=[{relativePath:b$1,label:"Agent context pack",required:true},{relativePath:b$2,label:"Operational skills index",required:true},{relativePath:a.model,label:"Workspace model",required:false},{relativePath:a.knowledgeGraph,label:"Workspace knowledge graph",required:false},{relativePath:a.evaluationLastRun,label:"Workspace Intelligence evaluation",required:false},{relativePath:a.doctor,label:"Workspace doctor",required:false},{relativePath:".workspai/reports/doctor-project-last-run.json",label:"Project doctor",required:false},{relativePath:".workspai/reports/doctor-remediation-plan-last-run.json",label:"Doctor remediation plan",required:false},{relativePath:".workspai/reports/artifact-remediation-plan-last-run.json",label:"Artifact remediation plan",required:false},{relativePath:".workspai/reports/doctor-fix-result-last-run.json",label:"Doctor fix result",required:false},{relativePath:a.analyze,label:"Workspace analyze",required:false},{relativePath:".workspai/reports/pipeline-last-run.json",label:"Governance pipeline",required:false},{relativePath:a.readiness,label:"Release readiness",required:false},{relativePath:a.impact,label:"Workspace impact",required:false},{relativePath:a.verify,label:"Workspace verify",required:false},{relativePath:a.snapshot,label:"Workspace model snapshot",required:false},{relativePath:a.diff,label:"Workspace model diff",required:false},{relativePath:a.explain,label:"Workspace explain",required:false},{relativePath:a.contractVerify,label:"Workspace contract verify",required:false},{relativePath:a.history,label:"Workspace intelligence history",required:false}];function It(){let e=$.map(n=>n.relativePath),r=b$3().consumers.agents.canonicalReadOrder.filter(n=>n!==H&&e.includes(n));return [...new Set([...r,...e])]}function P(e){return `npx workspai ${e}`.trim()}function be(e){return e&&typeof e=="object"?e:null}function Ee(e,t=12){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.trim().length>0).slice(0,t):[]}function Ot(e){let t=Ee(e.blockers,12);if(t.length>0)return t;let r=Ee(e.blockingReasons,12);if(r.length>0)return r;let n=be(e.summary);return n&&Array.isArray(n.blockingReasons)?Ee(n.blockingReasons,12):[]}function bt(e){let t=[...new Set(e.map(r=>r.trim()).filter(Boolean))];return t.filter(r=>{let n=r.toLowerCase();return !t.some(c=>{if(c===r||!c.includes(":"))return false;let l=c.toLowerCase();return l.length>n.length&&l.endsWith(n)})})}function _t(e){for(let t of ["generatedAt","updatedAt","timestamp"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}if(Array.isArray(e.entries)){let t=e.entries.map(r=>be(r)?.generatedAt).filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim()).filter(r=>Number.isFinite(Date.parse(r)));if(t.length>0)return t.reduce((r,n)=>Date.parse(n)>Date.parse(r)?n:r)}}function Tt(e,t,r){if(!e)return true;let n=Date.parse(e);return Number.isFinite(n)?r.getTime()-n>t*60*60*1e3:true}function vt(e,t,r){return e.path===a.snapshot?false:Tt(e.generatedAt,t,r)}function Wt(e){let t=e&&e.length>0?e:["all"];return t.includes("all")?new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]):new Set(t)}function S(e,t){return e.has("all")||e.has(t)}function jt(e){return S(e,"copilot")||S(e,"vscode")}function Lt(e){return e??"enterprise"}function Nt(e){return e===b$2?"skills-index":e.includes("workspace-explain-last-run.json")?"explain-report":(e.startsWith(`${a$3}/`)||e.startsWith(".rapidkit/skills/"))&&e.endsWith(".md")?"operational-skill":e.includes("hooks")||e===F||e===G?"hook":e.includes("mcp")||e===D||e===E?"mcp-design":e.endsWith(".json")?"report":e.includes("/instructions/")||e.endsWith("copilot-instructions.md")?"instruction":e.includes("/prompts/")?"prompt":e.includes("/skills/")&&e.endsWith("/SKILL.md")?"skill":e.includes("/skills/")?"skill-resource":e.includes("/agents/")?"agent":e.includes("/rules/")||e.endsWith(".mdc")?"rule":"grounding"}function Gt(e){return e.startsWith(".github/")?["vscode","copilot"]:e.startsWith(".cursor/")?["cursor"]:e.startsWith(".claude/")||e==="CLAUDE.md"?["claude"]:e==="AGENTS.md"||e.startsWith(".rapidkit/")?["agents","codex","orca","vscode"]:e.startsWith(".vscode/")?["vscode"]:["agents"]}function Dt(e,t){return ot().presets[t].requiredOutputs.includes(e)}async function $t(e,t){if(t)return t;let r=await d(e,k$1)??s.join(e,k$1);if(await f$1.pathExists(r))try{let n=await f$1.readJson(r);return b$5(k$1,n,r),n}catch{}return p({workspacePath:e,includeEvidence:true})}function Kt(e){return e.length>0&&!s.isAbsolute(e)&&!e.split(/[\\/]+/).includes("..")}function Ht(e){return Object.fromEntries(["all","vscode","agents","copilot","cursor","claude","codex","orca"].map(r=>[r,{enabled:e.targets.includes("all")||e.targets.includes(r),outputs:e.outputs.filter(n=>n.targets.includes(r)).map(n=>n.path).sort()}]))}async function Mt(e,t){try{if(!await f$1.pathExists(e))return {payload:null,exists:false,validity:"missing"};let r=await f$1.readJson(e),n=be(r);return n?a$2(t)?(b$5(t,n,e),{payload:n,exists:true,validity:"valid"}):{payload:n,exists:true,validity:"uncontracted"}:{payload:null,exists:true,validity:"invalid",validationError:"Artifact root must be a JSON object"}}catch(r){return {payload:null,exists:true,validity:"invalid",validationError:r instanceof Error?r.message:String(r)}}}async function st(e){let t=e.now??new Date,r=e.staleAfterHours??24,n=[],c=[];for(let o of $){let A=await d(e.workspacePath,o.relativePath)??s.join(e.workspacePath,o.relativePath),h=await Mt(A,o.relativePath),g=h.payload;h.validity==="invalid"?c.push(`Invalid evidence contract: ${o.relativePath}`):g&&c.push(...Ot(g)),n.push({path:o.relativePath,label:o.label,required:o.required,exists:h.exists,validity:h.validity,validationError:h.validationError,generatedAt:g?_t(g):void 0,commandId:typeof g?.commandId=="string"?g.commandId:void 0,exitCode:typeof g?.exitCode=="number"?g.exitCode:void 0});}let l=bt(c).slice(0,16),p=b$3();return {schemaVersion:xt,generatedAt:t.toISOString(),workspaceRoot:e.workspacePath,intelligenceChain:{schemaVersion:p.schemaVersion,contractPath:p.contractPath,currentStep:"agent-sync"},readOrder:It(),blockers:l,staleAfterHours:r,reports:n,refreshCommand:P("workspace agent-sync --write --refresh-context")}}function it(e){let t=["# Workspai agent grounding","","Cross-tool instructions for Copilot, Cursor, Claude Code, Codex, Grok, and other agents.","","## Read order (mandatory before workspace diagnosis)","",`1. \`${a.agentIndex}\` \u2014 latest blockers, timestamps, and report paths`,`2. \`${a.agentContext}\` \u2014 read only task-relevant context`,"3. Read only the task-relevant evidence artifacts listed in the index.","4. Use `workspace graph search <query> --limit 12 --json` or MCP `searchWorkspaceGraph` before loading the full graph.","","Do **not** full-repo scan or inject the complete graph when a bounded query can answer the task.","","## Regenerate intelligence","","```bash",P("workspace agent-sync --write --refresh-context"),P("workspace context --for-agent --json --write"),P("pipeline --json --write"),"```",""];if(e.index.blockers.length>0){t.push("## Current blockers","");for(let r of e.index.blockers.slice(0,12))t.push(`- ${r}`);t.push("");}if(e.context?.safeCommands?.length){t.push("## Safe commands (prefer these)","");for(let r of e.context.safeCommands.slice(0,10))t.push(`- \`${r.display}\` \u2014 ${r.description}`);t.push("");}return t.push("## Rules","","- Treat `.workspai/reports/*` as the source of truth for health, gates, and release posture.","- Prefer deterministic Workspai CLI commands over heuristic framework guesses.","- If evidence is missing or stale, run the refresh commands above before proposing fixes.","- Keep project-scoped advice aligned with the active project named in the context pack.",""),t.join(`
9
- `)}function qt(e){return ["# Workspai agent grounding","",`Generated: ${e.generatedAt}`,"",`This file is tool-agnostic. Synced agents should read it together with \`${a.agentIndex}\`.`,"","## Mandatory read order","",...e.readOrder.map((t,r)=>`${r+1}. \`${t}\``),"",e.blockers.length>0?"## Blockers":"",...e.blockers.length>0?e.blockers.map(t=>`- ${t}`):[],"","## Refresh","","```bash",e.refreshCommand,"```",""].filter(t=>t!=="").join(`
10
- `)}function Vt(){return ["# Workspai workspace grounding","","Before answering workspace, release, or architecture questions:","","1. Read `AGENTS.md` (managed Workspai section).",`2. Read \`${a.agentIndex}\` and only task-relevant context from \`${a.agentContext}\`.`,"3. Use bounded `workspace graph search` or MCP `searchWorkspaceGraph` before scanning the full repository.","","Regenerate stale intelligence:","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
11
- `)}function Ut(){return ["## Claude Code","",`- Load \`${a.agentIndex}\` before diagnosing blockers.`,"- Use `.claude/rules/workspai-evidence.md` for scoped Workspai evidence rules.","- Treat `.claude/rules/rapidkit-evidence.md` as a legacy compatibility mirror.","- Refresh grounding with `npx workspai workspace agent-sync --write`.",""].join(`
12
- `)}function Ft(){return ["---","description: Workspai workspace evidence and intelligence grounding","globs: []","alwaysApply: true","---","","Before proposing fixes in this workspace:","",`1. Read \`${a.agents}\` and \`${a.agentIndex}\`.`,`2. Read only task-relevant context from \`${a.agentContext}\`.`,"3. Prefer bounded graph search and evidence reports over full-repo exploration.","","Refresh when stale:","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
13
- `)}function zt(){return ["---",'applyTo: ".workspai/**,**/.workspai/**,.rapidkit/**,**/.rapidkit/**"',"description: Workspai evidence and intelligence artifacts","---","","When working under `.workspai/` or legacy `.rapidkit/`:","","- Treat `.workspai/reports/*` JSON reports as canonical gate and health evidence.",`- Start from \`${a.agentIndex}\` for read order and blockers.`,"- Do not invent pass/fail state \u2014 cite `exitCode`, `blockers`, and `generatedAt` fields.",""].join(`
14
- `)}function Bt(){return ["---",'applyTo: "**"',"description: Workspai workspace scope, evidence, and command discipline","---","","# Workspai Workspace Intelligence","","Use Workspai reports as the workspace source of truth before giving architectural, repair, release, or project lifecycle advice.","","## Scope rules","",`- Start from \`${a.agentIndex}\`; read only task-relevant context and evidence.`,"- Prefer bounded `workspace graph search` or MCP `searchWorkspaceGraph` over loading the complete graph.","- Distinguish workspace-level blockers from project-level blockers.","- When a project is active, cite its name, path, framework, and evidence source.","- Do not translate unsupported stack requests into unrelated native kits.","","## Answer contract","","Return answers with: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
15
- `)}function Jt(){return ["# Workspai evidence","","Applies when reading or editing `.workspai/reports/*`.","","- Start from `INDEX.json`, then `workspace-context-agent.json`.","- Use report blockers as the primary fix target.","- Regenerate with `npx workspai workspace agent-sync --write`.",""].join(`
16
- `)}function Yt(){return ["# Legacy RapidKit evidence alias","","Compatibility path only. Use `.claude/rules/workspai-evidence.md` as the canonical rule.",""].join(`
17
- `)}function Xt(){return ["---","description: Legacy RapidKit metadata compatibility alias",'globs: [".rapidkit/**", "**/.rapidkit/**"]',"alwaysApply: false","---","","Use `.cursor/rules/workspai-grounding.mdc` for canonical Workspai grounding.",""].join(`
18
- `)}function ct(e){return ["---",'applyTo: ".rapidkit/**,**/.rapidkit/**"',"description: Legacy RapidKit metadata compatibility alias","---","",`Use \`.github/instructions/workspai-${e}.instructions.md\` as the canonical Workspai instruction.`,""].join(`
19
- `)}function lt(){return ["---","description: Diagnose Workspai workspace blockers from evidence reports","---","","Diagnose this workspace using Workspai evidence only.","","Read:","",`- \`${a.agentIndex}\``,`- \`${a.agentContext}\``,"- Any fail/warn reports referenced in the index","","Return:","","1. Root cause grounded in report blockers","2. Smallest safe fix path (commands + file edits)","3. One verification command to prove recovery",""].join(`
20
- `)}function te(e){return ["---",`description: ${e.description}`,"---","",e.objective,"","Read first:","",`- \`${a.agentIndex}\``,`- \`${a.agentContext}\``,"- Any report referenced by the current blocker or task","","Return:","",...e.expectedOutput.map((t,r)=>`${r+1}. ${t}`),"","Use the standard Workspai answer contract: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.",""].join(`
21
- `)}function T(e){return ["# "+e.title,"",...e.lines,""].join(`
22
- `)}function Zt(){return T({title:"MCP Tool Design",lines:["Workspai MCP is a read-mostly bridge over contract-validated workspace artifacts.","","Candidate read tools:",`- \`getWorkspaceModel\` \u2014 read \`${a.model}\`.`,`- \`getWorkspaceKnowledgeGraph\` \u2014 read \`${a.knowledgeGraph}\`.`,`- \`getWorkspaceEvaluation\` \u2014 read \`${a.evaluationLastRun}\` (or the live evaluation when requested).`,"- `queryWorkspaceEntities` \u2014 filter proof-backed graph entities by kind.","- `searchWorkspaceGraph` \u2014 retrieve bounded proof-backed context by text query.","- `getWorkspaceGraphEvidence` \u2014 resolve evidence for an entity or relation.","- `findWorkspaceGraphPath` \u2014 find a shortest proof-carrying relationship path.",`- \`getEvidenceIndex\` \u2014 read \`${a.agentIndex}\`.`,"- `getBlockers` \u2014 derive current blockers from INDEX and gate reports.","- `getSafeCommands` \u2014 read safe commands from `workspace-context-agent.json`.","- `getProjectContext` \u2014 return one project-scoped slice of the workspace model.","- `getArtifact` \u2014 read one explicit artifact path inside the workspace root.",`- \`listOperationalSkills\` \u2014 read \`${a.skillsIndex}\`.`,"- `getWorkspaceExplain` \u2014 read/build workspace explain for release-blocked or project scope.","- `refreshWorkspaceIntelligence` \u2014 explicit user-approved refresh command only.","","Write or repair tools require explicit approval boundaries and are intentionally not part of the first read-mostly design."]})}function Qt(e){return `${JSON.stringify({schemaVersion:"workspai-mcp-design.v1",generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,status:"design-only",mode:"read-mostly",safety:{writeToolsEnabled:false,approvalRequiredForRefresh:true,artifactReadsMustStayInsideWorkspace:true},candidateTools:[{name:"getWorkspaceModel",reads:[a.model],mutates:false},{name:"getWorkspaceKnowledgeGraph",reads:[a.knowledgeGraph],mutates:false},{name:"getWorkspaceEvaluation",reads:[a.evaluationLive,a.evaluationLastRun],mutates:false},{name:"queryWorkspaceEntities",reads:[a.knowledgeGraph],mutates:false},{name:"searchWorkspaceGraph",reads:[a.knowledgeGraph],mutates:false},{name:"getWorkspaceGraphEvidence",reads:[a.knowledgeGraph],mutates:false},{name:"findWorkspaceGraphPath",reads:[a.knowledgeGraph],mutates:false},{name:"getEvidenceIndex",reads:[a.agentIndex],mutates:false},{name:"getBlockers",reads:[a.agentIndex,a.verify,".workspai/reports/pipeline-last-run.json"],mutates:false},{name:"getSafeCommands",reads:[a.agentContext],mutates:false},{name:"getProjectContext",reads:[a.model,a.agentContext],mutates:false},{name:"getArtifact",reads:["requested workspace-relative artifact path"],mutates:false},{name:"listOperationalSkills",reads:[a.skillsIndex],mutates:false},{name:"getWorkspaceExplain",reads:[a.explain,a.verify,a.impact],mutates:false},{name:"refreshWorkspaceIntelligence",command:P("workspace agent-sync --write --refresh-context"),mutates:true,approvalRequired:true}]},null,2)}
23
- `}function er(e){return `${JSON.stringify({schemaVersion:"workspai-agent-hooks.v1",generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,enabledByDefault:false,mode:"advisory",hooks:[{name:"workspai-pre-tool-use-workspace-boundary",event:"PreToolUse",purpose:"Block or warn on state-changing commands outside the active workspace root.",defaultAction:"warn",rules:["Allow read-only commands.","Warn before write/delete commands outside workspaceRoot.","Never run destructive commands without explicit user approval."]},{name:"workspai-post-tool-use-verify-suggestion",event:"PostToolUse",purpose:"Suggest non-destructive verification commands after edits.",defaultAction:"suggest",commands:[P("doctor workspace"),P("workspace verify --strict --json")]},{name:"workspai-user-prompt-submit-scope-hint",event:"UserPromptSubmit",purpose:"Inject lightweight workspace scope and evidence index hints.",defaultAction:"inject-context-hint",reads:[a.agentIndex,a.agentContext]}]},null,2)}
24
- `}function dt(e){let t=["---","name: workspai-workspace-intelligence","description: Use Workspai workspace intelligence reports to answer, repair, verify, and release with evidence","---","","# Workspai Workspace Intelligence","","Use this skill for workspace architecture, project lifecycle, blocker repair, release readiness, agent grounding, and CI evidence questions.","","## Decision flow","","1. Load `resources/scope-model.md`.",`2. Load \`${a.agentIndex}\`.`,`3. Load \`${a.agentContext}\`.`,`4. Load \`${a.skillsIndex}\` when operational playbooks are needed.`,"5. Load the smallest evidence report required for the task.","6. Answer with Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Rules","","- Prefer Workspai reports over full-repo scans.","- Never claim a gate passed without a cited report.","- Separate display commands from execution requests.","- Keep project-scoped fixes inside the active project unless workspace evidence says otherwise.",""];return e?.trim()&&t.push(e.trim(),""),t.join(`
25
- `)}function re(e){return ["---",`name: ${e.name}`,`description: ${e.description}`,`tools: [${e.tools.map(t=>`'${t}'`).join(", ")}]`,"---","",`You are the ${e.name} agent for Workspai Workspace Intelligence.`,"",`Mode: ${e.mode}.`,"",`Start every task by reading \`${a.agentIndex}\` and \`${a.agentContext}\`.`,"","Use this answer contract:","","- Scope","- Evidence","- Diagnosis","- Fix Plan","- Run","- Verify","- Assumptions","","Do not invent health, readiness, or policy status. Cite report paths and command outputs.",""].join(`
26
- `)}function pt(){return ["---","name: workspai-grounding","description: Load Workspai workspace intelligence reports before diagnosing or changing code","---","","# Workspai grounding","","Use when the user asks about workspace health, release gates, doctor/pipeline failures, or project structure.","","## Workflow","",`1. Read \`${a.agentIndex}\``,`2. Read \`${a.agentContext}\``,"3. Read fail/warn evidence artifacts listed in the index","4. Propose the smallest safe fix with explicit verification commands","","## Refresh stale evidence","","```bash",P("workspace agent-sync --write --refresh-context"),"```",""].join(`
27
- `)}async function u(e,t,r){return r?(await f$1.ensureDir(s.dirname(e)),await f$1.writeFile(e,t,"utf8"),"written"):"skipped"}async function Ie(e){if(!e.write)return "skipped";let t=await f$1.pathExists(e.absolutePath)?await f$1.readFile(e.absolutePath,"utf8"):null,{upsertManagedAgentSection:r}=await import('./managed-agent-markers-COE5DJ3W.js'),n=r(t,e.generatedBody),c=e.preamble?`${e.preamble.trimEnd()}
28
-
29
- ${n}`:n;return await f$1.ensureDir(s.dirname(e.absolutePath)),await f$1.writeFile(e.absolutePath,c,"utf8"),"written"}function zr(e){if(!e?.trim())return;let t=new Set(["all","vscode","agents","copilot","cursor","claude","codex","orca"]),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.has(n));return r.length>0?r:void 0}function tr(e){let t=[...e.outputs].sort((n,c)=>n.path.localeCompare(c.path)),r=b$3();return {schemaVersion:Et,generatedAt:e.generatedAt,workspaceRoot:e.workspacePath,preset:e.preset,targets:[...e.targets].sort(),sourceReports:e.index.reports.filter(n=>n.exists).map(n=>n.path).sort(),intelligenceChain:{schemaVersion:r.schemaVersion,contractPath:r.contractPath,currentStep:"agent-sync"},outputInventory:t,capabilityMatrix:Ht({targets:e.targets,outputs:t}),drift:{missingRequired:e.missingRequired,staleReports:e.staleReports,strictViolations:e.strictViolations},answerContract:["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"],refreshCommand:P(`workspace agent-sync --write --refresh-context --preset ${e.preset}`),experimental:{hooksEnabled:e.experimentalHooks,mcpReady:t.some(n=>n.kind==="mcp-design")}}}async function Oe(e){let t$1=s.resolve(e.workspacePath),r$1=e.now??new Date,n$1=e.staleAfterHours??24,c$1=Wt(e.targets),l$1=[...c$1].sort(),p$3=Lt(e.preset),o$1=e.write===true,A$1=e.strict===true,h,g=null,ne=e.model;e.refreshContext&&(ne??=await p({workspacePath:t$1,includeEvidence:true}),g=await c({workspacePath:t$1,model:ne,agent:e.agent??"generic",scope:e.scope,includeEvidence:true}),o$1&&(h=await d$1(g,t$1)));let b=[],ae=[],oe=[],se=[],d=(i,k)=>{i==="written"?ae.push(k):oe.push(k),se.push({path:k,kind:Nt(k),targets:Gt(k),required:Dt(k,p$3),status:i==="written"?"written":e.dryRun?"planned":"skipped"});},ie="",ut=await $t(t$1,ne),ce=null;try{ce=(await p$1({workspacePath:t$1})).contract;}catch{ce=null;}let gt=tt({model:ut,context:g,contract:ce}),le=await rt({workspacePath:t$1,skills:gt,generatedAt:r$1.toISOString(),write:o$1});for(let i of le.skills)d(o$1?"written":"skipped",i.canonicalPath);d(o$1?"written":"skipped",b$2),ie=nt(le.index);let y$1=await st({workspacePath:t$1,staleAfterHours:n$1,now:r$1});if(d(await u(s.join(t$1,H),`${JSON.stringify(y$1,null,2)}
30
- `,o$1),H),d(await u(s.join(t$1,f$2),`${qt(y$1)}
31
- `,o$1),f$2),(S(c$1,"agents")||S(c$1,"vscode"))&&d(await Ie({absolutePath:s.join(t$1,"AGENTS.md"),generatedBody:it({index:y$1,context:g}),write:o$1}),"AGENTS.md"),S(c$1,"claude")){let i=s.join(t$1,"CLAUDE.md");if(o$1){let{upsertManagedAgentSection:k}=await import('./managed-agent-markers-COE5DJ3W.js'),m=await f$1.pathExists(i)?await f$1.readFile(i,"utf8"):"",w=k(m,Ut()),C=w.includes("@AGENTS.md")?w:`@AGENTS.md
32
-
33
- ${w}`;await f$1.ensureDir(s.dirname(i)),await f$1.writeFile(i,C,"utf8"),ae.push("CLAUDE.md");}else oe.push("CLAUDE.md");d(await u(s.join(t$1,j),`${Jt()}
34
- `,o$1),j),d(await u(s.join(t$1,k),`${Yt()}
35
- `,o$1),k);}if(S(c$1,"cursor")&&(d(await u(s.join(t$1,h$2),Ft(),o$1),h$2),d(await u(s.join(t$1,i),Xt(),o$1),i)),jt(c$1)){if(d(await Ie({absolutePath:s.join(t$1,".github/copilot-instructions.md"),generatedBody:Vt(),write:o$1}),".github/copilot-instructions.md"),d(await u(s.join(t$1,l),Bt(),o$1),l),d(await u(s.join(t$1,m),ct("workspace"),o$1),m),d(await u(s.join(t$1,n),zt(),o$1),n),d(await u(s.join(t$1,o),ct("evidence"),o$1),o),d(await u(s.join(t$1,p$2),lt(),o$1),p$2),d(await u(s.join(t$1,q),lt(),o$1),q),p$3==="enterprise"){let i=[[r,te({description:"Repair Workspai blockers with evidence and verification",objective:"Plan the smallest safe repair for the current Workspai blocker.",expectedOutput:["Blocker and affected workspace/project scope","Evidence paths and exact failing signals","Minimal fix plan","Human-run commands","Verification command and expected success signal"]})],[t,te({description:"Assess Workspai release readiness from evidence",objective:"Assess whether this workspace is release-ready using Workspai gates.",expectedOutput:["Readiness verdict with cited reports","Blocking gates","Safe next command","Verification checklist"]})],[v,te({description:"Onboard a project into Workspai Workspace Intelligence",objective:"Guide project onboarding using workspace model and create planner capabilities.",expectedOutput:["Target project scope","Native create, official generator, or existing lane","Safe commands","Post-onboarding verification"]})],[x,te({description:"Adopt an existing project into Workspai governance",objective:"Adopt an existing project without changing its runtime behavior.",expectedOutput:["Detected stack and confidence","Adoption plan","Generated metadata expectations","Doctor and workspace model verification"]})]];for(let[m,w]of i)d(await u(s.join(t$1,m),w,o$1),m);let k=[[s$1,i[0][1]],[u$1,i[1][1]],[w,i[2][1]],[y,i[3][1]]];for(let[m,w]of k)d(await u(s.join(t$1,m),w,o$1),m);if(e.hydratePrompts===true)for(let m of await at({workspacePath:t$1,skills:le.skills,write:o$1}))d(o$1?"written":"skipped",m);}if(d(await u(s.join(t$1,z),pt(),o$1),z),d(await u(s.join(t$1,A),pt(),o$1),A),p$3==="enterprise"){d(await u(s.join(t$1,B),dt(ie),o$1),B),d(await u(s.join(t$1,C),dt(ie),o$1),C);let i=[["artifact-map.md",T({title:"Artifact Map",lines:$.map(m=>`- \`${m.relativePath}\` \u2014 ${m.label}`)})],["command-map.md",T({title:"Command Map",lines:["- `npx workspai workspace agent-sync --write --refresh-context` \u2014 refresh agent grounding.","- `npx workspai workspace model --json --write` \u2014 refresh workspace model.","- `npx workspai doctor workspace` \u2014 refresh health evidence.","- `npx workspai workspace verify --strict --json` \u2014 verify release gates."]})],["scope-model.md",T({title:"Scope Model",lines:["- Workspace scope is the default source of truth.","- Project scope is selected only when the active task targets a specific project.","- Always name the workspace and project when giving repair or lifecycle advice."]})],["runtime-support.md",T({title:"Runtime Support",lines:["- Native create is available only for Workspai-owned scaffold contracts.","- Unsupported stacks should use the official lane when a stable ecosystem generator exists.","- Existing projects should use the existing lane when native create is unavailable."]})],["create-planner-capabilities.md",T({title:"Create Planner Capabilities",lines:["- Use `contracts/create-planner-capabilities.v1.json` to decide native, official, or existing.","- Do not map PHP, WordPress, Laravel, Rails, or Symfony requests to unrelated native kits.","- Explain unsupported native create requests and guide users to adopt/import."]})],["mcp-tools.md",Zt()]];for(let[m,w]of i){let C$1=`${s.dirname(B)}/resources/${m}`;d(await u(s.join(t$1,C$1),w,o$1),C$1);let Te=`${s.dirname(C)}/resources/${m}`;d(await u(s.join(t$1,Te),w,o$1),Te);}let k=[["workspai-advisor.agent.md",re({name:"Workspai Advisor",description:"Read-only workspace and project guidance using Workspai evidence",mode:"read-only",tools:["search","read"]})],["workspai-repair.agent.md",re({name:"Workspai Repair",description:"Turn Workspai blockers into minimal fixes and verification steps",mode:"repair",tools:["search","read","edit"]})],["workspai-release.agent.md",re({name:"Workspai Release",description:"Assess readiness, governance gates, and release safety from evidence",mode:"release",tools:["search","read"]})],["workspai-project-onboarder.agent.md",re({name:"Workspai Project Onboarder",description:"Guide create, import, and adopt flows with Workspai contracts",mode:"onboard",tools:["search","read","edit"]})]];for(let[m,w]of k){let C=`.github/agents/${m}`;d(await u(s.join(t$1,C),w,o$1),C);}}}if(p$3==="enterprise"){let i=Qt({workspacePath:t$1,generatedAt:y$1.generatedAt});b$5(D,JSON.parse(i)),d(await u(s.join(t$1,D),i,o$1),D),d(await u(s.join(t$1,E),i,o$1),E);}if(p$3==="enterprise"&&e.experimentalHooks===true){let i=er({workspacePath:t$1,generatedAt:y$1.generatedAt});b$5(F,JSON.parse(i)),d(await u(s.join(t$1,F),i,o$1),F),d(await u(s.join(t$1,G),i,o$1),G);}(S(c$1,"codex")||S(c$1,"orca"))&&(S(c$1,"agents")||d(await Ie({absolutePath:s.join(t$1,"AGENTS.md"),generatedBody:it({index:y$1,context:g}),write:o$1}),"AGENTS.md"));let de=o$1?await st({workspacePath:t$1,staleAfterHours:n$1,now:r$1}):y$1,M=de.reports.filter(i=>i.required&&!i.exists).map(i=>i.path),q$1=de.reports.filter(i=>i.exists&&vt(i,n$1,r$1)).map(i=>i.path);if(A$1){M.length>0&&b.push(`Missing required reports: ${M.join(", ")}`),q$1.length>0&&b.push(`Stale reports (>${n$1}h): ${q$1.join(", ")}`);let i=se.map(k=>k.path).filter(k=>!Kt(k));i.length>0&&b.push(`Unsafe generated output paths: ${i.join(", ")}`);}let V=o$1?await g$1({workspacePath:t$1,mode:e.projectGrounding??"managed",now:r$1}):void 0;A$1&&V&&V.skipped.length>0&&b.push(`Project grounding incomplete: ${V.skipped.map(i=>`${i.name} (${i.reason})`).join(", ")}`);let _e=tr({workspacePath:t$1,generatedAt:r$1.toISOString(),preset:p$3,targets:l$1,index:de,outputs:[...se,{path:K,kind:"report",targets:["agents","vscode","copilot","codex","orca"],required:true,status:o$1?"written":e.dryRun?"planned":"skipped"}],missingRequired:M,staleReports:q$1,strictViolations:b,experimentalHooks:e.experimentalHooks===true});if(o$1&&process.env.WORKSPAI_TEST_FAIL_AGENT_SYNC_BEFORE_PACK==="1")throw new Error("Injected agent-sync failure before generation commit.");return d(await u(s.join(t$1,K),`${JSON.stringify(_e,null,2)}
36
- `,o$1),K),{workspacePath:t$1,indexPath:s.join(t$1,H),packPath:s.join(t$1,K),pack:_e,contextPath:h,writtenFiles:ae,skippedFiles:oe,blockers:y$1.blockers,missingRequired:M,staleReports:q$1,strictViolations:b,projectLenses:V}}async function Br(e){if(e.write!==true)return Oe(e);let t=s.resolve(e.workspacePath),r=s.join(t,".workspai","transactions","agent-sync");await b$4(r);let n=await Oe({...e,write:false,dryRun:true});if(!n.pack)throw new Error("Agent-sync dry run did not produce an output inventory.");let c=[...n.pack.outputInventory.map(p=>p.path),H,K],l=await a$1({journalDirectory:r});try{for(let A of [...new Set(c)].sort()){let h=s.resolve(t,A),g=s.relative(t,h);if(g===".."||g.startsWith(`..${s.sep}`)||s.isAbsolute(g))throw new Error(`Agent-sync output escapes workspace root: ${A}`);await l.captureFile(h);}let p=await h(t);for(let A of p.resolved)for(let h of [f,g,h$1,"AGENTS.md",".gitignore"])await l.captureFile(s.join(A.projectPath,h));let o=await Oe(e);return await l.commit(),o}catch(p){try{await l.rollback();}catch(o){throw new AggregateError([p,o],"Agent-sync generation failed and rollback was incomplete.")}throw p}}export{kt as a,ht as b,Ct as c,xt as d,Et as e,H as f,K as g,$ as h,It as i,st as j,zr as k,Br as l};
@@ -1 +0,0 @@
1
- var o={model:".workspai/reports/workspace-model.json",knowledgeGraph:".workspai/reports/workspace-knowledge-graph.json",snapshot:".workspai/reports/workspace-model-snapshot.json",diff:".workspai/reports/workspace-model-diff-last-run.json",impact:".workspai/reports/workspace-impact-last-run.json",analyze:".workspai/reports/analyze-last-run.json",doctor:".workspai/reports/doctor-last-run.json",contractVerify:".workspai/reports/workspace-contract-verify-last-run.json",readiness:".workspai/reports/release-readiness-last-run.json",verify:".workspai/reports/workspace-verify-last-run.json",history:".workspai/reports/workspace-intelligence-history.json",agentContext:".workspai/reports/workspace-context-agent.json",agentIndex:".workspai/reports/INDEX.json",agentCustomizationPack:".workspai/reports/agent-customization-pack.json",skillsIndex:".workspai/reports/workspace-skills-index.json",agents:"AGENTS.md",explain:".workspai/reports/workspace-explain-last-run.json",intelligenceRun:".workspai/reports/workspace-intelligence-run-last-run.json",evaluationLive:".workspai/reports/workspace-intelligence-evaluation-live.json",evaluationLastRun:".workspai/reports/workspace-intelligence-evaluation-last-run.json",verifiedGoalStatus:".workspai/reports/verified-goal-last-run.json"},r={model:"workspace-model.v1",knowledgeGraph:"workspace-knowledge-graph.v1",snapshot:"workspace-model-snapshot.v1",diff:"workspace-model-diff.v1",impact:"workspace-impact.v1",analyze:"rapidkit-analyze-v1",doctor:"doctor-workspace-evidence-v1",contractVerify:"workspace-contract-verify.v1",readiness:"release-readiness-v1",verify:"workspace-verify.v1",history:"workspace-intelligence-history.v1",agentContext:"workspace-context.v1",agentIndex:"rapidkit-agent-reports-index.v1",agentCustomizationPack:"rapidkit-agent-customization-pack.v1",skillsIndex:"workspace-skills-index.v1",agents:null,explain:"workspace-explain.v1",intelligenceRun:"workspace-intelligence-run.v1",evaluationLive:"workspace-intelligence-evaluation.v1",evaluationLastRun:"workspace-intelligence-evaluation.v1",verifiedGoalStatus:"workspai.verified-goal-status.v1"},c={model:"contracts/workspace-intelligence/workspace-model.v1.json",knowledgeGraph:"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json",snapshot:"contracts/workspace-intelligence/workspace-model-snapshot.v1.json",diff:"contracts/workspace-intelligence/workspace-model-diff.v1.json",impact:"contracts/workspace-intelligence/workspace-impact.v1.json",analyze:"contracts/analyze-last-run.v1.json",doctor:"contracts/doctor-workspace-evidence.v1.json",contractVerify:"contracts/workspace-intelligence/workspace-contract-verify.v1.json",readiness:"contracts/release-readiness.v1.json",verify:"contracts/workspace-intelligence/workspace-verify.v1.json",history:"contracts/workspace-intelligence/workspace-intelligence-history.v1.json",agentContext:"contracts/workspace-intelligence/workspace-context.v1.json",agentIndex:"contracts/workspace-intelligence/agent-reports-index.v1.json",agentCustomizationPack:"contracts/workspace-intelligence/agent-customization-pack-report.v1.json",skillsIndex:"contracts/workspace-intelligence/workspace-skills-index.v1.json",agents:null,explain:"contracts/workspace-intelligence/workspace-explain.v1.json",intelligenceRun:"contracts/workspace-intelligence/workspace-intelligence-run.v1.json",evaluationLive:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",evaluationLastRun:"contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",verifiedGoalStatus:"contracts/workspace-intelligence/verified-goal-status.v1.json"},i={analyze:"analyze",workspace:"workspace <action> [subaction] [key] [value]",doctor:"doctor [scope]",readiness:"readiness"},p=["analyze","readiness","doctor","workspace"],l=["model","diff","impact","doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence","verify","context","agent-sync","explain"],k=["sync","baseline"],d={sync:[".workspai/workspace.contract.json",".workspai/workspace-registry.v1.json"],baseline:[o.snapshot]},e=o,s={model:{command:["workspace","model","--json","--write"],produces:[e.model,e.knowledgeGraph]},diff:{command:["workspace","diff","--from",e.snapshot,"--json"],produces:[e.diff]},impact:{command:["workspace","impact","--from",e.diff,"--json"],produces:[e.impact]},"doctor-evidence":{command:["doctor","workspace","--json"],produces:[e.doctor]},"contract-evidence":{command:["workspace","contract","verify","--strict","--json"],produces:[e.contractVerify]},"analyze-evidence":{command:["analyze","--json"],produces:[e.analyze]},"readiness-evidence":{command:["readiness","--json","--skip-verify"],produces:[e.readiness]},verify:{command:["workspace","verify","--from-impact",e.impact,"--json"],produces:[e.verify,e.history]},context:{command:["workspace","context","--for-agent","--json","--write","--no-agent-sync"],produces:[e.agentContext]},"agent-sync":{command:["workspace","agent-sync","--write","--json","--preset","enterprise"],produces:[e.agentIndex,e.agentCustomizationPack,e.skillsIndex,e.agents]},explain:{command:["workspace","explain","release-blocked","--json","--write"],produces:[e.explain]}};function w(n){return s[n]}export{o as a,r as b,c,i as d,p as e,l as f,k as g,d as h,s as i,w as j};
@@ -1 +0,0 @@
1
- import {b}from'./chunk-62K2H72S.js';var y=b.doctor,m="doctor-project-evidence-v1";function n(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function R(e,o){let r=n(e);if(!r)return false;let s=r.schemaVersion,i=r.evidenceType;return !(typeof s=="string"&&(s!==y&&s!==m||o==="workspace"&&s!==y||o==="project"&&s!==m)||typeof i=="string"&&(i!=="workspace"&&i!=="project"||o&&i!==o))}function c(e,o){let r=e[o];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`Doctor evidence ${o} must be a non-negative integer.`);return Number(r)}function v(e){if(Array.isArray(e.projects))return e.projects.map(n).filter(r=>r!==null);let o=n(e.project);return o?[o]:[]}function S(e){let o=n(e);if(!o)throw new Error("Doctor evidence must be an object.");let r=n(o.healthScore);if(!r||typeof r.verdict!="string")return;let s=c(r,"total"),i=c(r,"passed"),f=c(r,"warnings"),u=c(r,"errors");if(s!==i+f+u)throw new Error("Doctor healthScore total must equal passed + warnings + errors.");let p=u>0?"blocked":f>0?"attention":"passed";if(r.verdict!==p)throw new Error(`Doctor healthScore verdict ${String(r.verdict)} contradicts score counts (${p}).`);let l=0,g=0;for(let t of v(o)){let w=Array.isArray(t.probes)?t.probes:[];l+=w.filter(d=>n(d)?.status==="fail").length,g+=Array.isArray(t.issues)?t.issues.length:0;let a=n(t.probeSummary);if(a){let d=c(a,"blockingFindings"),h=w.filter(k=>n(k)?.status==="fail").length+(Array.isArray(t.issues)?t.issues.length:0);if(d!==h)throw new Error("Doctor project probeSummary.blockingFindings contradicts failed probes and runtime issues.");let E=d>0?"blocked":c(a,"advisoryFindings")>0?"attention":"passed";if(a.verdict!==E||t.verdict!==E)throw new Error("Doctor project verdict contradicts its probe summary.")}}if(l+g>0&&u===0)throw new Error("Doctor evidence contains blocking findings but healthScore.errors is zero.")}export{y as a,m as b,R as c,S as d};
@@ -1,7 +0,0 @@
1
- import {a}from'./chunk-A5FBGRJA.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {j,u as u$1,e,a as a$2,t,f as f$1}from'./chunk-MOSXTVPU.js';import {s}from'./chunk-RJIYCDVC.js';import b from'crypto';import P from'fs';import d from'fs/promises';import i from'path';import O from'fs-extra';var x="project-workspace-link.v1",A="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 L(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 $(e){let t=i.resolve(e);for(;;){if(j(t))return t;let r=i.dirname(t);if(r===t)return null;t=r;}}function J(e){let t$1=i.resolve(e);for(;;){if([...t(t$1,"project.json"),...t(t$1,"context.json")].some(a=>P.existsSync(a)))return t$1;let r=i.dirname(t$1);if(r===t$1)return null;t$1=r;}}function y(e){return JSON.parse(P.readFileSync(e,"utf8"))}function I(e){let t=y(e);if(!t||typeof t!="object"||Array.isArray(t))throw new l("project.workspace.link-invalid",`Project workspace link is not a JSON object: ${e}`,{linkPath:e});let r=t;if(r.schemaVersion!==x||r.kind!==A||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!==".workspai/workspace.contract.json"||!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,"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 K(e,t,r){let a$1=a(e),o=new Map;for(let n of s(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);!j(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 u(e,t){if(e)throw t;return null}function Z(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 j(a)?e$1.requireProjectMembership===true&&o&&f(a,o)!==true?u(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?u$1(o,e):null,recovered:false}:u(t,new l("project.workspace.explicit-invalid",`Explicit workspace path is not a Workspai workspace: ${a}`,{workspacePath:a,projectPath:o}));let n=$(r);if(n)return e$1.requireProjectMembership===true&&o&&f(n,o)!==true?u(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?u$1(o,e):null,recovered:false};if(!o)return u(t,new l("project.workspace.unlinked","No Workspai project or workspace could be resolved from the current directory.",{startPath:r}));let c=u$1(o,e),p=null;if(P.existsSync(c)){let s;try{s=I(c);}catch(C){if(t)throw C;return null}let m=L({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===m&&j(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=K(o,e$1.env??process.env,e$1.platform??process.platform);return h.length>1?u(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?u(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})):u(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 T(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
- `,{encoding:"utf8",mode:384});try{await d.rename(r,e);}catch(a){let o=a.code;if(o!=="EEXIST"&&o!=="EPERM")throw a;await O.move(r,e,{overwrite:true});}}finally{await d.rm(r,{force:true}).catch(()=>{});}}async function M(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
- `)?`
4
- `:""}
5
- # Workspai machine-local workspace binding
6
- ${f$1}
7
- `;await d.writeFile(t,`${r}${n}`,"utf8");}async function F(e$1){let t=i.resolve(e$1.workspacePath),r=i.resolve(e$1.projectPath);if(!j(t))throw new l("project.workspace.explicit-invalid",`Cannot link project to an invalid Workspai workspace: ${t}`,{workspacePath:t,projectPath:r});let a$3=i.join(t,".workspai","workspace.contract.json"),o=e$1.workspaceName??i.basename(t),n=e$1.relativePath;if(P.existsSync(a$3)){let h=y(a$3);typeof h.workspace?.name=="string"&&(o=h.workspace.name);let s=a(r),m=h.projects?.find(w=>typeof w.externalPath=="string"?a(w.externalPath)===s:typeof w.relativePath=="string"&&!w.relativePath.startsWith("external/")&&a(i.resolve(t,w.relativePath))===s);m&&typeof m.relativePath=="string"&&(n=m.relativePath);}if(n??=i.relative(t,r).replace(/\\/g,"/"),(!n||n.startsWith(".."))&&(n=`external/${e$1.projectName}`),f(t,r)!==true)throw new l("project.workspace.membership-missing",`Project is not registered in the canonical workspace contract: ${e$1.projectName}`,{workspacePath:t,projectPath:r,projectName:e$1.projectName});let c={schemaVersion:x,kind:A,generatedAt:(e$1.now??new Date).toISOString(),state:"active",workspace:{name:o,root:t,marker:_(t),contract:".workspai/workspace.contract.json"},project:{name:e$1.projectName,relativePath:n,relationship:e$1.relationship},integrity:{algorithm:"sha256",binding:L({workspaceName:o,workspacePath:t,projectName:e$1.projectName,projectPath:r,relativePath:n,relationship:e$1.relationship})}};a$1(c,"contracts/project-workspace-link.v1.json","Project workspace link");let p=i.join(r,a$2,e);return await M(r),await T(p,c),{linkPath:p,link:c}}async function ee(e,t$1="linked"){if(!e.projectPath)return null;let r=t(e.projectPath,"project.json").find(o=>P.existsSync(o)),a=i.basename(e.projectPath);if(r)try{let o=y(r);typeof o.name=="string"?a=o.name:typeof o.slug=="string"&&(a=o.slug);}catch{}return F({workspacePath:e.workspacePath,projectPath:e.projectPath,projectName:a,relationship:t$1})}export{l as a,Z as b,F as c,ee as d};
@@ -1,8 +0,0 @@
1
- import {a as a$2}from'./chunk-SQTV2OYU.js';import {a as a$5}from'./chunk-2OIBHUVH.js';import {a as a$3,e}from'./chunk-GHB6QMQH.js';import {d,a as a$1,e as e$1}from'./chunk-MBRU3VWJ.js';import {a}from'./chunk-62K2H72S.js';import a$4 from'chalk';import se from'fs';import b from'path';import {execa}from'execa';var G="autopilot-release-last-run.json",V="autopilot-release.json";function j(r){try{return JSON.parse(r)}catch{return null}}function Re(r){let e=b.resolve(r),n=a$5(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 re(r){let e=r.toLowerCase();return e==="pass"?"pass":e==="warn"?"warn":e==="fail"?"fail":"warn"}function oe(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 Se(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 be(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 se.promises.mkdir(b.dirname(r),{recursive:true}),await se.promises.writeFile(r,`${JSON.stringify(e,null,2)}
2
- `,"utf-8");}async function Me(r){let e$2=Re(r.workspacePath),n=r.mode,o=[],t=[],F,H,D,q,Q,X=0,f=false,T=0,L=0,N=-1,W=-1,c="skipped",d$1="skipped",ae=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([...ae],e$2),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=j(l.stdout),E=p&&p.healthScore&&typeof p.healthScore=="object"?p.healthScore:{},k=Number(E.errors??0),$=Number(E.warnings??0);Number.isFinite(k)&&k>0?(c="fail",t.push(`doctor workspace reports ${k} error(s)`)):Number.isFinite($)&&$>0&&(c="warn");}N=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=Date.now(),w=await S(["analyze","--json"],e$2),v=Date.now()-g;H=await d(e$2,a.analyze)??a$1(e$2,a.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=j(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:v,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 P=Date.now(),h=await S(["readiness","--json"],e$2),y=Date.now()-P;if(d$1="fail",h.crashed)d$1="fail",f=true,t.push(`readiness execution error: ${h.stderr||"unknown error"}`);else if(h.exitCode!==0)d$1="fail",t.push("readiness command failed");else {let p=j(h.stdout),E=String(p?.overallStatus??"fail");if(d$1=re(E),typeof p?.evidencePath=="string"&&p.evidencePath.trim().length>0&&(F=p.evidencePath),d$1==="fail"){let k=Array.isArray(p?.blockingReasons)?p?.blockingReasons.filter($=>typeof $=="string"):[];k.length>0?t.push(...k.map($=>`readiness: ${$}`)):t.push("readiness overall status is fail");}}W=o.push({name:"readiness",status:d$1,durationMs:y,summary:`readiness overall status is ${d$1}`})-1,n==="enforce"&&d$1==="warn"&&t.push("readiness reported warnings under enforce mode");}let ne=Date.now(),z=await S(["doctor","workspace","--plan","--json"],e$2),ie=Date.now()-ne,R="warn";if(z.crashed)R="fail",f=true,t.push(`doctor remediation plan execution error: ${z.stderr||"unknown error"}`);else if(z.exitCode!==0)R="fail",t.push("doctor remediation plan command failed");else {let s=j(z.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&&(T=m),Number.isFinite(g)&&g>0&&(L=g),Number.isFinite(m)&&m===0?R="pass":R="warn";}if(o.push({name:"remediation-plan",status:R,durationMs:ie,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$2),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=L>0?L:T>0?T:1;let w=await S(["doctor","workspace","--json"],e$2);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=j(w.stdout),P=i&&i.healthScore&&typeof i.healthScore=="object"?i.healthScore:{},h=Number(P.errors??0),y=Number(P.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";}N>=0&&(o[N].status=c,o[N].summary=`doctor workspace post-apply status is ${c}`);let v=await S(["readiness","--json"],e$2);if(v.crashed)d$1="fail",f=true,t.push(`post-apply readiness execution error: ${v.stderr||"unknown error"}`);else if(v.exitCode!==0)d$1="fail",t.push("post-apply readiness command failed");else {let i=j(v.stdout),P=String(i?.overallStatus??"fail");if(d$1=re(P),typeof i?.evidencePath=="string"&&i.evidencePath.trim().length>0&&(F=i.evidencePath),d$1==="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");}}W>=0&&(o[W].status=d$1,o[W].summary=`readiness post-apply overall status is ${d$1}`);}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 le=Date.now(),x="pass",A="workspace test/build completed for selected projects";try{let s=await a$2({workspacePath:e$2,stage:"test",affected:true,since:r.since,parallel:r.parallel,maxWorkers:r.maxWorkers,strict:true,json:true,enforceGates:false});D=a$1(e$2,b.join(".workspai","reports",a$3)),await e(e$2,s),q=D;let l=oe(s);if(l==="fail")x="fail",A="workspace test stage failed for selected projects",t.push("workspace run test failed for selected projects");else {l==="warn"&&(x="warn",A="workspace test stage completed with warnings",n==="enforce"&&t.push("workspace run test reported warnings under enforce mode"));let m=await a$2({workspacePath:e$2,stage:"build",affected:true,since:r.since,parallel:r.parallel,maxWorkers:r.maxWorkers,strict:true,json:true,enforceGates:false});await e(e$2,m),Q=D;let g=oe(m);g==="fail"?(x="fail",A="workspace build stage failed for selected projects",t.push("workspace run build failed for selected projects")):g==="warn"&&(x="warn",A="workspace test/build completed with warnings",n==="enforce"&&t.push("workspace run test/build reported warnings under enforce mode"));}}catch(s){x="fail",A="workspace test/build orchestration failed",f=true,t.push(`workspace run orchestration error: ${s instanceof Error?s.message:String(s)}`);}let ce=Date.now()-le;o.push({name:"workspace-run-test-build",status:x,durationMs:ce,summary:A});let M=o.filter(s=>s.status==="warn").length,pe=o.filter(s=>s.status==="fail").length,_=n==="enforce"?o.some(s=>s.status==="warn"||s.status==="fail"):pe>0,C=[...new Set(t)],O=f||_?Math.max(1,C.length):0,ue=O>0?C:[],de=O===0?C:[],fe=Se(o),me=f||_?"blocked":M>0?"partial":"approved",ge=f?3:_?1:M>0?2:0,we=be({mode:n,executionError:f,blockers:C,hasWarnings:M>0}),Y=a$1(e$2,".workspai/reports"),he=b.join(Y,G),ke=b.join(Y,V),u={schemaVersion:"autopilot-release-v1",generatedAt:new Date().toISOString(),workspacePath:e$2,mode:n,summary:{releaseScore:fe,verdict:me,blockers:O,warnings:M,safeFixesApplied:X,manualActions:C.length,exitCode:ge},stages:o,blockingReasons:ue,warningReasons:de,nextActions:we,artifacts:{reportPath:he,aliasEvidencePath:ke,analyzeEvidencePath:H,readinessEvidencePath:F,workspaceRunEvidencePath:D,workspaceRunTestPath:q,workspaceRunBuildPath:Q},enterpriseControls:{jsonReady:true,evidencePath:`.workspai/reports/${G}`,aliasEvidencePath:`.workspai/reports/${V}`}};if(await e$1(e$2,`.workspai/reports/${G}`,u),await e$1(e$2,`.workspai/reports/${V}`,u),r.output&&await xe(b.resolve(r.output),u),!r.json){console.log(a$4.bold.cyan(`
3
- \u{1F680} Workspai Autopilot Release
4
- `)),console.log(a$4.bold(`Workspace: ${a$4.cyan(b.basename(e$2))}`)),console.log(a$4.gray(`Path: ${e$2}`)),console.log(a$4.white(`Mode: ${n}`)),console.log(a$4.white(`Verdict: ${u.summary.verdict==="approved"?a$4.green("approved"):u.summary.verdict==="partial"?a$4.yellow("partial"):a$4.red("blocked")}`)),console.log(a$4.white(`Release score: ${u.summary.releaseScore}`));for(let s of u.stages){let l=s.status==="pass"?a$4.green("PASS"):s.status==="warn"?a$4.yellow("WARN"):s.status==="skipped"?a$4.gray("SKIP"):a$4.red("FAIL");console.log(` - ${s.name}: ${l} ${s.summary} (${s.durationMs}ms)`);}if(u.blockingReasons.length>0){console.log(a$4.bold.red(`
5
- Blocking reasons:`));for(let s of u.blockingReasons)console.log(a$4.red(` - ${s}`));}if(u.warningReasons.length>0){console.log(a$4.bold.yellow(`
6
- Warning reasons:`));for(let s of u.warningReasons)console.log(a$4.yellow(` - ${s}`));}if(u.nextActions.length>0){console.log(a$4.bold(`
7
- Next actions:`));for(let s of u.nextActions)console.log(a$4.gray(` - ${s}`));}console.log(a$4.gray(`
8
- Report: ${u.artifacts.reportPath}`));}return u}export{G as a,V as b,Me as c};
@@ -1,2 +0,0 @@
1
- import {w}from'./chunk-6HJJHEL6.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2,d,c,e as e$1}from'./chunk-MBRU3VWJ.js';import {b as b$1}from'./chunk-ULR66OJR.js';import {a,b}from'./chunk-62K2H72S.js';import {l}from'./chunk-OCGZNSOE.js';import {e}from'./chunk-RO73VVHW.js';import {s,t,p}from'./chunk-MOSXTVPU.js';import*as g from'path';import g__default from'path';import h from'fs-extra';var ge="unknown-run";function Z(e$1){let t=e();return !t||t===ge?e$1:{...e$1,runId:t}}async function Q(e,t){await h.ensureDir(g.dirname(e));let r=`${e}.${process.pid}.${Date.now()}.tmp`;try{await h.writeJSON(r,t,{spaces:2}),await h.move(r,e,{overwrite:true});}finally{await h.remove(r).catch(()=>{});}}function X(e){return p(e,"imported-projects.json")}async function I(e){let t=(await Promise.all(s(e,"imported-projects.json").map(async r=>await h.pathExists(r)?r:null))).find(r=>typeof r=="string");if(!t)return [];try{let r=await h.readJSON(t);if(!r||typeof r!="object"||r.version!==1||!Array.isArray(r.projects))throw new Error("expected a version 1 registry with a projects array");let o=r.projects,a=o.filter(c=>{if(!c||typeof c!="object")return false;let i=c;return typeof i.name=="string"&&typeof i.path=="string"&&typeof i.stack=="string"&&typeof i.confidence=="string"&&typeof i.importedAt=="string"});if(a.length!==o.length)throw new Error("one or more project entries are invalid");return a}catch(r){throw new Error(`Imported-project registry is invalid: ${t}`,{cause:r})}}async function Ne(e,t){if(t.length===0)return;let r=await I(e),o=new Map;for(let l of r)o.set(l.path,l);for(let l of t)o.set(l.path,l);let a=Array.from(o.values()).sort((l,u)=>l.name.localeCompare(u.name)).map(l=>({...l})),c={version:1,updatedAt:new Date().toISOString(),projects:a},i=X(e);await Q(i,c);}async function De(e,t){if(t.length===0)return;let r=await I(e),o=new Set(t.map(l=>g.resolve(l))),a=r.filter(l=>!o.has(g.resolve(l.path))),c={version:1,updatedAt:new Date().toISOString(),projects:a},i=X(e);await Q(i,c);}var $e="workspace-dependency-graph.v1",ee=["code-import","package-dep","event-pub-sub","service-dependsOn","shared-resource"],te=["inferred","contract","manual"];var E=".workspai/workspace.contract.json",fe=a.contractVerify,R=1,he=b.contractVerify,N=class extends Error{constructor(r){super(`Workspace contract verification failed: ${r.violations.join("; ")}`);this.verification=r;this.name="WorkspaceContractVerificationError";}verification};function se(e){return e.replace(/\\/g,"/")}function H(e){let t=se(e).trim();return !t||t.startsWith("/")||t.startsWith("~")||/^[a-zA-Z]:\//.test(t)||t.includes("\0")?false:!t.split("/").filter(Boolean).some(r=>r===".."||r===".")}function re(e,t){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-_.]+|[-_.]+$/g,"").slice(0,80)||t}function ke(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function we(e){let r=(Array.isArray(e.ports)?e.ports:[]).map(c=>{if(!c||typeof c!="object"||Array.isArray(c))return null;let i=c,l=Number(i.port);if(!Number.isInteger(l)||l<1||l>65535)return null;let u=i.protocol==="https"||i.protocol==="grpc"||i.protocol==="tcp"||i.protocol==="udp"?i.protocol:"http";return {name:typeof i.name=="string"&&i.name.trim()?i.name:"http",port:l,protocol:u}}).filter(c=>c!==null);if(r.length>0)return r;let o=e.frontend&&typeof e.frontend=="object"&&!Array.isArray(e.frontend)?e.frontend:void 0,a=Number(e.port??o?.default_port);return Number.isInteger(a)&&a>=1&&a<=65535?[{name:"http",port:a,protocol:"http"}]:[]}async function D(e){for(let t of e)if(await h.pathExists(t))return t;return null}async function Pe(e){for(let t of s(e,"workspace.json"))try{let r=await h.readJson(t);return {name:typeof r.workspace_name=="string"&&r.workspace_name.trim()||typeof r.name=="string"&&r.name.trim()||g__default.basename(e),profile:typeof r.profile=="string"?r.profile:void 0}}catch{}return {name:g__default.basename(e)}}async function ye(e){let t$1=[],r=[e],o=new Set,a=new Set([".git",".workspai",".rapidkit","node_modules",".venv","venv","dist","build","target",".next",".turbo",".cache"]);for(;r.length>0;){let c=r.shift();if(!c||o.has(c))continue;o.add(c);let i=await D(t(c,"project.json")),l=await D(t(c,"context.json"));if(i||l){t$1.push(i??l??"");continue}let u;try{u=await h.readdir(c,{withFileTypes:true});}catch{continue}for(let d of u)!d.isDirectory()||a.has(d.name)||a$1(d.name)||r.push(g__default.join(c,d.name));}return t$1.sort()}function Ce(e){let t=(e||"").toLowerCase();if(t.includes("fastapi"))return "fastapi";if(t.includes("nestjs"))return "nestjs";if(t.includes("springboot"))return "springboot";if(t.includes("gofiber"))return "fiber";if(t.includes("gogin"))return "gin"}function Ee(e,t){let r=(e||"").toLowerCase(),o=(t||"").toLowerCase();return r.includes("fastapi")?8e3:r.includes("nestjs")?3e3:r.includes("springboot")?8080:r.includes("gofiber")?3e3:r.includes("gogin")?8080:o==="node"?3e3:o==="python"?8e3:o==="java"||o==="go"?8080:null}function oe(e,t){let r=e;for(;t.has(r)&&r<65535;)r+=1;return r}function M(e,t,r){let o=e!==void 0&&e.source===void 0,a=Ee(t.kit,t.runtime),c=e?.ports||[],i=t.ports||[],u=(c.length>0?c:i.length>0?i:a?[{name:"http",port:oe(a,r),protocol:"http"}]:[]).map(p=>({...p,port:oe(p.port,r)}));for(let p of u)r.add(p.port);let d={...t,...e,slug:e?.slug||t.slug,relativePath:o&&e?.relativePath&&H(e.relativePath)?e.relativePath:t.relativePath,source:o&&e?.source||t.source,relationship:o&&e?.relationship||t.relationship,externalPath:o&&e?.externalPath||t.externalPath,runtime:e?.runtime||t.runtime,framework:e?.framework||t.framework,kit:e?.kit||t.kit,modules:e?.modules?.length?e.modules:t.modules,ports:u,contracts:{owns:e?.contracts?.owns||[],apis:e?.contracts?.apis||[],publishes:e?.contracts?.publishes||[],consumes:e?.contracts?.consumes||[],dependsOn:e?.contracts?.dependsOn||[],env:e?.contracts?.env||[]}},s=JSON.stringify(e||null)!==JSON.stringify(d);return {project:d,changed:s}}async function ce(e){let t$1=g__default.resolve(e.workspacePath),r=await Pe(t$1),o=await ye(t$1),a=await I(t$1),c=[];for(let d of a){let s=g__default.resolve(d.path),p=await D(t(s,"project.json"))??await D(t(s,"context.json"));!p||o.some(k=>g__default.resolve(k)===g__default.resolve(p))||c.push({projectJsonPath:p,registryEntry:d});}let i=[],l=[...o.map(d=>({projectJsonPath:d})),...c];for(let{projectJsonPath:d,registryEntry:s}of l){let p=g__default.dirname(g__default.dirname(d)),k=se(g__default.relative(t$1,p)),f=s!==void 0&&!H(k),P=re(s?.name||g__default.basename(p),g__default.basename(p)),y=f?`external/${P}`:k||P,w=await h.readJson(d),x=typeof w.kit_name=="string"&&w.kit_name||typeof w.kit=="string"&&w.kit||void 0,n=typeof w.framework=="string"&&w.framework||Ce(x);i.push({slug:s?.name||y||g__default.basename(p),relativePath:y,source:s?.source??"workspace",relationship:s?.relationship,externalPath:f?p:void 0,runtime:typeof w.runtime=="string"?w.runtime:void 0,framework:n,kit:x,modules:ke(w.modules),ports:we(w),contracts:{owns:[],apis:[],publishes:[],consumes:[],dependsOn:[],env:[]}});}let u=new Map;for(let d of i){let s=re(d.slug,d.relativePath),p=u.get(s);(!p||p.source!=="workspace"&&d.source==="workspace")&&u.set(s,d);}return {schemaVersion:R,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:r,projects:[...u.values()]}}async function et(e){let t=g__default.resolve(e.outputPath||a$2(e.workspacePath,E));if(await h.pathExists(t)&&e.force!==true)throw new Error(`Workspace contract already exists: ${t}. Use --force to overwrite.`);let r=await ce({workspacePath:e.workspacePath,now:e.now}),o=new Set,a={...r,projects:r.projects.map(i=>M(void 0,i,o).project)},c=await de({workspacePath:e.workspacePath,contractPath:t,contract:a});if(e.strict&&c.status==="failed")throw new N(c);return await ie({workspacePath:e.workspacePath,contractPath:t,contract:a,now:e.now}),{contractPath:t,contract:a}}async function tt(e){let t=g__default.resolve(e.workspacePath),r=a$2(t,E),o=await d(t,E)??r,a=await ce({workspacePath:t,now:e.now}),c=await h.pathExists(o)?await h.readJson(o):null,i=new Map((c?.projects||[]).map(f=>[f.slug,f])),l=new Set,u=[],d$1=[],s=[];for(let f of a.projects){let P=i.get(f.slug),y=M(P,f,l);P?y.changed&&d$1.push(f.slug):u.push(f.slug),s.push(y.project),i.delete(f.slug);}for(let f of i.values()){if(f.source)continue;let P=M(f,f,l);s.push(P.project);}let p={schemaVersion:R,kind:"rapidkit.workspace.contract",generatedAt:(e.now??new Date).toISOString(),workspace:{...c?.workspace||{},...a.workspace,name:a.workspace.name||c?.workspace?.name||g__default.basename(t)},projects:s.sort((f,P)=>f.slug.localeCompare(P.slug))},k=await de({workspacePath:t,contractPath:r,contract:p});if(e.strict&&k.status==="failed")throw new N(k);return await ie({workspacePath:t,contractPath:r,contract:p,now:e.now}),{contractPath:r,contract:p,addedProjects:u,updatedProjects:d$1,verification:k}}async function ne(e){return await h.pathExists(e)?{exists:true,contents:await h.readFile(e)}:{exists:false}}async function ae(e,t){if(!t.exists){await h.remove(e);return}await h.outputFile(e,t.contents);}async function ie(e){let{buildWorkspaceRegistrySummary:t,WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH:r}=await import('./workspace-registry-summary-HOQ3OBNT.js'),o=await t(e.workspacePath,{now:e.now,contract:e.contract}),a=a$2(e.workspacePath,r),c$1=i=>{if(!i||typeof i!="object"||Array.isArray(i))return JSON.stringify(i);let{generatedAt:l,...u}=i;return JSON.stringify(u)};if(await h.pathExists(e.contractPath)&&await h.pathExists(a)){let[i,l]=await Promise.all([h.readJson(e.contractPath),h.readJson(a)]);if(c$1(i)===c$1(e.contract)&&c$1(l)===c$1(o))return}b$1(E,e.contract),b$1(r,o),await c(e.workspacePath,E,async()=>{let[i,l]=await Promise.all([ne(e.contractPath),ne(a)]);try{if(e.contractPath===a$2(e.workspacePath,E)?await e$1(e.workspacePath,E,e.contract):(await h.ensureDir(g__default.dirname(e.contractPath)),await h.writeJson(e.contractPath,e.contract,{spaces:2})),process.env.WORKSPAI_TEST_FAIL_WORKSPACE_REGISTRY_PUBLISH==="1")throw new Error("Injected workspace registry summary publication failure.");await e$1(e.workspacePath,r,o);}catch(u){let s=(await Promise.allSettled([ae(e.contractPath,i),ae(a,l)])).filter(p=>p.status==="rejected");throw s.length>0?new AggregateError([u,...s.map(p=>p.reason)],"Workspace contract publication failed and rollback was incomplete."):u}});}async function pe(e){let t=e.contractPath??(await d(e.workspacePath,E)||a$2(e.workspacePath,E)),r=await h.readJson(t);return {contractPath:t,contract:r}}var je={metadata:[".workspai/project.json",".workspai/context.json",".rapidkit/project.json",".rapidkit/context.json"],manifests:["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","pyproject.toml","poetry.lock","requirements.txt","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","Cargo.toml","Gemfile","composer.json"],entrypoints:["src/main.ts","src/index.ts","src/app.ts","src/main.js","src/index.js","main.py","app/main.py","manage.py","main.go","cmd/main.go","Program.cs"],apiSpecifications:["openapi.yaml","openapi.yml","openapi.json","swagger.yaml","swagger.yml","swagger.json"],infrastructure:["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml","k8s","kubernetes","terraform"],documentation:["README.md","ARCHITECTURE.md","CONTRIBUTING.md","docs"]};function be(e,t){return t.externalPath?g__default.resolve(t.externalPath):g__default.resolve(e,t.relativePath)}async function ve(e){let t={metadata:[],manifests:[],entrypoints:[],apiSpecifications:[],infrastructure:[],documentation:[]};for(let[r,o]of Object.entries(je))for(let a of o)await h.pathExists(g__default.join(e,a))&&t[r].push(a);try{let r=await h.readdir(e,{withFileTypes:true});for(let o of r)o.isFile()&&(o.name.endsWith(".csproj")||o.name.endsWith(".sln"))&&t.manifests.push(o.name),o.isFile()&&o.name.endsWith(".tf")&&t.infrastructure.push(o.name);}catch{}for(let r of Object.values(t))r.sort((o,a)=>o.localeCompare(a));return t}function A(e){return !e||typeof e!="object"||Array.isArray(e)?[]:Object.keys(e).sort((t,r)=>t.localeCompare(r))}async function We(e){try{let t=await h.readJson(g__default.join(e,"package.json")),r={runtime:A(t.dependencies),development:A(t.devDependencies),peer:A(t.peerDependencies),optional:A(t.optionalDependencies)};return {...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{},...typeof t.private=="boolean"?{private:t.private}:{},scripts:A(t.scripts),dependencies:r,dependencyCount:new Set(Object.values(r).flat()).size}}catch{return}}async function Se(e){for(let t of [".env.example",".env.sample",".env.template"])try{return (await h.readFile(g__default.join(e,t),"utf8")).split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("#")&&o.includes("=")).map(o=>o.slice(0,o.indexOf("=")).trim()).filter(o=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(o)).sort((o,a)=>o.localeCompare(a))}catch{}return []}function Ae(e,t){try{let r=w(e);if(r.engine!=="unknown")return r;let o=h.pathExistsSync(g__default.join(e,"package.json"))?"npm":h.pathExistsSync(g__default.join(e,"pyproject.toml"))?"python":h.pathExistsSync(g__default.join(e,"requirements.txt"))?"pip":"unknown";return {...r,engine:o,runtime:t.runtime??r.runtime,framework:t.framework??r.framework,frameworkDisplayName:t.framework??r.frameworkDisplayName}}catch{return {schemaVersion:1,scope:"project",projectRoot:null,engine:"unknown",runtime:"unknown",framework:"unknown",frameworkDisplayName:"Unknown",frameworkConfidence:"low",frameworkSupportTier:"observed",runtimeSupportTier:"observed",runtimeDoctorSupport:"observed",moduleSupport:false,fleetStages:[],localOnlyCommands:[],commandMap:{},supportedCommands:[],unsupportedCommands:[],globalCommands:[]}}}function Re(e,t,r){let o=e.projects.map(a=>({id:a.slug,path:a.relativePath,runtime:a.runtime,framework:a.framework}));return {schemaVersion:"workspace-dependency-graph.v1",generatedAt:t,nodes:o,edges:[],stats:{nodeCount:o.length,edgeCount:0,inferredEdges:0,contractEdges:0,manualEdges:0,authoritativeEdges:0,lowConfidenceEdges:0,orphanCount:o.length,connectedNodeCount:0,density:0,edgeCoverageRatio:o.length===0?1:0,evidenceCoverageRatio:1,hotspotCount:0,hasCycle:false},diagnostics:[{code:"graph.enrichment.failed",severity:"warning",message:r,recommendation:"Review project manifests and graph overrides, then rerun workspace contract graph."}]}}async function rt(e){let{contractPath:t,contract:r}=await pe(e),o=e.now??new Date,a$1=o.toISOString(),{buildWorkspaceModel:c,workspaceModelProjectTopology:i}=await import('./workspace-model-FJXX3NET.js'),{hashWorkspaceModel:l}=await import('./workspace-model-hash-ZXYPIGCW.js'),u=await c({workspacePath:e.workspacePath,includeEvidence:false,now:o}),d=i(u)??Re(r,a$1,"The canonical Workspace Model did not provide a project dependency topology."),s=new Map(d.nodes.map(n=>[n.id,n.operationalProfile])),{buildWorkspaceKnowledgeGraph:p}=await import('./workspace-knowledge-graph-LEM6X5CM.js'),k=await p({workspacePath:e.workspacePath,workspace:{name:u.workspace.name,...u.workspace.profile?{profile:u.workspace.profile}:{}},contract:r,projectTopology:d,now:o,projects:u.projects.map(n=>({id:n.name,path:n.path,...n.absolutePath?{absolutePath:n.absolutePath}:{},runtime:n.runtime,runtimeCandidates:n.runtimeCandidates,framework:n.framework,...n.kit?{kit:n.kit}:{}})),source:{kind:"workspace-model",artifact:a.model,hashAlgorithm:"sha256",hash:l(u)}}),f=await Promise.all(r.projects.map(async n=>{let m=be(e.workspacePath,n),[_,v,le]=await Promise.all([ve(m),We(m),Se(m)]),C=Ae(m,n);return {id:n.slug,label:n.slug,relativePath:n.relativePath,source:n.source,relationship:n.relationship,externalPath:n.externalPath,runtime:n.runtime??C.runtime,framework:n.framework??C.framework,kit:n.kit,modules:n.modules,ports:n.ports,apis:n.contracts.apis,owns:n.contracts.owns,env:[...new Set([...n.contracts.env,...le])].sort((ue,me)=>ue.localeCompare(me)),contracts:{owns:[...n.contracts.owns],apis:[...n.contracts.apis],publishes:[...n.contracts.publishes],consumes:[...n.contracts.consumes],dependsOn:[...n.contracts.dependsOn],env:[...n.contracts.env]},capabilities:{engine:C.engine,supportTier:C.frameworkSupportTier,runtimeSupportTier:C.runtimeSupportTier,doctorSupport:C.runtimeDoctorSupport,moduleSupport:C.moduleSupport,fleetStages:[...C.fleetStages],localOnlyCommands:[...C.localOnlyCommands],supportedCommands:[...C.supportedCommands]},files:_,...v?{package:v}:{},...s.get(n.slug)?{operationalProfile:s.get(n.slug)}:{}}})),P=new Set(f.map(n=>n.id)),y=new Map,w=[];for(let n of r.projects){for(let m of n.contracts.dependsOn||[])P.has(m)&&w.push({from:m,to:n.slug,type:"dependency",label:"dependsOn"});for(let m of n.contracts.publishes||[])y.has(m)||y.set(m,new Set),y.get(m)?.add(n.slug);}for(let n of r.projects)for(let m of n.contracts.consumes||[]){let _=y.get(m);if(_)for(let v of _)v!==n.slug&&w.push({from:v,to:n.slug,type:"event",label:m});}let x={schemaVersion:1,kind:"rapidkit.workspace.contract.graph",workspace:r.workspace,generatedAt:a$1,nodes:f.sort((n,m)=>n.id.localeCompare(m.id)),edges:w.sort((n,m)=>`${n.from}:${n.to}:${n.type}:${n.label}`.localeCompare(`${m.from}:${m.to}:${m.type}:${m.label}`)),dependencyGraph:d,knowledgeGraph:k,semantics:{legacyEdges:"producer-to-consumer",dependencyGraphEdges:"consumer-to-dependency"},summary:{projectCount:f.length,dependencyEdges:w.filter(n=>n.type==="dependency").length,eventEdges:w.filter(n=>n.type==="event").length,portCount:f.reduce((n,m)=>n+m.ports.length,0),apiCount:f.reduce((n,m)=>n+m.apis.length,0),relationshipEdges:d.stats.edgeCount,inferredEdges:d.stats.inferredEdges,authoritativeEdges:d.stats.authoritativeEdges,orphanProjects:d.stats.orphanCount,hotspotProjects:d.stats.hotspotCount,evidenceCoverageRatio:d.stats.evidenceCoverageRatio,edgeCoverageRatio:d.stats.edgeCoverageRatio,connectedProjects:d.stats.connectedNodeCount,lowConfidenceEdges:d.stats.lowConfidenceEdges,hasCycle:d.stats.hasCycle,manifestCount:f.reduce((n,m)=>n+m.files.manifests.length,0),entrypointCount:f.reduce((n,m)=>n+m.files.entrypoints.length,0),diagnostics:d.diagnostics?.length??0,relationshipKinds:Object.fromEntries(ee.map(n=>[n,d.edges.filter(m=>m.kind===n).length])),relationshipSources:Object.fromEntries(te.map(n=>[n,d.edges.filter(m=>m.source===n).length])),entityCount:k.quality.entityCount,knowledgeRelations:k.quality.relationCount,proofCount:k.quality.proofCount,providerCount:k.providers.length,knowledgeUnknowns:k.quality.unknownCount}};return {contractPath:t,graph:x}}async function de(e){let t=e.contract?{contractPath:e.contractPath??a$2(e.workspacePath,E),contract:e.contract}:await pe(e),{contractPath:r,contract:o}=t,a=[],c=[];o.kind!=="rapidkit.workspace.contract"&&a.push("Contract kind must be rapidkit.workspace.contract."),o.schemaVersion!==R&&a.push(`Contract schemaVersion must be ${R}.`),o.workspace?.name||a.push("Contract workspace.name is required."),Array.isArray(o.projects)||a.push("Contract projects must be an array.");let i=new Set,l$1=new Map;for(let s of o.projects||[]){if(!s.slug){a.push("Every project must declare slug.");continue}i.has(s.slug)&&a.push(`Duplicate project slug: ${s.slug}.`),i.add(s.slug),s.relativePath?H(s.relativePath)||a.push(`Project ${s.slug} declares unsafe relativePath: ${s.relativePath}.`):a.push(`Project ${s.slug} must declare relativePath.`),s.externalPath&&(s.relationship==="adopted"||s.source==="adopted-local"||s.source==="local-folder"||s.source==="git-url"||a.push(`Project ${s.slug} declares externalPath without imported/adopted provenance.`),g__default.isAbsolute(s.externalPath)||a.push(`Project ${s.slug} declares non-absolute externalPath.`));for(let p of s.ports||[]){(!Number.isInteger(p.port)||p.port<1||p.port>65535)&&a.push(`Project ${s.slug} declares invalid port: ${p.port}.`);let k=l$1.get(p.port);k&&a.push(`Port ${p.port} is claimed by both ${k} and ${s.slug}.`),l$1.set(p.port,s.slug);}for(let p of s.contracts?.apis||[])(!p.name?.trim()||!p.basePath?.startsWith("/"))&&a.push(`Project ${s.slug} declares invalid API contract.`);for(let p of [...s.contracts?.publishes||[],...s.contracts?.consumes||[]])p.trim()||a.push(`Project ${s.slug} declares an empty event contract.`);for(let p of s.contracts?.env||[])/^[A-Z_][A-Z0-9_]*$/.test(p)||a.push(`Project ${s.slug} declares invalid env contract: ${p}.`);for(let p of s.contracts?.dependsOn||[])i.has(p);}for(let s of o.projects||[])for(let p of s.contracts?.dependsOn||[])i.has(p)||a.push(`Project ${s.slug} depends on unknown project: ${p}.`);c.push({id:"schema",status:o.kind==="rapidkit.workspace.contract"&&o.schemaVersion===R?"passed":"failed",message:"Contract schema and kind are valid."}),c.push({id:"projects",status:Array.isArray(o.projects)?"passed":"failed",message:`Contract declares ${Array.isArray(o.projects)?o.projects.length:0} project(s).`}),c.push({id:"ports",status:a.some(s=>s.toLowerCase().includes("port"))?"failed":"passed",message:"Project port declarations are valid and collision-free."}),c.push({id:"dependencies",status:a.some(s=>s.includes("depends on unknown project"))?"failed":"passed",message:"Project dependencies point to known project slugs."}),c.push({id:"contracts",status:a.some(s=>s.includes("unsafe relativePath")||s.includes("invalid API contract")||s.includes("event contract")||s.includes("env contract"))?"failed":"passed",message:"Project path, API, event, and env contracts are valid."});let u=await l(e.workspacePath);if(u.moduleCount>0){for(let s of u.issues)a.push(`${g__default.basename(s.projectRoot)}: ${s.message} (slug=${s.slug})`);c.push({id:"module-paths",status:u.status,message:u.status==="passed"?`All ${u.moduleCount} registered module(s) resolve under canonical paths.`:`${u.issues.length} registered module(s) missing canonical install paths.`});}else e.strict&&c.push({id:"module-paths",status:"passed",message:"No registry-backed modules declared in workspace projects."});return {status:a.length>0?"failed":"passed",contractPath:r,projectCount:Array.isArray(o.projects)?o.projects.length:0,checks:c,violations:a}}async function ot(e){let t=g__default.resolve(e.workspacePath),r={schemaVersion:he,generatedAt:e.generatedAt??new Date().toISOString(),status:e.result.status,contractPath:e.result.contractPath,projectCount:e.result.projectCount,checks:e.result.checks,violations:e.result.violations};return e$1(t,fe,Z(r))}
2
- export{I as a,Ne as b,De as c,Z as d,$e as e,ee as f,E as g,fe as h,R as i,he as j,N as k,ye as l,ce as m,et as n,tt as o,pe as p,rt as q,de as r,ot as s};
@@ -1 +0,0 @@
1
- var o="rapidkit-doctor-fix-result-v1",i="npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json";function n(t){return {schemaVersion:o,generatedAt:new Date().toISOString(),appliedFixes:t.appliedFixes,remainingBlockers:t.remainingBlockers,verifyRecommended:t.verifyRecommended??i}}var c="doctor-graph-diagnosis.v1";export{o as a,i as b,n as c,c as d};
@@ -1,75 +0,0 @@
1
- import {c}from'./chunk-AL237TSJ.js';import {d as d$1,b,a as a$2}from'./chunk-3RBUSW7H.js';import {d}from'./chunk-EWZZUQBR.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a}from'./chunk-62K2H72S.js';import {t,h,g}from'./chunk-MOSXTVPU.js';import z from'crypto';import I from'fs';import k from'fs/promises';import p from'path';import ne from'fs-extra';var oe="project-context-agent.v1",Ie=["managed","local","off"],X="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",q="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function G(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function v(e){try{return JSON.parse(await k.readFile(e,"utf8"))}catch(t){return null}}function E(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function W(e,t,r){let o=e.replace(/\\/g,"/"),s=/^[A-Za-z]:\//.test(o);if(!p.isAbsolute(e)&&!s)return E(o);if(s&&process.platform!=="win32")return null;let i=p.resolve(e),a=p.relative(r,i);if(a&&!a.startsWith("..")&&!p.isAbsolute(a))return E(a);let c=p.relative(t,i);return c&&!c.startsWith("..")&&!p.isAbsolute(c)?`workspace:${E(c)}`:null}function w(e,t,r){return [[r,"project:"],[r.replace(/\\/g,"/"),"project:"],[t,"workspace:"],[t.replace(/\\/g,"/"),"workspace:"]].reduce((s,[i,a])=>i.length>0?s.split(i).join(a):s,e)}function Z(e,t){return G(e?.adoption)?.mode==="linked"?"adopted":G(e?.import)?"imported":t}function se(e){if(!e.model)return null;let t=E(e.relativePath);return e.model.projects.find(r=>r.name===e.projectName||E(r.path)===t)??null}function B(e,t){e[t]=(e[t]??0)+1;}function ie(e,t){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let r=e.entities.find(n=>n.kind==="project"&&(n.id===t||n.label===t||n.projectId===t)),o=new Set(e.entities.filter(n=>n.projectId===t||n.id===r?.id||n.kind==="project"&&n.label===t).map(n=>n.id));r&&o.add(r.id);let s=e.relations.filter(n=>o.has(n.from)||o.has(n.to)),i=new Set(o);for(let n of s)i.add(n.from),i.add(n.to);let a=e.entities.filter(n=>i.has(n.id)),c=new Set,f={},y={};for(let n of a){B(f,n.kind);for(let d of n.proofIds)c.add(d);}for(let n of s){B(y,n.kind);for(let d of n.proofIds)c.add(d);}let m=e.proofs.filter(n=>c.has(n.id)),h=[...new Set(e.entities.filter(n=>i.has(n.id)&&n.projectId&&n.projectId!==t).map(n=>n.projectId))].sort(),j=e.diagnostics.filter(n=>n.entityIds?.some(d=>i.has(d))||n.relationIds?.some(d=>s.some(R=>R.id===d))).map(n=>({code:n.code,severity:n.severity,message:n.message,...n.recommendation?{recommendation:n.recommendation}:{}})),P=(n,d)=>({project:d,kind:n.kind,source:n.source,confidence:n.confidence,evidence:[...new Set(n.evidence.map(R=>R.file.replace(/\\/g,"/")))].sort()}),g=e.projectTopology.edges.filter(n=>n.from===t).map(n=>P(n,n.to)).sort((n,d)=>`${n.project}:${n.kind}`.localeCompare(`${d.project}:${d.kind}`)),u=e.projectTopology.edges.filter(n=>n.to===t).map(n=>P(n,n.from)).sort((n,d)=>`${n.project}:${n.kind}`.localeCompare(`${d.project}:${d.kind}`));return {entityCount:a.length,relationCount:s.length,proofCount:m.length,entitiesByKind:f,relationsByKind:y,relatedProjects:h,proofArtifacts:[...new Set(m.map(n=>n.artifact))].sort(),entities:[...a].sort((n,d)=>n.id.localeCompare(d.id)).slice(0,96),relations:[...s].sort((n,d)=>n.id.localeCompare(d.id)).slice(0,128),proofs:[...m].sort((n,d)=>n.id.localeCompare(d.id)).slice(0,128),topology:{status:g.length>0||u.length>0?"proven":e.projectTopology.nodes.some(n=>n.id===t)?"unproven":"unavailable",dependencies:g,dependents:u},diagnostics:j}}function Q(e,t,r){return Array.isArray(e)?e.map(o=>typeof o=="string"?w(o,t,r):o):typeof e=="string"?w(e,t,r):e}function ae(e,t,r){return {id:e.id,kind:e.kind,label:w(e.label,t,r),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,s])=>[o,Q(s,t,r)])),proofIds:[...e.proofIds].sort()}}function ce(e,t,r){let o=(...i)=>e.filter(a=>i.includes(a.kind)).map(a=>ae(a,t,r)).slice(0,32),s=[];for(let i of e){for(let[a,c]of Object.entries(i.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(a)&&(s.push({entityId:i.id,label:w(i.label,t,r),attribute:a,value:Q(c,t,r)}),s.length>=32))break;if(s.length>=32)break}return {services:o("service"),apis:o("api"),endpoints:o("endpoint"),dataStores:o("database","queue"),deployments:o("container","deployment","environment"),pipelines:o("pipeline"),tests:o("test-suite"),owners:o("owner"),decisions:o("decision"),ports:s}}function le(e,t,r){let o=W(e.artifact,t,r);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:w(e.pointer,t,r)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function pe(e,t,r){let o=[],s=await v(p.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(s?.blockers))for(let a of s.blockers)typeof a=="string"&&(a.startsWith(`${r}:`)||a.includes(`project:${r}`)||a.includes(`project ${r}`))&&o.push({source:"workspace-report-index",severity:"error",message:w(a,e,t)});let i=await v(p.join(e,".workspai","reports","doctor-project-last-run.json"));if(i?.projectName===r){if(Array.isArray(i.project?.issues))for(let a of i.project.issues)typeof a=="string"&&o.push({source:"doctor-project",severity:"error",message:w(a,e,t)});if(Array.isArray(i.project?.probes))for(let a of i.project.probes){let c=G(a);if(!c||!["fail","warn"].includes(String(c.status)))continue;let f=typeof c.reason=="string"?c.reason:typeof c.label=="string"?c.label:"Project Doctor reported unresolved evidence.";o.push({source:"doctor-project",severity:c.status==="fail"?"error":"warning",message:w(f,e,t),...typeof c.id=="string"?{code:c.id}:{}});}}return [...new Map(o.map(a=>[`${a.source}:${a.code??""}:${a.message}`,a])).values()].slice(0,32)}function O(e,t=[]){return typeof e=="string"?/^[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])[A-Za-z]:[\\/]/.test(e)||/(?:^|[\s("'`])\/(?:Users|home|private|var|opt|srv|mnt|Volumes|tmp)\//.test(e)||t.some(r=>r.length>0&&(e.includes(r)||e.includes(r.replace(/\\/g,"/")))):Array.isArray(e)?e.some(r=>O(r,t)):e&&typeof e=="object"?Object.values(e).some(r=>O(r,t)):false}function de(e){return z.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function ge(e){let t$1=p.resolve(e.workspacePath),r=p.resolve(e.projectPath),o=t(r,"project.json").find(l=>I.existsSync(l)),s=o?await v(o):null,i=await v(p.join(t$1,".workspai","workspace.contract.json")),a$2=p.resolve(r),c=i?.projects?.find(l=>l.externalPath?p.resolve(l.externalPath)===a$2:!l.relativePath||l.relativePath.startsWith("external/")?false:p.resolve(t$1,l.relativePath)===a$2)??i?.projects?.find(l=>l.slug===e.projectName||l.slug===p.basename(r)),f=e.projectName??(typeof s?.name=="string"?s.name:void 0)??c?.slug??p.basename(r),y=c?.relativePath??(()=>{let l=E(p.relative(t$1,r));return !l||l.startsWith("..")?`external/${f}`:l})(),m=await v(p.join(t$1,a.model)),h=await v(p.join(t$1,a.knowledgeGraph)),j=m?d(m):void 0,P=!!(j&&h?.source.hash===j),g=se({model:m,projectName:f,relativePath:y}),u=ie(P?h:null,f),n=await pe(t$1,r,f),d$1=u.proofs.map(l=>l.freshness),R=h?!P||d$1.includes("stale")?"stale":d$1.includes("unknown")?"unknown":"fresh":"missing",ee=m?m.factFreshness?.status??"unknown":"missing",te=[...m?[]:[{code:"project.context.model-missing",severity:"warning",message:"The canonical Workspace Model has not been generated yet. Refresh workspace intelligence before relying on project topology."}],...m&&!g?[{code:"project.context.project-not-materialized",severity:"warning",message:"The project is registered in the workspace contract but is not present in the current Workspace Model."}]:[],...h?[]:[{code:"project.context.graph-missing",severity:"warning",message:"The Workspace Knowledge Graph has not been generated yet. Run the workspace intelligence loop to build proof-backed relationships."}],...h&&!P?[{code:"project.context.graph-model-mismatch",severity:"warning",message:"The persisted Knowledge Graph does not match the current Workspace Model and was excluded from this project lens."}]:[]],re=Z(s,e.relationship??c?.relationship??"managed"),N={schemaVersion:oe,generatedAt:(e.now??new Date).toISOString(),workspace:{name:i?.workspace?.name??m?.workspace.name??p.basename(t$1),...i?.workspace?.profile||m?.workspace.profile?{profile:i?.workspace?.profile??m?.workspace.profile}:{},relationship:re,contract:".workspai/workspace.contract.json",model:a.model,knowledgeGraph:a.knowledgeGraph,access:{localBinding:".workspai/workspace-link.local.json",canonicalEvidenceAvailableAtGeneration:true}},project:{name:f,relativePath:y,...g?.kind?{kind:g.kind}:{},...g?.runtime||c?.runtime?{runtime:g?.runtime??c?.runtime}:{},...g?.framework||c?.framework?{framework:g?.framework??c?.framework}:{},...g?.kit||c?.kit?{kit:g?.kit??c?.kit}:{},...g?.supportTier?{supportTier:g.supportTier}:{},commands:{supported:[...g?.commands.supported??[]].sort(),unsupported:[...g?.commands.unsupported??[]].sort(),fleetStages:[...g?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((g?.importantFiles??[]).map(l=>W(l,t$1,r)).filter(l=>l!==null))].sort()},intelligence:{...m?.generatedAt?{modelGeneratedAt:m.generatedAt}:{},...h?.generatedAt?{graphGeneratedAt:h.generatedAt}:{},...h?.source.hash?{graphModelHash:h.source.hash}:{},entityCount:u.entityCount,relationCount:u.relationCount,proofCount:u.proofCount,entitiesByKind:u.entitiesByKind,relationsByKind:u.relationsByKind,relatedProjects:u.relatedProjects,freshness:{model:ee,graph:R,graphMatchesModel:P},topology:{...u.topology,dependencies:u.topology.dependencies.map(l=>({...l,evidence:l.evidence.map(b=>W(b,t$1,r)).filter(b=>b!==null)})),dependents:u.topology.dependents.map(l=>({...l,evidence:l.evidence.map(b=>W(b,t$1,r)).filter(b=>b!==null)}))},surfaces:ce(u.entities,t$1,r),diagnostics:[...te,...u.diagnostics].map(l=>({...l,message:w(l.message,t$1,r),...l.recommendation?{recommendation:w(l.recommendation,t$1,r)}:{}}))},evidence:{readOrder:[".workspai/PROJECT-GROUNDING.md",".workspai/reports/project-context-agent.json","AGENTS.md","workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`workspace:${a.model}`,`workspace:${a.knowledgeGraph}`],projectProofArtifacts:[...new Set(u.proofArtifacts.map(l=>W(l,t$1,r)).filter(l=>l!==null))],relations:u.relations.map(l=>({id:l.id,from:l.from,to:l.to,kind:l.kind,derivation:l.derivation,trust:l.trust,confidence:l.confidence,proofIds:[...l.proofIds].sort()})),proofs:u.proofs.map(l=>le(l,t$1,r)).filter(l=>l!==null)},blockers:n,commands:{refresh:"npx workspai workspace intelligence run --for-agent generic --strict --json",verify:"npx workspai workspace verify --strict --json",graphSearch:`npx workspai workspace graph search ${JSON.stringify(f)} --limit 12 --json`,doctor:"npx workspai doctor project --json",workspaceStatus:"npx workspai project workspace status --json"}};if(O(N,[t$1,r]))throw new Error("Project context lens rejected a non-portable absolute path.");let L={...N,integrity:{algorithm:"sha256",...j?{modelHash:j}:{},payloadHash:de(N),portable:true,absolutePathsEmitted:false}};return a$1(L,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),L}function ue(e){let t=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(s=>`\`${s}\``).join(", "):"No proven cross-project relation is currently available.",r=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(s=>`- **${s.severity} \xB7 ${s.code}:** ${s.message}`).join(`
2
- `):"- No project-scoped graph diagnostic is currently recorded.",o=e.blockers.length>0?e.blockers.slice(0,12).map(s=>`- **${s.severity}${s.code?` \xB7 ${s.code}`:""}:** ${s.message}`).join(`
3
- `):"- No current project-scoped blocker is recorded.";return `# Workspai project grounding
4
-
5
- This project is part of the **${e.workspace.name}** Workspai workspace.
6
- Commands launched from this project resolve that workspace automatically; you do not need to change directories first.
7
-
8
- ## Start here
9
-
10
- 1. Read \`.workspai/reports/project-context-agent.json\` for the bounded project lens.
11
- 2. Read the workspace report index only when the task crosses the project boundary.
12
- 3. Use graph search/evidence commands instead of loading the full graph into a prompt.
13
- 4. Do not claim healthy, ready, or verified without current Workspai evidence.
14
-
15
- The Workspace Model owns canonical project identity and its compact \`projectTopology\`.
16
- The Workspace Knowledge Graph is a separate, proof-backed enrichment containing
17
- files, symbols, APIs, infrastructure, tests, owners, and decisions. Do not treat
18
- an unproven topology edge as proof that two projects are independent.
19
-
20
- ## Project
21
-
22
- - Name: \`${e.project.name}\`
23
- - Workspace-relative identity: \`${e.project.relativePath}\`
24
- - Runtime: \`${e.project.runtime??"unknown"}\`
25
- - Framework: \`${e.project.framework??"unknown"}\`
26
- - Relationship: \`${e.workspace.relationship}\`
27
- - Related projects: ${t}
28
- - Topology status: \`${e.intelligence.topology.status}\`
29
- - Model freshness: \`${e.intelligence.freshness.model}\`
30
- - Knowledge Graph freshness: \`${e.intelligence.freshness.graph}\`
31
-
32
- ## Current evidence coverage
33
-
34
- - Project-scoped entities: ${e.intelligence.entityCount}
35
- - Project-scoped relations: ${e.intelligence.relationCount}
36
- - Portable proofs: ${e.intelligence.proofCount}
37
-
38
- ${r}
39
-
40
- ## Current project blockers
41
-
42
- ${o}
43
-
44
- ## Safe commands from this project
45
-
46
- \`\`\`bash
47
- ${e.commands.workspaceStatus}
48
- ${e.commands.doctor}
49
- ${e.commands.graphSearch}
50
- ${e.commands.verify}
51
- \`\`\`
52
-
53
- The machine-local workspace path lives only in \`.workspai/workspace-link.local.json\`, which is gitignored. Portable grounding files never publish that path.
54
- `}function me(e){return `# Workspai project boundary
55
-
56
- - Project: \`${e.project.name}\`
57
- - Canonical workspace: \`${e.workspace.name}\`
58
- - Portable project lens: \`.workspai/reports/project-context-agent.json\`
59
- - Project grounding: \`.workspai/PROJECT-GROUNDING.md\`
60
- - Workspace discovery: run \`npx workspai project workspace status --json\`
61
-
62
- For project-local tasks, start with the project lens. When a change can affect another project, a contract, an API, infrastructure, or release readiness, follow the workspace evidence references and query the Workspai graph. The agent should run the bounded graph search/evidence commands itself when required; the user does not need to preload the full graph. \`projectTopology\` is the compact project dependency view in the canonical Workspace Model, while the Workspace Knowledge Graph is the proof-backed detail layer. Workspai commands launched here resolve the canonical workspace automatically. Never copy the machine-local workspace link into answers, commits, or generated portable artifacts.`}function F(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e,t){return new RegExp(`${F(e)}[\\s\\S]*?${F(t)}`,"m")}function Y(e){let t=e.replace(U(X,q),"");return d$1(t)?.includes("# Workspai project boundary")&&(t=t.replace(U(a$2,b),"")),t.replace(/\n{3,}/g,`
63
-
64
- `).trim()}function fe(e,t){let r=Y(e),o=`${X}
65
- ${t.trim()}
66
- ${q}`;return r?`${r}
67
-
68
- ${o}
69
- `:`${o}
70
- `}async function C(e,t){await k.mkdir(p.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${z.randomUUID()}.tmp`;try{await k.writeFile(r,t,"utf8");try{await k.rename(r,e);}catch(o){let s=o.code;if(s!=="EEXIST"&&s!=="EPERM")throw o;await ne.move(r,e,{overwrite:true});}}finally{await k.rm(r,{force:true}).catch(()=>{});}}async function H(e,t){let r=p.join(e,".gitignore"),o=await k.readFile(r,"utf8").catch(c=>{if(c.code==="ENOENT")return "";throw c}),s=[g,h],i=o.split(/\r?\n/).filter(c=>c.trim()!=="# Workspai local project grounding"&&!s.includes(c.trim()));for(;i.length>0&&i[i.length-1]==="";)i.pop();t==="local"&&(i.length>0&&i.push(""),i.push("# Workspai local project grounding",...s));let a=i.length>0?`${i.join(`
71
- `)}
72
- `:"";a!==o&&await C(r,a);}async function V(e,t,r){let o=p.join(e,"AGENTS.md"),s=I.existsSync(o),i=await k.readFile(o,"utf8").catch(f=>{if(f.code==="ENOENT")return "";throw f});if(t==="managed"&&!r)throw new Error("Managed project grounding requires a project context.");let a=t==="managed"&&r?fe(i,me(r)):Y(i);if(!a){s&&await k.rm(o,{force:true});return}let c=`${a.trimEnd()}
73
- `;return c!==i&&await C(o,c),t==="managed"?o:void 0}async function he(e){let t$1=e.mode??"managed",r=p.resolve(e.workspacePath),o=p.resolve(e.projectPath);if(t$1==="off"){let h$1=t(o,"project.json").find(n=>I.existsSync(n)),j=h$1?await v(h$1):null,P=e.projectName??(typeof j?.name=="string"?j.name:void 0)??p.basename(o),g$1=Z(j,e.relationship??"managed"),u=await c({workspacePath:r,projectPath:o,projectName:P,relationship:g$1,now:e.now});return await H(o,t$1),await V(o,t$1),await Promise.all([k.rm(p.join(o,h),{force:true}),k.rm(p.join(o,g),{force:true})]),{mode:t$1,projectPath:o,linkPath:u.linkPath,writtenFiles:[".workspai/workspace-link.local.json"]}}let s=await ge(e),i=s.workspace.relationship,a=await c({workspacePath:r,projectPath:o,projectName:s.project.name,relationship:i,workspaceName:s.workspace.name,relativePath:s.project.relativePath,now:e.now});await H(o,t$1);let c$1=await V(o,t$1,s),f=p.join(o,h),y=p.join(o,g);await C(f,`${JSON.stringify(s,null,2)}
74
- `),await C(y,`${ue(s).trimEnd()}
75
- `);let m=[".workspai/workspace-link.local.json",h,g];return c$1&&m.push("AGENTS.md"),{mode:t$1,projectPath:o,linkPath:a.linkPath,groundingPath:y,contextPath:f,agentsPath:c$1,writtenFiles:m}}async function Ne(e){let t=p.resolve(e.workspacePath),r=e.mode??"managed",o=await je(t),s=[],i=[];for(let a of o.resolved)try{s.push(await he({workspacePath:t,projectPath:a.projectPath,projectName:a.name,relationship:a.relationship,mode:r,now:e.now}));}catch(c){i.push({name:a.name,reason:c instanceof Error?c.message:String(c)});}return {workspacePath:t,mode:r,projects:s,skipped:[...o.skipped,...i]}}async function je(e){let t=p.resolve(e),r=await v(p.join(t,".workspai","workspace.contract.json")),o=[],s=[];for(let i of r?.projects??[]){let a=i.slug??i.relativePath??"unknown-project",c=typeof i.externalPath=="string"?p.resolve(i.externalPath):typeof i.relativePath=="string"&&!i.relativePath.startsWith("external/")?p.resolve(t,i.relativePath):null;if(!c||!I.existsSync(c)){s.push({name:a,reason:"project path is unavailable on this machine"});continue}o.push({name:a,projectPath:c,relationship:i.relationship??"managed"});}return {resolved:o,skipped:s}}export{oe as a,Ie as b,X as c,q as d,ge as e,he as f,Ne as g,je as h};