workspai 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +2 -0
  2. package/contracts/agent-customization-pack.v1.json +10 -0
  3. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +77 -0
  4. package/contracts/extension-cli-compatibility.v1.json +5 -0
  5. package/contracts/published-contract-catalog.v1.json +25 -0
  6. package/contracts/runtime-command-surface.v1.json +45 -0
  7. package/contracts/workspace-intelligence/goal-agent-handoff.v1.json +96 -0
  8. package/contracts/workspace-intelligence/goal-index.v1.json +45 -0
  9. package/contracts/workspace-intelligence/goal-lifecycle-result.v1.json +96 -0
  10. package/contracts/workspace-intelligence/goal-pack.v1.json +250 -0
  11. package/contracts/workspace-intelligence/goal-plan-result.v1.json +46 -0
  12. package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +1 -0
  13. package/contracts/workspace-intelligence-architecture.v1.json +20 -0
  14. package/dist/analyze-MAU36FTX.js +1 -0
  15. package/dist/{artifact-remediation-plan-BPLON5VX.js → artifact-remediation-plan-JRX4XZ7C.js} +1 -1
  16. package/dist/autopilot-release-TA2L7SCB.js +1 -0
  17. package/dist/capabilities-command-HE2FICLG.js +1 -0
  18. package/dist/chunk-42Q5E2YV.js +1 -0
  19. package/dist/{workspace-knowledge-graph-snapshot-XSQADCNR.js → chunk-4NN5QWOB.js} +1 -1
  20. package/dist/{chunk-GDKFN3CM.js → chunk-4YICCES6.js} +1 -1
  21. package/dist/{chunk-VL3APTVB.js → chunk-6TNSCVR4.js} +1 -1
  22. package/dist/{chunk-PKIRVQLG.js → chunk-7IRGSM25.js} +1 -1
  23. package/dist/{chunk-NHTLE3WN.js → chunk-7KXRA5ST.js} +1 -1
  24. package/dist/{chunk-Z57G62KE.js → chunk-A3JCETSF.js} +1 -1
  25. package/dist/{chunk-GXTCU4WF.js → chunk-AUCHMXUZ.js} +1 -1
  26. package/dist/{chunk-L36ZASME.js → chunk-C4NYG57I.js} +1 -1
  27. package/dist/{chunk-P475BOJW.js → chunk-CFBAGPB4.js} +1 -1
  28. package/dist/{chunk-GTJY55QK.js → chunk-CHMCKYJJ.js} +1 -1
  29. package/dist/{chunk-SNO3WG4V.js → chunk-EEMRRCGR.js} +1 -1
  30. package/dist/{chunk-75HOCFNH.js → chunk-FXIE2WVG.js} +1 -1
  31. package/dist/{chunk-YJTEMJFV.js → chunk-FY6OHOXR.js} +1 -1
  32. package/dist/{chunk-W5ZFXKSL.js → chunk-G4VMNWSU.js} +1 -1
  33. package/dist/{chunk-ADL3CK44.js → chunk-GRGUPSNP.js} +1 -1
  34. package/dist/{chunk-6OFGLNFS.js → chunk-GVS5OFUB.js} +1 -1
  35. package/dist/{chunk-E53BGUOW.js → chunk-H545P6LN.js} +1 -1
  36. package/dist/chunk-HH54C3XJ.js +1 -0
  37. package/dist/{chunk-XMTLKDPP.js → chunk-HI7ONEFI.js} +1 -1
  38. package/dist/chunk-HYY5PQCV.js +1 -0
  39. package/dist/{chunk-QK5QOXOE.js → chunk-I5PDN2P2.js} +1 -1
  40. package/dist/{chunk-V5EYVQ63.js → chunk-II4ROT6X.js} +1 -1
  41. package/dist/{chunk-GBMCHFOV.js → chunk-LGJAAPNR.js} +1 -1
  42. package/dist/{chunk-UQEQ6CXU.js → chunk-M2BK3XTP.js} +1 -1
  43. package/dist/{chunk-N2BIIUDH.js → chunk-MFJ6ZP7S.js} +1 -1
  44. package/dist/{chunk-64JUYYRC.js → chunk-N3DFX4BY.js} +1 -1
  45. package/dist/chunk-NQ5H4R2I.js +83 -0
  46. package/dist/chunk-PCXBPQO6.js +1 -0
  47. package/dist/chunk-QXW3SLEX.js +1 -0
  48. package/dist/{chunk-IXOLHPTN.js → chunk-RJDGC6AQ.js} +1 -1
  49. package/dist/{chunk-ZPA6ECBJ.js → chunk-RMDVRNU7.js} +1 -1
  50. package/dist/{chunk-TTFQWH55.js → chunk-SM55RK3C.js} +1 -1
  51. package/dist/{chunk-LYVDRRDO.js → chunk-T63WRURN.js} +1 -1
  52. package/dist/{chunk-VUR7H2FU.js → chunk-TMOKXYAQ.js} +1 -1
  53. package/dist/{chunk-DF4NWPB7.js → chunk-TTLVG5AR.js} +1 -1
  54. package/dist/{chunk-QHY6F4SS.js → chunk-VAWV3UKV.js} +1 -1
  55. package/dist/chunk-VIFTO53Y.js +1 -0
  56. package/dist/{chunk-IZLEMTES.js → chunk-WSDVFLHT.js} +1 -1
  57. package/dist/{chunk-IUYZ3NHS.js → chunk-XC26FNRL.js} +3 -3
  58. package/dist/chunk-YMY6EFX4.js +1 -0
  59. package/dist/{chunk-YM77FQB3.js → chunk-YYCPRYP7.js} +1 -1
  60. package/dist/{chunk-RPHM7LQW.js → chunk-ZDYGO3T7.js} +17 -17
  61. package/dist/{create-O2KLTN5H.js → create-QIN56Y4M.js} +1 -1
  62. package/dist/{doctor-AL5YWO5X.js → doctor-RP4Q2CKJ.js} +1 -1
  63. package/dist/goal-command-contract-CHE7U6YY.js +1 -0
  64. package/dist/goal-lifecycle-YTBU3ICP.js +1 -0
  65. package/dist/goal-pack-MYYH7K43.js +1 -0
  66. package/dist/index.d.ts +17 -2
  67. package/dist/index.js +125 -125
  68. package/dist/{pipeline-4ST4BQWY.js → pipeline-77NUVYQD.js} +1 -1
  69. package/dist/{project-intelligence-lens-JHYECYOK.js → project-intelligence-lens-AM2B2PXU.js} +1 -1
  70. package/dist/project-test-coverage-MUSS7Z7V.js +1 -0
  71. package/dist/{verified-goal-KFNRGOKT.js → verified-goal-ZSIZYNVO.js} +1 -1
  72. package/dist/{workspace-O4E5CCGK.js → workspace-LFESVKE7.js} +1 -1
  73. package/dist/{workspace-agent-sync-N5DPGU2E.js → workspace-agent-sync-JMRX6J2Y.js} +1 -1
  74. package/dist/{workspace-archive-BA3ONVXX.js → workspace-archive-MFHCFCDO.js} +1 -1
  75. package/dist/{workspace-context-ETZNEHOJ.js → workspace-context-TBKRMVMT.js} +1 -1
  76. package/dist/{workspace-contract-OSI7NBXS.js → workspace-contract-KKVC2DUQ.js} +1 -1
  77. package/dist/workspace-explain-RGGZL5IW.js +1 -0
  78. package/dist/workspace-explain-contract-4ZZ6CJ44.js +1 -0
  79. package/dist/{workspace-feedback-PCZKXG5R.js → workspace-feedback-O6J3RQML.js} +1 -1
  80. package/dist/{workspace-foundation-QQHX66KE.js → workspace-foundation-JQWT7YGC.js} +1 -1
  81. package/dist/{workspace-graph-stream-UZJQ75XZ.js → workspace-graph-stream-V5WOXP4B.js} +1 -1
  82. package/dist/{workspace-history-CHJOABME.js → workspace-history-TOCRMJUJ.js} +1 -1
  83. package/dist/{workspace-intelligence-A7O7MN6T.js → workspace-intelligence-SDBIRKMK.js} +1 -1
  84. package/dist/{workspace-intelligence-evaluation-YMY3C5AW.js → workspace-intelligence-evaluation-E4UMWDAZ.js} +1 -1
  85. package/dist/{workspace-intelligence-runner-4EF66L66.js → workspace-intelligence-runner-DIMNL6CJ.js} +1 -1
  86. package/dist/{workspace-intelligence-runtime-registry-NCVHKCMP.js → workspace-intelligence-runtime-registry-YGWB2RRS.js} +1 -1
  87. package/dist/{workspace-knowledge-graph-BVN4NTJ6.js → workspace-knowledge-graph-MUW6UAGI.js} +1 -1
  88. package/dist/workspace-knowledge-graph-snapshot-7IU2QAXI.js +1 -0
  89. package/dist/{workspace-mcp-serve-TKX4J3SX.js → workspace-mcp-serve-2SWLIH4I.js} +1 -1
  90. package/dist/{workspace-model-7ESEP366.js → workspace-model-VPFCKTYQ.js} +1 -1
  91. package/dist/{workspace-onboarding-SY255V7L.js → workspace-onboarding-GHI6UTQJ.js} +1 -1
  92. package/dist/{workspace-readme-IVJXSIBS.js → workspace-readme-RASXBZRQ.js} +1 -1
  93. package/dist/{workspace-registry-summary-7ISKYEPM.js → workspace-registry-summary-7QT7YMIU.js} +1 -1
  94. package/dist/workspace-repair-engine-AZTJIFCY.js +3 -0
  95. package/dist/workspace-run-VMZY6LIF.js +1 -0
  96. package/dist/{workspace-verify-CNXZPWS5.js → workspace-verify-RYCQZYYB.js} +1 -1
  97. package/dist/{workspace-watch-HGFL2EU3.js → workspace-watch-U3YGN3GG.js} +1 -1
  98. package/docs/README.md +2 -0
  99. package/docs/ci-workflows.md +1 -1
  100. package/docs/commands-reference.md +12 -0
  101. package/docs/contracts/ARTIFACT_CATALOG.md +11 -0
  102. package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +1 -0
  103. package/docs/goal-packs.md +174 -0
  104. package/docs/real-world-qualification.md +22 -3
  105. package/package.json +1 -1
  106. package/dist/analyze-HJ774J3E.js +0 -1
  107. package/dist/autopilot-release-WIFFFQKW.js +0 -1
  108. package/dist/capabilities-command-44JVOE5S.js +0 -1
  109. package/dist/chunk-3U4VLIGW.js +0 -1
  110. package/dist/chunk-5EPPPMAS.js +0 -1
  111. package/dist/chunk-D4RST2HE.js +0 -1
  112. package/dist/chunk-DT4X7I5M.js +0 -81
  113. package/dist/chunk-VZPWIILU.js +0 -1
  114. package/dist/project-test-coverage-FRMVYTFB.js +0 -1
  115. package/dist/workspace-explain-EM7IUV6L.js +0 -1
  116. package/dist/workspace-explain-contract-KVQO57RC.js +0 -1
  117. package/dist/workspace-repair-engine-GMA2YTCF.js +0 -3
  118. package/dist/workspace-run-ZZXVNFUS.js +0 -1
@@ -1 +0,0 @@
1
- import {a}from'./chunk-W5ZFXKSL.js';import {a as a$1}from'./chunk-GR6442P7.js';import {f,e}from'./chunk-ADL3CK44.js';import {h,i}from'./chunk-5EPPPMAS.js';import {createHash}from'crypto';import c from'path';import {execa}from'execa';import u from'fs-extra';var V=h.projectTestCoverage.schemaVersion,k=i.projectTestCoverage,$=["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 m(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 W(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;return m(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 H(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($.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 D(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),g=c.relative(e,d).split(c.sep).join("/");l.isFile()&&t(l.name,g)&&n.push(d),l.isDirectory()&&s.depth<o&&r.push({dir:d,depth:s.depth+1});}}return n}async function L(e,t){let o=await u.readJson(t),n=o.total??o,r={};for(let s of ["lines","branches","functions","statements"]){let a=W(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 g of ["lines","branches","functions","statements"]){let b=W(l[g]);b&&(d[g]=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 G(e,t){let o=await u.readJson(t),n=o.totals??{},r={lines:m(n.num_statements,n.covered_lines)};p(n.num_branches)>0&&(r.branches=m(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:m(l.num_statements,l.covered_lines),...p(l.num_branches)>0?{branches:m(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?m(o,n):void 0}async function q(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 A(e,t){let o=await u.readFile(t,"utf8"),n=[],r="",i=0,s=0,a=0,l=0,d=0,g=0,b=v=>{r&&(n.push({path:y(e,r),metrics:{lines:m(v.lineTotal,v.lineCovered),functions:m(v.functionTotal,v.functionCovered),branches:m(v.branchTotal,v.branchCovered)}}),i+=v.lineTotal,s+=v.lineCovered,a+=v.functionTotal,l+=v.functionCovered,d+=v.branchTotal,g+=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:m(i,s),functions:m(a,l),branches:m(d,g)},files:n,source:{format:"lcov",path:t,sha256:await x(t)}}}async function U(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:m(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:m(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?m(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=m(1e4,Math.round(Number(i)*1e4))),s&&(n.branches=m(1e4,Math.round(Number(s)*1e4)));}if(t==="clover-xml"){let i=[...o.matchAll(/<metrics\b([^>]*)\/?>/gi)].at(-1)?.[1]??"",s=g=>p(new RegExp(`\\b${g}=["'](\\d+)["']`,"i").exec(i)?.[1]),a=s("statements"),l=s("methods"),d=s("conditionals");a>0&&(n.statements=m(a,s("coveredstatements"))),l>0&&(n.functions=m(l,s("coveredmethods"))),d>0&&(n.branches=m(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 z(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"),g={};return r>0?g.statements=m(r,i):l>0&&(g.statements=m(1e4,Math.round(l*100))),s>0?g.branches=m(s,a):d>0&&(g.branches=m(1e4,Math.round(d*100))),{metrics:g,files:[],source:{format:"scoverage-xml",path:e,sha256:await x(e)}}}async function B(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 g=n.get(l)??[];d.forEach((b,h)=>{typeof b=="number"&&(g[h]=Math.max(g[h]??0,b));}),n.set(l,g);}}let r=[...n.entries()].map(([s,a])=>{let l=a.filter(d=>typeof d=="number");return {path:y(e,s),metrics:{lines:m(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:m(i.total,i.covered)},files:r,source:{format:"simplecov-json",path:t,sha256:await x(t)}}}async function K(e){let t=[{relativePath:"coverage/coverage-summary.json",parser:r=>L(e,r)},{relativePath:"coverage.json",parser:async r=>{let i=await u.readJson(r);return Array.isArray(i.data)?q(e,r):G(e,r)}},{relativePath:"coverage/lcov.info",parser:r=>A(e,r)},{relativePath:"cover/lcov.info",parser:r=>A(e,r)},{relativePath:"lcov.info",parser:r=>A(e,r)},{relativePath:"coverage.out",parser:r=>U(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=>B(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")?L(e,n):n.endsWith("jacoco.xml")?C(n,"jacoco-xml"):n.endsWith("coverage.cobertura.xml")?C(n,"cobertura-xml"):n.endsWith("scoverage.xml")?z(n):C(n,"clover-xml"):null}async function X(e){return u.readJson(c.join(e,"package.json")).catch(()=>null)}async function Q(e,t){let o=(n,r)=>({cwd:e,executable:n,args:r});if(t==="node"||t==="bun"){let r=(await X(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 Y(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 Z(e){return e.lines?"lines":e.statements?"statements":e.branches?"branches":"functions"}async function ue(e$1={}){let t=await H(e$1.projectPath??process.cwd()),o=a(t),n=await D(t),r=Math.max(0,Math.min(100,Math.round(e$1.target??80))),i=await Q(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 K(t).catch(()=>null),d=l?Z(l.metrics):"lines",g=l?.metrics[d]?.percent??null,b=e$1.run&&s.some(f=>f!==0)?"failed":g===null?"unavailable":g>=r?"passed":"below-target",h=Y(o,t),v=c.join(t,k),E=o?`.workspai/reports/projects/${h}/project-test-coverage-last-run.json`:null,R={schemaVersion:V,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{V as a,k as b,ue as c};
@@ -1 +0,0 @@
1
- var r="workspai.doctor-capabilities.v1",k="universal-doctor-capabilities-v1",t="workspai.doctor-validation.v1",w="doctor-disease-corpus-v1";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",repairTransaction:".workspai/reports/workspace-repair-last-run.json"},s={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",repairTransaction:"workspai.workspace-repair-transaction.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",repairTransaction:"contracts/workspace-intelligence/workspace-repair-transaction.v1.json"},l={projectWorkspaceLink:{artifactPath:".workspai/workspace-link.local.json",schemaVersion:"project-workspace-link.v1",contractPath:"contracts/project-workspace-link.v1.json",producerCommands:[["adopt"],["import"],["project","workspace","relink"],["workspace","sync"]]},projectContextAgent:{artifactPath:".workspai/reports/project-context-agent.json",schemaVersion:"project-context-agent.v1",contractPath:"contracts/workspace-intelligence/project-context-agent.v1.json",producerCommands:[["adopt"],["import"],["workspace","sync"],["workspace","agent-sync","--write"]]},workspaceContract:{artifactPath:".workspai/workspace.contract.json",schemaVersion:1,contractPath:"contracts/workspace-contract.v1.json",producerCommands:[["workspace","sync"],["workspace","contract","sync"]]},workspaceModelCache:{artifactPath:".workspai/cache/workspace-model.v1.json",schemaVersion:"workspace-model-cache.v1",contractPath:"contracts/workspace-model-cache.v1.json",producerCommands:[["workspace","model"]]},workspaceRegistry:{artifactPath:".workspai/workspace-registry.v1.json",schemaVersion:"workspace-registry.v1",contractPath:"contracts/workspace-registry.v1.json",producerCommands:[["workspace","sync"]]},compatibilityMatrix:{artifactPath:".workspai/compatibility-matrix.json",schemaVersion:"rapidkit.compatibility-matrix.v1",contractPath:"contracts/compatibility-matrix.v1.json",producerCommands:[["bootstrap"]]},doctorWorkspaceCache:{artifactPath:".workspai/reports/doctor-workspace-cache.json",schemaVersion:"doctor-workspace-cache-v2",contractPath:"contracts/doctor-workspace-cache.v2.json",producerCommands:[["doctor","workspace"]]},doctorCapabilities:{artifactPath:".workspai/reports/doctor-capabilities.json",schemaVersion:r,contractPath:"contracts/workspace-intelligence/doctor-capabilities.v1.json",producerCommands:[["doctor","capabilities","--write"]]},doctorValidation:{artifactPath:".workspai/reports/doctor-validation-last-run.json",schemaVersion:t,contractPath:"contracts/workspace-intelligence/doctor-validation.v1.json",producerCommands:[["doctor","capabilities","--validate","--write"]]},bootstrapCompliance:{artifactPath:".workspai/reports/bootstrap-compliance.latest.json",schemaVersion:"bootstrap-compliance.v1",contractPath:"contracts/bootstrap-compliance.v1.json",producerCommands:[["bootstrap"]]},mirrorOps:{artifactPath:".workspai/reports/mirror-ops.latest.json",schemaVersion:"mirror-ops.v1",contractPath:"contracts/mirror-ops.v1.json",producerCommands:[["mirror","status"]]},transparencyEvidence:{artifactPath:".workspai/reports/transparency-evidence.latest.json",schemaVersion:"transparency-evidence.v1",contractPath:"contracts/transparency-evidence.v1.json",producerCommands:[["mirror","sync"]]},workspaceShareBundle:{artifactPath:".workspai/reports/share-bundle.json",schemaVersion:"1.1",schemaVersionField:"schema_version",contractPath:"contracts/workspace-share-bundle.v1.json",producerCommands:[["workspace","share"]]},doctorProject:{artifactPath:".workspai/reports/doctor-project-last-run.json",schemaVersion:"doctor-project-evidence-v1",contractPath:"contracts/doctor-project-evidence.v1.json",producerCommands:[["doctor","project"]]},doctorReceipt:{artifactPath:".workspai/reports/doctor-receipt-last-run.json",schemaVersion:"workspai.doctor-receipt.v1",contractPath:"contracts/workspace-intelligence/doctor-receipt.v1.json",producerCommands:[["doctor","workspace"],["doctor","project"]]},projectTestCoverage:{artifactPath:".workspai/reports/project-test-coverage-last-run.json",schemaVersion:"workspai.project-test-coverage.v1",contractPath:"contracts/project-test-coverage.v1.json",producerCommands:[["project","coverage"]]},doctorRemediationPlan:{artifactPath:".workspai/reports/doctor-remediation-plan-last-run.json",schemaVersion:"doctor-remediation-plan-v2",contractPath:"contracts/doctor-remediation-plan.v2.json",producerCommands:[["workspace","remediation-plan"]]},artifactRemediationPlan:{artifactPath:".workspai/reports/artifact-remediation-plan-last-run.json",schemaVersion:"artifact-remediation-plan-v1",contractPath:"contracts/artifact-remediation-plan.v1.json",producerCommands:[["workspace","remediation-plan"]]},doctorFixResult:{artifactPath:".workspai/reports/doctor-fix-result-last-run.json",schemaVersion:"rapidkit-doctor-fix-result-v1",contractPath:"contracts/workspace-intelligence/doctor-fix-result.v1.json",producerCommands:[["doctor","workspace"]]},pipelineLastRun:{artifactPath:".workspai/reports/pipeline-last-run.json",schemaVersion:"rapidkit-pipeline-v1",contractPath:"contracts/pipeline-last-run.v1.json",producerCommands:[["pipeline"]]},autopilotReleaseLastRun:{artifactPath:".workspai/reports/autopilot-release-last-run.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json",producerCommands:[["autopilot","release"]]},autopilotReleaseAlias:{artifactPath:".workspai/reports/autopilot-release.json",schemaVersion:"autopilot-release-v1",contractPath:"contracts/autopilot-release.v1.json",producerCommands:[["autopilot","release"]]},workspaceRunLast:{artifactPath:".workspai/reports/workspace-run-last.json",schemaVersion:"workspace-run-v1",contractPath:"contracts/workspace-run-last.v1.json",producerCommands:[["workspace","run"]]},workspaiMcpDesign:{artifactPath:".workspai/reports/workspai-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json",producerCommands:[["workspace","agent-sync","--write"]]},legacyMcpDesign:{artifactPath:".workspai/reports/rapidkit-mcp-design.json",schemaVersion:"workspai-mcp-design.v1",contractPath:"contracts/workspace-intelligence/mcp-design.v1.json",producerCommands:[["workspace","agent-sync","--write"]]},workspaceWhy:{artifactPath:".workspai/reports/workspace-why-last-run.json",schemaVersion:s.explain,contractPath:c.explain,producerCommands:[["workspace","why"]]},workspaceTrace:{artifactPath:".workspai/reports/workspace-trace-last-run.json",schemaVersion:s.explain,contractPath:c.explain,producerCommands:[["workspace","trace"]]},agentHooks:{artifactPath:".vscode/workspai-agent-hooks.json",schemaVersion:"workspai-agent-hooks.v1",contractPath:"contracts/workspace-intelligence/agent-hooks.v1.json",producerCommands:[["workspace","agent-sync"]]},infraPlan:{artifactPath:".workspai/reports/infra-plan.json",schemaVersion:"rapidkit.infra-plan.v1",contractPath:"contracts/infra-plan.v1.json",producerCommands:[["infra","plan"]]}},h=Object.freeze(Object.fromEntries(Object.entries(l).map(([a,n])=>[a,n.artifactPath]))),g={[o.intelligenceRun]:[["workspace","intelligence","run"]],[o.snapshot]:[["workspace","snapshot"]],[o.history]:[["workspace","feedback","record","--json"]],[o.evaluationLive]:[["workspace","eval","init"],["workspace","eval","record","--json"]],[o.evaluationLastRun]:[["workspace","eval","report","--json"]],[o.verifiedGoalStatus]:[["workspace","goal","plan"],["workspace","goal","verify"]],[o.repairTransaction]:[["workspace","repair","plan"],["workspace","repair","propose"],["workspace","repair","approve"],["workspace","repair","decide"],["workspace","repair","execute"],["workspace","repair","resume"],["workspace","repair","rollback"],["workspace","repair","cancel"]]},j={analyze:"analyze",workspace:"workspace <action> [subaction] [key] [value]",doctor:"doctor [scope]",readiness:"readiness"},f=["analyze","readiness","doctor","workspace"],C=["model","diff","impact","doctor-evidence","contract-evidence","analyze-evidence","readiness-evidence","verify","context","agent-sync","explain"],P=["sync","baseline"],I={sync:[".workspai/workspace.contract.json",".workspai/workspace-registry.v1.json"],baseline:[o.snapshot]},e=o,d={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 y(a){return d[a]}export{r as a,k as b,t as c,w as d,o as e,s as f,c as g,l as h,h as i,g as j,j as k,f as l,C as m,P as n,I as o,d as p,y as q};
@@ -1 +0,0 @@
1
- import {h}from'./chunk-5EPPPMAS.js';var _=h.artifactRemediationPlan.schemaVersion;export{_ as a};
@@ -1,81 +0,0 @@
1
- import {c}from'./chunk-ZPA6ECBJ.js';import {c as c$1}from'./chunk-X7FYEKLI.js';import {d as d$1,b as b$1,a as a$1}from'./chunk-3RBUSW7H.js';import {d}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import {h,e,i}from'./chunk-5EPPPMAS.js';import {t,h as h$1,g}from'./chunk-MOSXTVPU.js';import te from'crypto';import D from'fs';import j from'fs/promises';import p from'path';import {execa}from'execa';import ae from'fs-extra';var ce=h.projectContextAgent.schemaVersion,De=["managed","local","off"],ne="<!-- WORKSPAI:PROJECT-GROUNDING:START -->",re="<!-- WORKSPAI:PROJECT-GROUNDING:END -->";function z(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function b(e){try{return JSON.parse(await j.readFile(e,"utf8"))}catch(n){return null}}function R(e){return e.replace(/\\/g,"/").replace(/^\.\/+/,"")}function x(e,n,r){let o=e.replace(/\\/g,"/"),i=/^[A-Za-z]:\//.test(o);if(!p.isAbsolute(e)&&!i)return R(o);if(i&&process.platform!=="win32")return null;let c=p.resolve(e),a=p.relative(r,c);if(a&&!a.startsWith("..")&&!p.isAbsolute(a))return R(a);let l=p.relative(n,c);return l&&!l.startsWith("..")&&!p.isAbsolute(l)?`workspace:${R(l)}`:null}function y(e,n,r){return [[r,"project:"],[r.replace(/\\/g,"/"),"project:"],[n,"workspace:"],[n.replace(/\\/g,"/"),"workspace:"]].reduce((i,[c,a])=>c.length>0?i.split(c).join(a):i,e)}function oe(e,n){return z(e?.adoption)?.mode==="linked"?"adopted":z(e?.import)?"imported":n}function le(e){if(!e.model)return null;let n=R(e.relativePath);return e.model.projects.find(r=>r.name===e.projectName||R(r.path)===n)??null}function X(e,n){e[n]=(e[n]??0)+1;}var pe=["project","language","service","api","endpoint","schema","protocol","runtime-unit","lifecycle-stage","database","queue","container","deployment","pipeline","environment","test-suite","owner","decision","document","package","file","module","symbol"];function de(e,n=160){let r={language:32,api:32,service:32,endpoint:32,schema:32,protocol:32,"runtime-unit":32,"lifecycle-stage":32,file:8,module:8,symbol:8},o=[];for(let i of pe){let c=e.filter(a=>a.kind===i).sort((a,l)=>a.label.localeCompare(l.label)||a.id.localeCompare(l.id)).slice(0,r[i]??32);for(let a of c){if(o.length>=n)return o;o.push(a);}}return o}function ge(e,n){if(!e)return {entityCount:0,relationCount:0,proofCount:0,entitiesByKind:{},relationsByKind:{},languages:{},semantic:{protocolConceptCount:0,protocolImplementationBindings:0,equivalenceBindings:0,generationBindings:0,runtimeUnitCount:0,lifecycleStageCount:0,runtimeCoverage:[]},relatedProjects:[],proofArtifacts:[],entities:[],relations:[],proofs:[],topology:{status:"unavailable",dependencies:[],dependents:[]},diagnostics:[]};let r=e.entities.find(t=>t.kind==="project"&&(t.id===n||t.label===n||t.projectId===n)),o=new Set(e.entities.filter(t=>t.projectId===n||t.id===r?.id||t.kind==="project"&&t.label===n).map(t=>t.id));r&&o.add(r.id);let i=e.relations.filter(t=>o.has(t.from)||o.has(t.to)),c=new Set(o);for(let t of i)c.add(t.from),c.add(t.to);let a=e.entities.filter(t=>c.has(t.id)),l=new Set,d={},u={},m={},k=new Set(a.filter(t=>t.kind==="language").map(t=>t.attributes.language).filter(t=>typeof t=="string"));for(let t of a){X(d,t.kind);let s=typeof t.attributes.language=="string"?t.attributes.language:void 0;if(s&&t.kind==="language")m[s]={fileCount:typeof t.attributes.fileCount=="number"?t.attributes.fileCount:0,symbolCount:m[s]?.symbolCount??0,generatedFileCount:typeof t.attributes.generatedFileCount=="number"?t.attributes.generatedFileCount:0};else if(s&&(t.kind==="file"||t.kind==="symbol")){let h=m[s]??{fileCount:0,symbolCount:0,generatedFileCount:0};t.kind==="file"&&!k.has(s)?(h.fileCount+=1,t.attributes.generated===true&&(h.generatedFileCount+=1)):t.kind==="symbol"&&(h.symbolCount+=1),m[s]=h;}for(let h of t.proofIds)l.add(h);}for(let t of i){X(u,t.kind);for(let s of t.proofIds)l.add(s);}let w=e.proofs.filter(t=>l.has(t.id)),P=[...new Set(e.entities.filter(t=>c.has(t.id)&&t.projectId&&t.projectId!==n).map(t=>t.projectId))].sort(),f=e.diagnostics.filter(t=>t.entityIds?.some(s=>c.has(s))||t.relationIds?.some(s=>i.some(h=>h.id===s))).map(t=>({code:t.code,severity:t.severity,message:t.message,...t.recommendation?{recommendation:t.recommendation}:{}})),g=(t,s)=>({project:s,kind:t.kind,source:t.source,confidence:t.confidence,evidence:[...new Set(t.evidence.map(h=>h.file.replace(/\\/g,"/")))].sort()}),C=e.projectTopology.edges.filter(t=>t.from===n).map(t=>g(t,t.to)).sort((t,s)=>`${t.project}:${t.kind}`.localeCompare(`${s.project}:${s.kind}`)),S=e.projectTopology.edges.filter(t=>t.to===n).map(t=>g(t,t.from)).sort((t,s)=>`${t.project}:${t.kind}`.localeCompare(`${s.project}:${s.kind}`)),T=de(a),$=a.filter(t=>t.kind==="runtime-unit"),A=new Set(T.map(t=>t.id)),L=[...i].sort((t,s)=>{let h=Number(A.has(t.from)||A.has(t.to));return Number(A.has(s.from)||A.has(s.to))-h||t.id.localeCompare(s.id)}).slice(0,128),I=new Set([...T.flatMap(t=>t.proofIds),...L.flatMap(t=>t.proofIds)]);return {entityCount:a.length,relationCount:i.length,proofCount:w.length,entitiesByKind:d,relationsByKind:u,languages:Object.fromEntries(Object.entries(m).sort(([t],[s])=>t.localeCompare(s))),semantic:{protocolConceptCount:d.protocol??0,protocolImplementationBindings:u["implements-protocol"]??0,equivalenceBindings:u["equivalent-to"]??0,generationBindings:(u["generated-from"]??0)+(u["generated-by"]??0),runtimeUnitCount:$.length,lifecycleStageCount:d["lifecycle-stage"]??0,runtimeCoverage:[...new Set($.map(t=>t.attributes.runtime).filter(t=>typeof t=="string"))].sort()},relatedProjects:P,proofArtifacts:[...new Set(w.map(t=>t.artifact))].sort(),entities:T,relations:L,proofs:w.filter(t=>I.has(t.id)).sort((t,s)=>t.id.localeCompare(s.id)).slice(0,128),topology:{status:C.length>0||S.length>0?"proven":e.projectTopology.nodes.some(t=>t.id===n)?"unproven":"unavailable",dependencies:C,dependents:S},diagnostics:f}}function se(e,n,r){return Array.isArray(e)?e.map(o=>typeof o=="string"?y(o,n,r):o):typeof e=="string"?y(e,n,r):e}function ue(e,n,r){return {id:e.id,kind:e.kind,label:y(e.label,n,r),attributes:Object.fromEntries(Object.entries(e.attributes).map(([o,i])=>[o,se(i,n,r)])),proofIds:[...e.proofIds].sort()}}function me(e,n,r){let o=(...c)=>e.filter(a=>c.includes(a.kind)).map(a=>ue(a,n,r)).slice(0,32),i=[];for(let c of e){for(let[a,l]of Object.entries(c.attributes))if(/(?:^|[-_.])ports?(?:$|[-_.])/i.test(a)&&(i.push({entityId:c.id,label:y(c.label,n,r),attribute:a,value:se(l,n,r)}),i.length>=32))break;if(i.length>=32)break}return {services:o("service"),packages:o("package"),protocols:o("protocol"),runtimeUnits:o("runtime-unit"),lifecycleStages:o("lifecycle-stage"),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:i}}function fe(e,n,r){let o=x(e.artifact,n,r);return o?{id:e.id,provider:e.provider,artifact:o,...e.pointer?{pointer:y(e.pointer,n,r)}:{},...e.line!==void 0?{line:e.line}:{},derivation:e.derivation,trust:e.trust,confidence:e.confidence,freshness:e.freshness}:null}async function he(e,n,r){let o=[],i=await b(p.join(e,".workspai","reports","INDEX.json"));if(Array.isArray(i?.blockers))for(let a of i.blockers)typeof a=="string"&&(a.startsWith(`${r}:`)||a.includes(`project:${r}`)||a.includes(`project ${r}`))&&o.push({source:"workspace-report-index",severity:"error",message:y(a,e,n)});let c=await b(p.join(e,".workspai","reports","doctor-project-last-run.json"));if(c?.projectName===r)for(let a of c$1({project:c.project}))o.push({source:"doctor-project",severity:a.status==="blocking"?"error":"warning",message:y(a.message,e,n),...a.id?{code:a.id}:{}});return [...new Map(o.map(a=>[`${a.source}:${a.code??""}:${a.message}`,a])).values()].slice(0,32)}function M(e,n=[]){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)||n.some(r=>r.length>0&&(e.includes(r)||e.includes(r.replace(/\\/g,"/")))):Array.isArray(e)?e.some(r=>M(r,n)):e&&typeof e=="object"?Object.values(e).some(r=>M(r,n)):false}function ke(e){return te.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function je(e$1){let n=p.resolve(e$1.workspacePath),r=p.resolve(e$1.projectPath),o=t(r,"project.json").find(s=>D.existsSync(s)),i$1=o?await b(o):null,c=await b(p.join(n,".workspai","workspace.contract.json")),a$1=p.resolve(r),l=c?.projects?.find(s=>s.externalPath?p.resolve(s.externalPath)===a$1:!s.relativePath||s.relativePath.startsWith("external/")?false:p.resolve(n,s.relativePath)===a$1)??c?.projects?.find(s=>s.slug===e$1.projectName||s.slug===p.basename(r)),d$1=e$1.projectName??(typeof i$1?.name=="string"?i$1.name:void 0)??l?.slug??p.basename(r),u=l?.relativePath??(()=>{let s=R(p.relative(n,r));return !s||s.startsWith("..")?`external/${d$1}`:s})(),m=await b(p.join(n,e.model)),k=await b(p.join(n,e.knowledgeGraph)),w=m?d(m):void 0,P=!!(w&&k?.source.hash===w),f=le({model:m,projectName:d$1,relativePath:u}),g=ge(P?k:null,d$1),C=await he(n,r,d$1),S=g.proofs.map(s=>s.freshness),T=k?!P||S.includes("stale")?"stale":S.includes("unknown")?"unknown":"fresh":"missing",$=m?m.factFreshness?.status??"unknown":"missing",A=[...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&&!f?[{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."}]:[],...k?[]:[{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."}],...k&&!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."}]:[]],L=oe(i$1,e$1.relationship??l?.relationship??"managed"),I={schemaVersion:ce,generatedAt:(e$1.now??new Date).toISOString(),workspace:{name:c?.workspace?.name??m?.workspace.name??p.basename(n),...c?.workspace?.profile||m?.workspace.profile?{profile:c?.workspace?.profile??m?.workspace.profile}:{},relationship:L,contract:i.workspaceContract,model:e.model,knowledgeGraph:e.knowledgeGraph,access:{localBinding:i.projectWorkspaceLink,canonicalEvidenceAvailableAtGeneration:true}},project:{name:d$1,relativePath:u,...f?.kind?{kind:f.kind}:{},...f?.runtime||l?.runtime?{runtime:f?.runtime??l?.runtime}:{},...f?.runtimeCandidates?.length?{runtimeCandidates:[...f.runtimeCandidates].sort()}:{},...f?.framework||l?.framework?{framework:f?.framework??l?.framework}:{},...f?.kit||l?.kit?{kit:f?.kit??l?.kit}:{},...f?.supportTier?{supportTier:f.supportTier}:{},commands:{supported:[...f?.commands.supported??[]].sort(),unsupported:[...f?.commands.unsupported??[]].sort(),fleetStages:[...f?.commands.fleetStages??[]].sort()},importantFiles:[...new Set((f?.importantFiles??[]).map(s=>x(s,n,r)).filter(s=>s!==null))].sort()},intelligence:{...m?.generatedAt?{modelGeneratedAt:m.generatedAt}:{},...k?.generatedAt?{graphGeneratedAt:k.generatedAt}:{},...k?.source.hash?{graphModelHash:k.source.hash}:{},entityCount:g.entityCount,relationCount:g.relationCount,proofCount:g.proofCount,entitiesByKind:g.entitiesByKind,relationsByKind:g.relationsByKind,languages:g.languages,semantic:g.semantic,relatedProjects:g.relatedProjects,freshness:{model:$,graph:T,graphMatchesModel:P},topology:{...g.topology,dependencies:g.topology.dependencies.map(s=>({...s,evidence:s.evidence.map(h=>x(h,n,r)).filter(h=>h!==null)})),dependents:g.topology.dependents.map(s=>({...s,evidence:s.evidence.map(h=>x(h,n,r)).filter(h=>h!==null)}))},surfaces:me(g.entities,n,r),diagnostics:[...A,...g.diagnostics].map(s=>({...s,message:y(s.message,n,r),...s.recommendation?{recommendation:y(s.recommendation,n,r)}:{}}))},evidence:{readOrder:[".workspai/PROJECT-GROUNDING.md",i.projectContextAgent,"AGENTS.md","workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`workspace:${e.model}`,`workspace:${e.knowledgeGraph}`],projectProofArtifacts:[...new Set(g.proofArtifacts.map(s=>x(s,n,r)).filter(s=>s!==null))],relations:g.relations.map(s=>({id:s.id,from:s.from,to:s.to,kind:s.kind,derivation:s.derivation,trust:s.trust,confidence:s.confidence,proofIds:[...s.proofIds].sort()})),proofs:g.proofs.map(s=>fe(s,n,r)).filter(s=>s!==null)},blockers:C,agentRouting:{enforcement:"required",mandatoryPreflight:{command:"npx workspai project workspace status --json",successCondition:"resolved"},workspaceEvidenceRequiredFor:["repository-analysis","architecture-analysis","change-impact","cross-project-change","contract-change","infrastructure-change","release-readiness"],requiredReadOrder:[i.projectContextAgent,"command:npx workspai project workspace status --json","workspace:.workspai/reports/INDEX.json","workspace:.workspai/reports/workspace-context-agent.json",`command:npx workspai workspace graph search ${JSON.stringify(d$1)} --scope ${JSON.stringify(`project:${d$1}`)} --limit 12 --json`],degradedMode:{allowCompleteArchitectureClaims:false,requireDisclosure:true}},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(d$1)} --scope ${JSON.stringify(`project:${d$1}`)} --limit 12 --json`,doctor:"npx workspai doctor project --json",workspaceStatus:"npx workspai project workspace status --json"}};if(M(I,[n,r]))throw new Error("Project context lens rejected a non-portable absolute path.");let t$1={...I,integrity:{algorithm:"sha256",...w?{modelHash:w}:{},payloadHash:ke(I),portable:true,absolutePathsEmitted:false}};return a(t$1,"contracts/workspace-intelligence/project-context-agent.v1.json","Project context agent"),t$1}function we(e){let n=e.intelligence.relatedProjects.length>0?e.intelligence.relatedProjects.map(i=>`\`${i}\``).join(", "):"No proven cross-project relation is currently available.",r=e.intelligence.diagnostics.length>0?e.intelligence.diagnostics.slice(0,8).map(i=>`- **${i.severity} \xB7 ${i.code}:** ${i.message}`).join(`
2
- `):"- No project-scoped graph diagnostic is currently recorded.",o=e.blockers.length>0?e.blockers.slice(0,12).map(i=>`- **${i.severity}${i.code?` \xB7 ${i.code}`:""}:** ${i.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
- This is a mandatory agent preflight, not optional background material:
11
-
12
- 1. Read \`.workspai/reports/project-context-agent.json\` before broad source discovery.
13
- 2. Run \`${e.commands.workspaceStatus}\` and require a resolved workspace.
14
- 3. For repository analysis, architecture analysis, change impact, contracts, infrastructure, or release readiness, read the canonical workspace \`.workspai/reports/INDEX.json\` and \`workspace-context-agent.json\` even when the request names only this repository.
15
- 4. Run the bounded agent graph search below before broad source scanning, then use targeted graph evidence/path queries as needed.
16
- 5. Use source inspection to verify and deepen the workspace evidence, not to silently replace it.
17
- 6. Do not claim complete architecture, independence, health, readiness, or verification without current Workspai evidence.
18
-
19
- If workspace resolution, required reports, or graph retrieval is unavailable, explicitly report degraded mode and the missing evidence. In degraded mode an agent may inspect source, but must not claim a complete architectural understanding.
20
-
21
- The Workspace Model owns canonical project identity and its compact \`projectTopology\`.
22
- The Workspace Knowledge Graph is a separate, proof-backed enrichment containing
23
- files, symbols, APIs, infrastructure, tests, owners, and decisions. Do not treat
24
- an unproven topology edge as proof that two projects are independent.
25
-
26
- ## Project
27
-
28
- - Name: \`${e.project.name}\`
29
- - Workspace-relative identity: \`${e.project.relativePath}\`
30
- - Runtime: \`${e.project.runtime??"unknown"}\`
31
- - Framework: \`${e.project.framework??"unknown"}\`
32
- - Relationship: \`${e.workspace.relationship}\`
33
- - Related projects: ${n}
34
- - Topology status: \`${e.intelligence.topology.status}\`
35
- - Model freshness: \`${e.intelligence.freshness.model}\`
36
- - Knowledge Graph freshness: \`${e.intelligence.freshness.graph}\`
37
-
38
- ## Current evidence coverage
39
-
40
- - Project-scoped entities: ${e.intelligence.entityCount}
41
- - Project-scoped relations: ${e.intelligence.relationCount}
42
- - Portable proofs: ${e.intelligence.proofCount}
43
-
44
- ${r}
45
-
46
- ## Current project blockers
47
-
48
- ${o}
49
-
50
- ## Safe commands from this project
51
-
52
- \`\`\`bash
53
- ${e.commands.workspaceStatus}
54
- ${e.commands.doctor}
55
- ${e.commands.graphSearch}
56
- ${e.commands.verify}
57
- \`\`\`
58
-
59
- The machine-local workspace path lives only in \`.workspai/workspace-link.local.json\`, which is gitignored. Portable grounding files never publish that path.
60
- `}function ye(e){return `# Workspai project boundary
61
-
62
- - Project: \`${e.project.name}\`
63
- - Canonical workspace: \`${e.workspace.name}\`
64
- - Portable project lens: \`.workspai/reports/project-context-agent.json\`
65
- - Project grounding: \`.workspai/PROJECT-GROUNDING.md\`
66
- - Workspace discovery: run \`npx workspai project workspace status --json\`
67
-
68
- Before broad source discovery, every agent must read the project lens and run \`${e.commands.workspaceStatus}\`; continue as fully grounded only when workspace resolution succeeds. Repository analysis, architecture analysis, change impact, contracts, APIs, infrastructure, and release readiness always require canonical workspace evidence and the bounded agent graph search, even when the request names only this repository. Source inspection verifies and deepens that evidence; it does not replace it silently. If required evidence is unavailable or stale, disclose degraded mode and do not claim complete architecture, independence, health, readiness, or verification. The user does not need to preload the 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 Z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(e,n){return new RegExp(`${Z(e)}[\\s\\S]*?${Z(n)}`,"m")}function ie(e){let n=e.replace(Y(ne,re),"");return d$1(n)?.includes("# Workspai project boundary")&&(n=n.replace(Y(a$1,b$1),"")),n.replace(/\n{3,}/g,`
69
-
70
- `).trim()}function Pe(e,n){let r=ie(e),o=`${ne}
71
- ${n.trim()}
72
- ${re}`;return r?`${r}
73
-
74
- ${o}
75
- `:`${o}
76
- `}async function O(e,n){await j.mkdir(p.dirname(e),{recursive:true});let r=`${e}.${process.pid}.${te.randomUUID()}.tmp`;try{await j.writeFile(r,n,"utf8");try{await j.rename(r,e);}catch(o){let i=o.code;if(i!=="EEXIST"&&i!=="EPERM")throw o;await ae.move(r,e,{overwrite:true});}}finally{await j.rm(r,{force:true}).catch(()=>{});}}async function be(e,n){let r;try{r=await execa("git",["rev-parse","--show-toplevel"],{cwd:e,reject:false});}catch{return false}if(r?.exitCode!==0)return false;let o=r.stdout.trim();if(!o)return false;let i,c;try{[i,c]=await Promise.all([j.realpath(p.resolve(o)),j.realpath(e)]);}catch{return false}let a=p.resolve(c,n),l=p.relative(i,a).replace(/\\/g,"/");if(!l||p.isAbsolute(l)||l===".."||l.startsWith("../"))return false;let d;try{d=await execa("git",["cat-file","-e",`HEAD:${l}`],{cwd:i,reject:false});}catch{return false}if(d?.exitCode!==0)return false;let u;try{u=await execa("git",["ls-files","--deleted","--error-unmatch","--",`:(top)${l}`],{cwd:i,reject:false});}catch{return false}return u?.exitCode===0}async function Q(e,n){let r=p.join(e,".gitignore"),o=await j.readFile(r,"utf8").catch(l=>{if(l.code==="ENOENT")return "";throw l}),i=[g,h$1],c=o.split(/\r?\n/).filter(l=>l.trim()!=="# Workspai local project grounding"&&!i.includes(l.trim()));for(;c.length>0&&c[c.length-1]==="";)c.pop();n==="local"&&(c.length>0&&c.push(""),c.push("# Workspai local project grounding",...i));let a=c.length>0?`${c.join(`
77
- `)}
78
- `:"";a!==o&&await O(r,a);}async function ee(e,n,r){let o=p.join(e,"AGENTS.md"),i=await j.lstat(o).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(i?.isSymbolicLink())return;let c=i?.isFile()===true,a=await j.readFile(o,"utf8").catch(u=>{if(u.code==="ENOENT")return "";throw u});if(n==="managed"&&!r)throw new Error("Managed project grounding requires a project context.");if(n==="managed"&&!c&&await be(e,"AGENTS.md"))return;let l=n==="managed"&&r?Pe(a,ye(r)):ie(a);if(!l){c&&await j.rm(o,{force:true});return}let d=`${l.trimEnd()}
79
- `;return d!==a&&await O(o,d),n==="managed"?o:void 0}async function ve(e){let n=e.mode??"managed",r=p.resolve(e.workspacePath),o=p.resolve(e.projectPath);if(n==="off"){let k=t(o,"project.json").find(C=>D.existsSync(C)),w=k?await b(k):null,P=e.projectName??(typeof w?.name=="string"?w.name:void 0)??p.basename(o),f=oe(w,e.relationship??"managed"),g$1=await c({workspacePath:r,projectPath:o,projectName:P,relationship:f,now:e.now});return await Q(o,n),await ee(o,n),await Promise.all([j.rm(p.join(o,h$1),{force:true}),j.rm(p.join(o,g),{force:true})]),{mode:n,projectPath:o,linkPath:g$1.linkPath,writtenFiles:[i.projectWorkspaceLink]}}let i$1=await je(e),c$1=i$1.workspace.relationship,a=await c({workspacePath:r,projectPath:o,projectName:i$1.project.name,relationship:c$1,workspaceName:i$1.workspace.name,relativePath:i$1.project.relativePath,now:e.now});await Q(o,n);let l=await ee(o,n,i$1),d=p.join(o,h$1),u=p.join(o,g);await O(d,`${JSON.stringify(i$1,null,2)}
80
- `),await O(u,`${we(i$1).trimEnd()}
81
- `);let m=[i.projectWorkspaceLink,h$1,g];return l&&m.push("AGENTS.md"),{mode:n,projectPath:o,linkPath:a.linkPath,groundingPath:u,contextPath:d,agentsPath:l,writtenFiles:m}}async function Fe(e){let n=p.resolve(e.workspacePath),r=e.mode??"managed",o=await Ee(n),i=[],c=[];for(let a of o.resolved)try{i.push(await ve({workspacePath:n,projectPath:a.projectPath,projectName:a.name,relationship:a.relationship,mode:r,now:e.now}));}catch(l){c.push({name:a.name,reason:l instanceof Error?l.message:String(l)});}return {workspacePath:n,mode:r,projects:i,skipped:[...o.skipped,...c]}}async function Ee(e){let n=p.resolve(e),r=await b(p.join(n,".workspai","workspace.contract.json")),o=[],i=[];for(let c of r?.projects??[]){let a=c.slug??c.relativePath??"unknown-project",l=typeof c.externalPath=="string"?p.resolve(c.externalPath):typeof c.relativePath=="string"&&!c.relativePath.startsWith("external/")?p.resolve(n,c.relativePath):null;if(!l||!D.existsSync(l)){i.push({name:a,reason:"project path is unavailable on this machine"});continue}o.push({name:a,projectPath:l,relationship:c.relationship??"managed"});}return {resolved:o,skipped:i}}export{ce as a,De as b,ne as c,re as d,je as e,ve as f,Fe as g,Ee as h};
@@ -1 +0,0 @@
1
- import {b,c as c$2}from'./chunk-QK5QOXOE.js';import {a as a$1}from'./chunk-YM77FQB3.js';import {r as r$1}from'./chunk-TTFQWH55.js';import {a as a$2}from'./chunk-N2BIIUDH.js';import {g}from'./chunk-IUYZ3NHS.js';import {j as j$1,e as e$2}from'./chunk-GBMCHFOV.js';import {j,l as l$2}from'./chunk-RPHM7LQW.js';import {c as c$1,d}from'./chunk-VUR7H2FU.js';import {a}from'./chunk-UQEQ6CXU.js';import {f as f$1,g as g$1,h as h$2}from'./chunk-6OFGLNFS.js';import {k,l as l$1,h as h$1,m as m$1,n,p as p$2,q}from'./chunk-QHY6F4SS.js';import {m,p as p$1,s}from'./chunk-GXTCU4WF.js';import {l,o as o$1,p as p$3}from'./chunk-SNO3WG4V.js';import {c,e as e$1}from'./chunk-ADL3CK44.js';import {b as b$1}from'./chunk-LYVDRRDO.js';import {e,f,o,p,n as n$1,m as m$2}from'./chunk-5EPPPMAS.js';import {d as d$1}from'./chunk-VRW6KXNK.js';import ue from'path';import de from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function ce(t,s){return t.length===s.length&&t.every((g,u)=>g===s[u])}function le(t){b$1(e.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a,`chainSchemaVersion must be ${a}`),r(t.artifactPath===e.intelligenceRun,`artifactPath must be ${e.intelligenceRun}`),r(t.preflight.length===n$1.length,`preflight must contain exactly ${n$1.length} entries`);for(let[l,n]of n$1.entries()){let a=t.preflight[l];r(a?.id===n,`preflight[${l}].id must be ${n}`),r(ce(a.artifacts,o[n]),`${n} preflight artifacts must match the runtime registry`),n==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===m$2.length,`stages must contain exactly ${m$2.length} canonical steps`);let g=t.preflight[0],u=g?.status==="failed";for(let[l,n]of m$2.entries()){let a=t.stages[l];r(a?.id===n,`stages[${l}].id must be ${n}`),r(ce(a.artifacts,p[n].produces),`${n} artifacts must match the runtime registry`),u&&r(a.status==="skipped",`${n} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${n} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${n} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${n} failed stage must have exitCode 1`),u=true):(r(a.exitCode===0,`${n} skipped stage must have exitCode 0`),r(a.durationMs===0,`${n} skipped stage must have durationMs 0`)),l===0&&((g?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(g?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(u=true));}let m=t.preflight.some(l=>l.status==="failed")||t.stages.some(l=>l.status==="failed"),y=t.stages.some(l=>l.status==="blocked"),c=m?"failed":y?"blocked":"passed",f=c==="failed"?1:c==="blocked"?2:0;r(t.status===c,`status must be ${c}`),r(t.exitCode===f,`exitCode must be ${f}`);}var he=e.intelligenceRun,Ie=f.intelligenceRun,x=he;function h(t){d$1({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function ze(t){let s=ue.resolve(t.workspacePath);return c(s,x,()=>Ee({...t,workspacePath:s}),{timeoutMs:15*6e4,staleAfterMs:3e4})}async function Ee(t){let s$1=t.workspacePath,g$2=[],u=[],m$2=false,y=async(e,i)=>{let o$1=[...o[e]];if(m$2){h({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),g$2.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:o$1,message:"skipped because a required upstream operation failed"});return}let I=Date.now();h({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let d=await i();h({id:e,kind:"preflight",status:"passed",message:d.message}),g$2.push({id:e,status:"passed",result:d.result,durationMs:Date.now()-I,artifacts:o$1,message:d.message});}catch(d){m$2=true;let k=d instanceof Error?d.message:String(d);h({id:e,kind:"preflight",status:"failed",message:k}),g$2.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-I,artifacts:o$1,message:k});}},c=async(e,i)=>{let o=[...p[e].produces];if(m$2){h({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),u.push({id:e,status:"skipped",durationMs:0,artifacts:o,exitCode:0,message:"skipped because a required upstream stage failed"});return}let I=Date.now();h({id:e,kind:"stage",status:"started",message:`${e} started`});try{let d=await i(),k=d.exitCode??0,_=d.blocked||k!==0?"blocked":"passed";h({id:e,kind:"stage",status:_,message:d.message}),u.push({id:e,status:_,durationMs:Date.now()-I,artifacts:o,exitCode:k,message:d.message});}catch(d){m$2=true;let k=d instanceof Error?d.message:String(d);h({id:e,kind:"stage",status:"failed",message:k}),u.push({id:e,status:"failed",durationMs:Date.now()-I,artifacts:o,exitCode:1,message:k});}};await y("sync",async()=>{let e=await g(s$1,true),i=await l({workspacePath:s$1});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${i.contract.projects.length} projects`}});let f,l$3=()=>{if(!f)throw new Error("canonical workspace model is unavailable");return f};await c("model",async()=>(f={...await p$1({workspacePath:s$1,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(f,s$1),{message:`${f.summary.projectCount} projects modeled`}));let n$1=ue.join(s$1,e.snapshot),a$3=false;await y("baseline",async()=>{if(!await de.pathExists(n$1)){let o=await k({workspacePath:s$1,model:l$3()});return await l$1(o,s$1),a$3=true,{result:"created",message:"initial structural baseline created"}}let e=await de.readJson(n$1),i=h$1(e);return i?(await l$1(i,s$1),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await c("diff",async()=>{let e$1=await m$1({workspacePath:s$1,fromPath:e.snapshot,model:l$3()});return await n(e$1,s$1),{message:e$1.summary.changed?"workspace changes detected":"no workspace changes"}}),await c("impact",async()=>{let e$1=await p$2({workspacePath:s$1,fromPath:e.diff});return await q(e$1,s$1),{message:`${e$1.summary.risk} risk; ${e$1.summary.affectedProjects} affected`}}),await c("doctor-evidence",async()=>{let e=await r$1({workspace:s$1,json:true,quiet:true,profile:t.strict===true?"enterprise-strict":"local"});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await c("contract-evidence",async()=>{let e=await o$1({workspacePath:s$1,strict:true});return await p$3({workspacePath:s$1,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await c("analyze-evidence",async()=>{let e=await a$1({workspacePath:s$1,json:true,strict:t.strict===true});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await c("readiness-evidence",async()=>{let e=await a$2({startPath:s$1,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await c("verify",async()=>{let e$1=await f$1({workspacePath:s$1,fromImpactPath:e.impact});await g$1(e$1,s$1);let i=h$2(e$1,{strict:t.strict===true});return await j$1(s$1,e$2(e$1,i.passed)),{blocked:!i.passed,exitCode:i.exitCode,message:`${e$1.summary.verdict}; gate ${i.passed?"passed":"blocked"}`}}),await c("context",async()=>{let e=await c$1({workspacePath:s$1,model:l$3(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$1),{message:`context grounded for ${e.agent}`}}),await c("agent-sync",async()=>{let e=await l$2({workspacePath:s$1,agent:t.agent??"generic",write:true,refreshContext:false,strict:t.strict===true,preset:"enterprise"}),i=e.strictViolations??[],o=t.strict===true&&i.length>0;return {blocked:o,exitCode:o?2:0,message:o?`${e.writtenFiles.length} grounding files written; ${i.length} strict grounding violation(s): ${i.join("; ")}`:`${e.writtenFiles.length} grounding files written`}}),await c("explain",async()=>{let e=await b({workspacePath:s$1,target:{kind:"release-blocked"}});await c$2(e,s$1);let i=t.strict===true?u.filter(o=>o.status==="blocked").map(o=>o.id):[];return {message:i.length>0&&e.blocking!==true?`Strict policy blocked advisory or incomplete evidence in ${i.join(", ")}. ${e.summary}`:e.summary}});let pe=u.some(e=>e.status==="blocked"),A=m$2?"failed":pe?"blocked":"passed",ge=m$2?1:A==="blocked"?2:0,R={schemaVersion:Ie,chainSchemaVersion:a,generatedAt:new Date().toISOString(),workspacePath:s$1,baselineCreated:a$3,preflight:g$2,status:A,exitCode:ge,stages:u,artifactPath:x};le(R),await e$1(s$1,x,R);let me=await j({workspacePath:s$1});return await e$1(s$1,e.agentIndex,me),R}export{he as a,Ie as b,ze as c};
@@ -1 +0,0 @@
1
- export{b as PROJECT_TEST_COVERAGE_ARTIFACT,a as PROJECT_TEST_COVERAGE_SCHEMA,c as collectProjectTestCoverage}from'./chunk-3U4VLIGW.js';
@@ -1 +0,0 @@
1
- export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-QK5QOXOE.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-64JUYYRC.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-QHY6F4SS.js';
@@ -1 +0,0 @@
1
- export{a as WORKSPACE_EXPLAIN_SCHEMA_VERSION,b as WORKSPACE_EXPLAIN_TARGETS,e as isWorkspaceExplainReport,c as parseWorkspaceExplainTarget,d as resolveWorkspaceTraceTarget}from'./chunk-NHTLE3WN.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-64JUYYRC.js';
@@ -1,3 +0,0 @@
1
- import {c as c$2}from'./chunk-VZPWIILU.js';import {a as a$1}from'./chunk-YJTEMJFV.js';import {d as d$1,i as i$1,j as j$1,k,h as h$2,m,n,o}from'./chunk-TTFQWH55.js';import {c,e,j,d,g,b,i,f}from'./chunk-PKIRVQLG.js';import {a as a$2}from'./chunk-AO2ZI42U.js';import {h as h$1}from'./chunk-DT4X7I5M.js';import {a}from'./chunk-AFIFZTOY.js';import {e as e$1}from'./chunk-5EPPPMAS.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import h from'fs-extra';var $e=".workspai/repair",ga="transaction.json",fa="source-plan.json",Ue="checkpoint",ka="engine.lock",aa=5*1024*1024,ma=25*1024*1024,wa=25*1024*1024,ta=4*1024*1024,ba=900*1e3,va=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),ya=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),_={safe:0,guarded:1,invasive:2},Pa=new Set(["node","npm","npx","pnpm","yarn","bun","deno","python","python3","py","pip","pip3","poetry","uv","pytest","pip-audit","govulncheck","go","cargo","composer","bundle","bundle-audit","dotnet","mvn","mvnw","gradle","gradlew","mix","clojure","lein","sbt","make"]);function Ra(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function N(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${$(e).slice(0,16)}`,message:r.message??e}]}}function ra(e){let a=new Map,r=t=>a.set(Ra(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=ye(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),_[t.risk]>_[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(s=>s.invocation&&`tool:${s.invocation.cwd}:${s.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${$(t).slice(0,16)}`,message:t});}return [...a.values()]}function D(e){return (e?.()??new Date).toISOString()}function $(e){return createHash("sha256").update(e).digest("hex")}function Q(e){return Array.isArray(e)?`[${e.map(Q).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${Q(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}var Ae="causal-action-integrity:";function oa(e){return $(Q([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function sa(e){if(e.length===0)return;let a=oa(e);return {id:`${Ae}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function C(e,a){let r=c$1.relative(c$1.resolve(e),c$1.resolve(a));return r===""||!r.startsWith("..")&&!c$1.isAbsolute(r)}async function H(e,a){let r=await h.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await h.pathExists(t);){let s=c$1.dirname(t);if(s===t)return false;t=s;}let o=await h.realpath(t).catch(()=>c$1.resolve(t));return C(r,o)}function F(e,a){let r=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!C(e,r))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,r).split(c$1.sep).join("/")||"."}function ae(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,$e,"transactions",a)}function ve(e,a){return c$1.join(ae(e,a),ga)}function Se(e,a){return c$1.join(ae(e,a),fa)}async function Z(e,a){await h.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await h.writeJson(r,a,{spaces:2}),await h.move(r,e,{overwrite:true});}function A(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:D(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function R(e$1,a$1,r){a$1.revision+=1,a$1.updatedAt=D(r),a(a$1,e,"Workspace repair transaction"),await Z(ve(e$1,a$1.transactionId),a$1),await Z(c$1.join(e$1,d),a$1);}async function ce(e$1){let a$1=await h.readJson(ve(e$1.workspacePath,e$1.transactionId));if(a$1.schemaVersion!==c)throw new Error(`Unsupported repair transaction schema: ${a$1.schemaVersion}`);return a(a$1,e,"Workspace repair transaction"),a$1}async function Ce(e,a){return await h.readJson(Se(e,a))}function we(e){return e.schemaVersion===f}function he(e,a){let r=a.scope==="project"&&a.projectPath?a.projectPath:".",t=c$1.isAbsolute(r)?c$1.resolve(r):c$1.resolve(e,r);if(!C(e,t))throw new Error(`Repair project scope escapes workspace: ${r}`);return t}function v(e){return {cwd:F(e.workspacePath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Ie(e){return h.readFile(e,"utf8").catch(()=>"")}async function xa(e){return h.readJson(e).catch(()=>({}))}function Ye(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function ja(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(t=>r?[c$1.join(t,e)]:a.map(o=>c$1.join(t,`${e}${o}`)))}function Xe(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ia(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(c$1.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=c$1.isAbsolute(r)?r:c$1.resolve(a,r),o=await h.stat(t).catch(()=>{});return Xe(o)}for(let t of ja(r)){let o=await h.stat(t).catch(()=>{});if(Xe(o))return true}return false}async function We(e){let a=new Set;for(let s of e.stages){if(s.kind!=="repair"||!s.invocation)continue;let d=Pe(s.invocation.executable);!["python","python3","py"].includes(d)||!s.invocation.args.includes("venv")||!s.invocation.args.includes(".venv")||a.add(c$1.normalize(c$1.join(c$1.resolve(e.workspacePath,s.invocation.cwd),".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),t=new Map;for(let s of r)t.set(`${s.cwd}\0${s.executable}`,s);let o=[];for(let s of t.values()){let d=c$1.isAbsolute(s.executable)?c$1.normalize(s.executable):c$1.normalize(c$1.resolve(e.workspacePath,s.cwd,s.executable));if(a.has(d)){o.push({id:`tool:${s.cwd}:${s.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${s.executable} (${s.cwd}).`});continue}let i=await ia({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});o.push({id:`tool:${s.cwd}:${s.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${s.executable} (${s.cwd}).`:`Required repair executable is unavailable: ${s.executable} (${s.cwd}). Install or configure it, then create a fresh plan.`});}return o}function X(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function y(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function Ia(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return v({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function Aa(e){let a=he(e.workspacePath,e.action),r=F(e.workspacePath,a),t=async p=>h.pathExists(c$1.join(a,p)),o=new Set,s=[],d=[],i$1=p=>`${r}:${e.adapterId}:${p}`,g=p=>p.forEach(P=>o.add(F(e.workspacePath,c$1.join(a,P)))),n=p=>{s.push(p),p.required&&p.status==="blocked"&&d.push(p.summary);},f=Ia(e.workspacePath,a,e.action),k=()=>{let p=i.find(P=>P.id===e.adapterId);if(!p)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:s,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:p.id,ecosystem:p.ecosystem,projectPath:r,manifests:p.manifests,support:p.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(s.filter(P=>P.required&&P.invocation).map(P=>P.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${p.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let p=await xa(c$1.join(a,"package.json")),P=p.scripts&&typeof p.scripts=="object"&&!Array.isArray(p.scripts)?p.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",T=b==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":b==="pnpm"?"pnpm-lock.yaml":b==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";g(["package.json",T]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${b} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:["install"],purpose:"reconcile"})}));let S=v(b==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return n(y({id:i$1("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:f??S})),n(typeof P.test=="string"&&P.test.trim()?y({id:i$1("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Ye({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):X(i$1("test"),"test","No test script is declared.")),n(typeof P.build=="string"&&P.build.trim()?y({id:i$1("build"),kind:"build",summary:"Run the declared project build contract.",invocation:Ye({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):X(i$1("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){g(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let p=e.action.transaction?.ecosystem.toLowerCase(),P=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=P==="uv"||p==="uv"||await t("uv.lock"),T=!b&&(P==="poetry"||p==="poetry"||await t("poetry.lock")),S=!b&&!T&&["python","python3","py"].includes(P)&&(e.action.invocation?.args??[]).some(L=>L==="venv")&&(e.action.invocation?.args??[]).some(L=>L===".venv"),j=process.platform==="win32"?"python":"python3",O=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await h.pathExists(O)||S)&&(j=O);let te=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):T?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&C(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&C(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:te})),n(y({id:i$1("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:f}));let M=await Ie(c$1.join(a,"pyproject.toml")),B=await t("tests")||/\[tool\.pytest/i.test(M),J=v(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pytest"],purpose:"test"}),re=v(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","build"],purpose:"build"});return n(B?y({id:i$1("test"),kind:"test",summary:"Run the Python test contract.",invocation:J}):X(i$1("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(M)?y({id:i$1("build"),kind:"build",summary:"Build the declared Python package.",invocation:re}):X(i$1("build"),"build","No Python build contract is declared.")),k()}let m=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let p of m){if(p.adapterId!==e.adapterId)continue;let P=await t(p.manifest)?p.manifest:p.alternateManifest&&await t(p.alternateManifest)?p.alternateManifest:void 0;if(!P)continue;g(p.files),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${P} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.reconcile[0],args:p.reconcile[1],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:f??(p.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:p.audit[0],args:p.audit[1],purpose:"audit"}):void 0)}));let b=await Ie(c$1.join(a,P)),T=p.manifest==="composer.json"||p.adapterId==="deno"?/["']test["']\s*:/.test(b):p.manifest==="Gemfile"?await t("Rakefile"):true,S=p.manifest==="composer.json"||p.manifest==="deno.json"?/["']build["']\s*:/.test(b):p.manifest==="Gemfile"?(await h.readdir(a)).some(j=>j.endsWith(".gemspec")):true;return n(T?y({id:i$1("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.test[0],args:p.test[1],purpose:"test"})}):X(i$1("test"),"test","No test contract is declared.")),n(S?y({id:i$1("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.build[0],args:p.build[1],purpose:"build"})}):X(i$1("build"),"build","No build contract is declared.")),k()}let x=await h.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&x.some(p=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(p)))return g(["Directory.Packages.props","packages.lock.json",...x.filter(p=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(p))]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:f??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(y({id:i$1("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),k();let I=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return g(["pom.xml"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["dependency:resolve"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["package","-DskipTests"],purpose:"build"})})),k();let W=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&W){let p=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g([W,"gradle.lockfile","gradle/libs.versions.toml"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["dependencies"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["build","-x","test"],purpose:"build"})})),k()}let w=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&w){let p=w==="deps.edn",P=await Ie(c$1.join(a,w)),b=p?"clojure":"lein";g([w]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${w} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:p?["-P"]:["deps"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:f}));let T=!p||/:test\b/.test(P);return n(T?y({id:i$1("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:p?["-M:test"]:["test"],purpose:"test"})}):X(i$1("test"),"test","No Clojure :test alias is declared.")),n(p?X(i$1("build"),"build","No portable Clojure CLI build entrypoint is declared."):y({id:i$1("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),k()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(g(["build.sbt"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),n(y({id:i$1("reconcile"),kind:"reconcile",required:true,summary:d[0]})),k())}async function na(e){let a=s=>h.pathExists(c$1.join(e,s)),r=await h.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(s=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(i.map((s,d)=>[s.id,d]));return [...new Set(t)].sort((s,d)=>(o.get(s)??999)-(o.get(d)??999))}function Ea(e){let a=e?.trim().toLowerCase();if(a){if(["npm","pnpm","yarn","bun","node","javascript","typescript"].includes(a))return "node";if(["python","pip","poetry","uv"].includes(a))return "python";if(["go","gomod","go-modules"].includes(a))return "go";if(["rust","cargo"].includes(a))return "rust";if(["php","composer"].includes(a))return "php-composer";if(["ruby","bundler","bundle"].includes(a))return "ruby-bundler";if(["elixir","mix"].includes(a))return "elixir-mix";if(a==="deno")return "deno";if(["dotnet",".net","nuget"].includes(a))return "dotnet";if(["maven","jvm-maven"].includes(a))return "jvm-maven";if(["gradle","jvm-gradle"].includes(a))return "jvm-gradle";if(["clojure","lein","leiningen"].includes(a))return "clojure";if(["scala","sbt","scala-sbt"].includes(a))return "scala-sbt"}}async function ca(e,a={}){let r=he(e.workspacePath,e.action),t=F(e.workspacePath,r),o=await na(r),s=Ea(e.action.transaction?.ecosystem),d=s?[s]:o;if(s&&!o.includes(s)){let n=`Doctor declared the ${s} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[y({id:`${t}:${s}:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:s,ecosystem:i.find(f=>f.id===s)?.ecosystem??s,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:n}]}}if(d.length===0){let n=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[y({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:n}]}}let i$1={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let n of d){let f=await Aa({...e,adapterId:n});i$1.stages.push(...f.stages),i$1.checkpointFiles.push(...f.checkpointFiles),i$1.blockers.push(...f.blockers),i$1.adapters.push(...f.adapters);}i$1.stages=[...new Map(i$1.stages.map(n=>[n.id,n])).values()],i$1.checkpointFiles=[...new Set(i$1.checkpointFiles)].sort(),i$1.blockers=[...new Set(i$1.blockers)];let g=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let n=new Set(e.action.transaction.requiredStages),f=Pe(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],m=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(f)&&k.includes("venv")&&k.includes(".venv");m&&g.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),i$1.stages=i$1.stages.filter(x=>x.kind==="reconcile"?m&&n.has("reconcile"):n.has(x.kind)),i$1.blockers=i$1.stages.filter(x=>x.required&&x.status==="blocked").map(x=>x.summary);}for(let n of i$1.adapters){let f=i$1.stages.filter(m=>m.id.startsWith(`${n.projectPath}:${n.adapterId}:`)),k=[];n.requiredExecutables=[...new Set(f.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))];for(let m of f){if(!m.required||!m.invocation)continue;let x=c$1.isAbsolute(m.invocation.executable)?c$1.normalize(m.invocation.executable):c$1.normalize(c$1.resolve(e.workspacePath,m.invocation.cwd,m.invocation.executable));g.has(x)||await ia({workspacePath:e.workspacePath,invocation:m.invocation,toolAvailable:a.toolAvailable})||k.push(m.invocation.executable);}n.missingExecutables=[...new Set(k)],n.missingExecutables.length>0&&(n.status="partial",n.message=`Required executable(s) unavailable: ${n.missingExecutables.join(", ")}.`);}if(d.length===1){let n=`:${d[0]}:`;for(let f of i$1.stages)f.id=f.id.replace(n,":");}return i$1}async function ut(e={}){let a=j();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let s=e.project.trim(),d=await h$1(r),i=s.replace(/\\/g,"/").replace(/^\.\//,""),g=c$1.resolve(r,s),n=d.resolved.filter(f=>{let k=C(r,f.projectPath)?F(r,f.projectPath):void 0;return f.name===s||k===i||c$1.resolve(f.projectPath)===g});if(n.length===0){let f=d.skipped.find(k=>k.name===s);throw f?new Error(`Registered project is unavailable for repair capability inspection: ${s} (${f.reason}).`):new Error(`Registered project not found for repair capability inspection: ${s}.`)}if(n.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${s}.`);t=c$1.resolve(n[0].projectPath),o=n[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!C(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=F(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await na(t)}}}function ye(e){if(e.command){let a=d$1(e.command);if(a)return a}return a$2(e.operation)??void 0}async function $a(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){let t=he(e.workspacePath,r);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);for(let d of r.files){let i=c$1.isAbsolute(d)?c$1.resolve(d):c$1.resolve(e.workspacePath,d);if(!await H(e.workspacePath,i))throw new Error(`Repair checkpoint path escapes workspace through a symbolic link: ${d}`);a.add(F(e.workspacePath,d));}let o=ye(r);if(!o)continue;let s="path"in o?o.path:void 0;if(s){let d=c$1.resolve(t,s);if(!await H(e.workspacePath,d))throw new Error(`Repair operation target escapes workspace through a symbolic link: ${s}`);a.add(F(e.workspacePath,d));}}return [...a].filter(r=>r!==".").sort()}function Sa(e,a){if(!a.invocation)return;let r=he(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Te(e){return $(Q({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function da(e){return Te({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}async function be(e,a){let r=[],t=[],o=0;for(let s of a){let d=c$1.resolve(e,s);if(!C(e,d)){t.push(`Checkpoint path escapes workspace: ${s}`);continue}if(!await H(e,d)){t.push(`Checkpoint path resolves through a link outside the workspace: ${s}`);continue}let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()){t.push(`Checkpoint refuses symbolic link mutation: ${s}`);continue}if(i&&!i.isFile()){t.push(`Checkpoint target is not a regular file: ${s}`);continue}if(i&&i.size>aa){t.push(`Checkpoint file exceeds 5 MiB: ${s}`);continue}if(o+=i?.size??0,o>ma){t.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let g=i?await h.readFile(d):void 0;r.push({path:s,existed:!!i,beforeHash:g?$(g):null,...i?{mode:i.mode}:{}});}return {entries:r,errors:t}}function pa(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}async function Ca(e){let a=await h.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function Wa(e){return va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Ta(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;C(e,t);){if((await h.readdir(t).catch(()=>[])).some(Wa))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function qa(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!C(a,o))return false;let s=c$1.basename(o);return ya.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function Na(e){let a=F(e.workspacePath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function Da(e,a){let r=Pe(a.executable),[t="",o=""]=a.args;if(a.args.some(i=>/^(?:-e|--eval|-c|--command|-command)$/i.test(i)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let s=["npm","pnpm","yarn","bun"].includes(r);if(!(s&&e.kind==="audit"&&a.args.some(i=>/audit/i.test(i))||s&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(i=>/^(?:test|build|check|verify|package)$/i.test(i))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function Fa(e){let a=[],r=new Set,t=[],o=[],s=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let i of e.proposal.validation??[]){let g=c$1.resolve(e.workspacePath,i.cwd),n=F(e.workspacePath,g),f=await h.lstat(g).catch(()=>{});if(!f?.isDirectory()||f.isSymbolicLink()||!await H(e.workspacePath,g)){t.push(`Validation ${i.id} requires a real directory inside the workspace.`);continue}if(d&&!C(d,g)){t.push(`Validation ${i.id} escapes the declared project scope.`);continue}if(_[i.risk]>_[e.maxRisk]){t.push(`Validation ${i.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:g,executable:i.executable,args:i.args,purpose:i.kind,timeoutMs:i.timeoutMs});try{qe(e.workspacePath,k,e.policy),Da(i,k);}catch(m){t.push(m instanceof Error?m.message:String(m));continue}a.push(y({id:`validation:${i.id}`,kind:i.kind,risk:i.risk,required:i.required,summary:i.summary,invocation:k})),s.add(`${n}:${i.kind}`);}for(let i of e.projectRoots){let g=Na({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await ca({workspacePath:e.workspacePath,action:g},e.dependencies);o.push(...n.adapters);let f=qa(e.workspacePath,i,e.proposal.changes);if(f){for(let m of n.checkpointFiles)r.add(m);t.push(...n.blockers);}let k=F(e.workspacePath,i);for(let m of n.stages)!f&&!["test","build"].includes(m.kind)||s.has(`${k}:${m.kind}`)||a.push(m);}return {stages:[...new Map(a.map(i=>[i.id,i])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(i=>[`${i.projectPath}:${i.adapterId}`,i])).values()]}}async function Oa(e$1,a$2={}){let r=c$1.resolve(e$1.workspacePath),t=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(l=>l.cardId===e$1.cardId).filter(l=>!e$1.projectName||l.projectName===e$1.projectName).sort((l,E)=>l.order-E.order||l.id.localeCompare(E.id)),s=e$1.actionId?o.filter(l=>l.id===e$1.actionId):o,d$1=t.actions.filter(l=>!e$1.projectName||!l.projectName||l.projectName===e$1.projectName).sort((l,E)=>l.order-E.order||l.id.localeCompare(E.id)),i=new Map(d$1.map(l=>[l.id,l])),g=l=>{let E=new Set(l.map(se=>se.id)),V=[...l];for(;V.length>0;){let se=V.pop();for(let K of se?.dependsOn??[]){let Y=i.get(K);!Y||E.has(Y.id)||(E.add(Y.id),V.push(Y));}}return d$1.filter(se=>E.has(se.id))},n=s.filter(l=>l.findingStatus==="blocking"||l.notes.includes("Doctor finding status: blocking")),f=n.length>0?n:s.filter(l=>l.findingStatus!=="advisory"&&l.findingStatus!=="informational"),k=e$1.actionId?s.filter(l=>l.id===e$1.actionId):[],m=f[0],x=m?f.filter(l=>l.cardId===m.cardId&&l.findingId===m.findingId):[],I=g(e$1.actionId?k:x),W=e$1.maxRisk??"guarded",w={maxRisk:W,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},p=[{id:"workspace-root",status:await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:I.length>0?"passed":"failed",message:I.length>0?`${I.length} governed action(s) selected.`:"No governed remediation action matches this target."}],P=sa(I);P&&p.push(P);let b=[],T=[],S=[],j=[],O=new Set(["manual-repair","cancel"]);for(let l of I){let E=ye(l),V=Sa(r,l);if(_[l.risk]<=_[W]||(j.push(`${l.id} exceeds the approved ${W} risk ceiling.`),O.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),(l.status==="blocked"||l.status==="guidance-only")&&j.push(`${l.id} is ${l.status}: ${l.blocker}`),!E&&!V&&j.push(`${l.id} has no typed operation or structured invocation.`),V)try{qe(r,V,w);}catch(K){let Y=K instanceof Error?K.message:String(K);j.push(Y),/Force-based/.test(Y)&&O.add("allow-force"),/Breaking dependency/.test(Y)&&O.add("allow-breaking");}if(b.push({id:`action:${l.id}`,kind:"repair",status:E||V?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,...V?{invocation:V}:{}}),l.transaction){let K=await ca({workspacePath:r,action:l},a$2);b.push(...K.stages),T.push(...K.checkpointFiles),j.push(...K.blockers),S.push(...K.adapters);}}let te=[...new Map(b.map(l=>[l.id,l])).values()];b.splice(0,b.length,...te),b.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),b.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),b.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),p.push(...await We({workspacePath:r,stages:b,toolAvailable:a$2.toolAvailable}));let M=await $a({workspacePath:r,actions:I,dependencyFiles:T}),B=await be(r,M);p.push({id:"rollback-coverage",status:I.some(l=>l.mode==="edit-file"||l.mode==="run-command")&&M.length===0?"failed":"passed",message:M.length>0?`${M.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),p.push({id:"structured-execution",status:b.some(l=>l.required&&l.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),p.push({id:"checkpoint-boundary",status:B.errors.length===0?"passed":"failed",message:B.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":B.errors.join(" ")});let J=$(Q(t)),re=[...new Set(I.map(l=>l.projectPath).filter(Boolean))],L={cardId:e$1.cardId,scope:e$1.projectName||re.length===1?"project":"workspace",...e$1.projectName?{projectName:e$1.projectName}:{},...re.length===1?{projectPath:re[0]}:{},actionIds:I.map(l=>l.id)},de=D(a$2.now),ee=`repair_${randomUUID().replaceAll("-","")}`,z=p.some(l=>l.status==="failed")||j.length>0,ge=[...j,...p.filter(l=>l.status==="failed").map(l=>l.message)],u=[...new Map(S.map(l=>[`${l.projectPath}:${l.adapterId}`,l])).values()],q=ra({actions:I,adapters:u,preconditions:p,stages:b,decisionOptions:O,maxRisk:W,fallbackReasons:ge}),G={schemaVersion:c,transactionId:ee,revision:1,createdAt:de,updatedAt:de,workspace:{name:t.workspace.name,rootRef:"."},target:L,state:z?"decision-required":"awaiting-approval",policy:w,approval:{required:true,status:"pending"},preconditions:p,adapterEvaluations:u,checkpoint:{status:M.length>0?"pending":"unavailable",files:B.entries},stages:b,...z?{decision:{reason:[...new Set(ge)].join(" "),options:[...O],causes:q}}:{},events:[],integrity:{sourceEvidenceHash:J,planHash:Te({sourceEvidenceHash:J,target:L,policy:w,preconditions:p,adapterEvaluations:u,stages:b,checkpointFiles:B.entries})}};A(G,"planned",z?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$2.now}),a(G,e,"Workspace repair transaction");let oe=ae(r,ee);return await h.ensureDir(oe),await Z(Se(r,ee),t),await Z(ve(r,ee),G),await Z(c$1.join(r,d),G),G}async function _a(e$1,a$2={}){a(e$1.proposal,g,"Workspace repair proposal");let r=c$1.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal)),o=e$1.maxRisk??"guarded",s={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d$1=[],i=[],g$1=new Set(["manual-repair","cancel"]),n=await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"));if(d$1.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."}),t.projectPath){t.projectPath=F(r,t.projectPath);let u=c$1.resolve(r,t.projectPath),q=await h.lstat(u).catch(()=>{});(!q?.isDirectory()||q.isSymbolicLink())&&i.push("The declared project path must be a real directory inside the workspace.");}t.validation=t.validation?.map(u=>({...u,cwd:F(r,u.cwd)}));let f=new Set,k=new Set,m=0;for(let u of t.changes){u.path=F(r,u.path),u.path==="."&&i.push(`${u.id} cannot replace the workspace root.`),f.has(u.id)&&i.push(`Duplicate proposal change id: ${u.id}.`),k.has(u.path)&&i.push(`Multiple proposal changes target ${u.path}.`),f.add(u.id),k.add(u.path),m+=Buffer.byteLength(u.content??"","utf8"),m>wa&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let q=pa(u.path);if(q&&i.push(`${u.path}: ${q}`),_[u.risk]>_[o]&&(i.push(`${u.id} exceeds the approved ${o} risk ceiling.`),g$1.add(u.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let G=c$1.resolve(r,t.projectPath),oe=c$1.resolve(r,u.path);C(G,oe)||i.push(`${u.path} escapes the declared project scope.`);}}let x=[...k].sort(),I=await be(r,x);i.push(...I.errors);let W=new Map(I.entries.map(u=>[u.path,u]));for(let u of t.changes){let q=W.get(u.path);if(!q||q.beforeHash!==u.expectedBeforeHash){i.push(`${u.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}u.operation==="delete"&&!q.existed&&i.push(`${u.path} cannot be deleted because it does not exist.`),u.operation==="write"&&q.beforeHash!==null&&$(u.content??"")===q.beforeHash&&i.push(`${u.path} is a no-op and cannot prove source progress.`);}d$1.push({id:"proposal-boundary",status:i.length===0?"passed":"failed",message:i.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(i)].join(" ")});let w=new Set;if(t.projectPath)w.add(c$1.resolve(r,t.projectPath));else for(let u of t.changes)w.add(await Ta(r,u.path));let p=await Fa({workspacePath:r,proposal:t,projectRoots:[...w].sort(),maxRisk:o,policy:s,dependencies:a$2});i.push(...p.blockers);let P=p.stages,b=P.some(u=>u.status!=="skipped"&&["audit","test","build"].includes(u.kind));d$1.push({id:"validation-coverage",status:b?"passed":"unknown",message:b?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let T=[...new Set([...x,...p.checkpointFiles])].sort(),S=await be(r,T);i.push(...S.errors),d$1.push({id:"checkpoint-boundary",status:S.errors.length===0?"passed":"failed",message:S.errors.length===0?`${S.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:S.errors.join(" ")});let j=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(u=>({id:`proposal:${u.id}`,kind:"repair",status:_[u.risk]<=_[o]?"pending":"blocked",required:true,risk:u.risk,summary:u.summary,changedPaths:[u.path]})),...P,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d$1.push(...await We({workspacePath:r,stages:j,toolAvailable:a$2.toolAvailable}));let O=new Set(j.map(u=>u.id));O.size!==j.length&&i.push("Repair proposal stage ids must be unique."),d$1.push({id:"stage-identity",status:O.size===j.length?"passed":"failed",message:O.size===j.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let u=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true});if(!t.targetActionIds?.length){let l=u.actions.filter(E=>E.cardId===t.cardId&&(!t.projectName||E.projectName===t.projectName)&&(!t.projectPath||E.projectPath===t.projectPath)).map(E=>E.id).sort();l.length>0&&(t.targetActionIds=l);}let q=new Set(t.targetActionIds??[]),G=u.actions.filter(l=>q.has(l.id)),oe=sa(G);oe&&d$1.push(oe);}catch{}let te=$(Q(t)),M={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(u=>`proposal:${u.id}`)},B=D(a$2.now),J=`repair_${randomUUID().replaceAll("-","")}`,L=d$1.some(u=>u.status==="failed")||i.length>0,de=[...i,...d$1.filter(u=>u.status==="failed").map(u=>u.message)],ee=ra({adapters:p.adapters,preconditions:d$1,stages:j,decisionOptions:g$1,maxRisk:o,fallbackReasons:de});for(let u of t.changes)_[u.risk]<=_[o]||ee.push({kind:"risk-approval",id:`risk:${u.id}`,message:`${u.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let z={schemaVersion:c,transactionId:J,revision:1,createdAt:B,updatedAt:B,workspace:{name:await Ca(r),rootRef:"."},target:M,state:L?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d$1,adapterEvaluations:p.adapters,checkpoint:{status:"pending",files:S.entries},stages:j,...L?{decision:{reason:[...new Set(de)].join(" "),options:[...g$1],causes:ee}}:{},events:[],integrity:{sourceEvidenceHash:te,planHash:Te({sourceEvidenceHash:te,target:M,policy:s,preconditions:d$1,adapterEvaluations:p.adapters,stages:j,checkpointFiles:S.entries})}};A(z,"planned",L?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a(z,e,"Workspace repair transaction");let ge=ae(r,J);return await h.ensureDir(ge),await Z(Se(r,J),t),await Z(ve(r,J),z),await Z(c$1.join(r,d),z),z}async function ht(e,a={}){let r=await ce(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(da(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=N("The compiled repair plan changed after planning.",["cancel"]),await R(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return $(Q(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=N("The persisted source plan changed after planning.",["cancel"]),await R(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:D(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",A(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await R(e.workspacePath,r,a.now),r)}async function la(e,a){let r=c$1.join(e,$e,ka);await h.ensureDir(c$1.dirname(r));try{let t=await h.stat(r),o=await h.readJson(r).catch(()=>({})),s=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,i=false;if((!s||s===hostname())&&d)try{process.kill(d,0),i=true;}catch(n){i=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let g=!!(s&&s!==hostname());!i&&!g&&Date.now()-t.mtimeMs>ba&&await h.remove(r);}catch{}try{await h.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
2
- `,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await h.readJson(r).catch(async()=>{let o=await h.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await h.remove(r);}}async function ua(e){let a=await be(e.workspacePath,e.transaction.checkpoint.files.map(t=>t.path));if(a.errors.length>0)throw new Error(a.errors.join(" "));let r=new Map(a.entries.map(t=>[t.path,t]));for(let t of e.transaction.checkpoint.files){let o=r.get(t.path);if(!o||t.existed!==o.existed||t.beforeHash!==o.beforeHash||t.mode!==o.mode)throw new Error(`Checkpoint precondition changed after planning: ${t.path}. Create and approve a fresh plan.`)}}async function Ma(e){if(e.transaction.checkpoint.status==="captured")return;await ua(e);let a=c$1.join(ae(e.workspacePath,e.transaction.transactionId),Ue);await h.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=c$1.resolve(e.workspacePath,t.path),s=t.existed?await h.readFile(o):void 0;if(s&&$(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${Ue}/${String(r).padStart(4,"0")}.bin`;if(s){let i=c$1.join(ae(e.workspacePath,e.transaction.transactionId),d),g=`${i}.${process.pid}.${randomUUID()}.tmp`;await h.writeFile(g,s,{flag:"wx"});let n=await h.readFile(g);if($(n)!==t.beforeHash)throw await h.remove(g),new Error(`Checkpoint backup verification failed for ${t.path}.`);await h.move(g,i,{overwrite:true}),t.backupRef=d;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=D(e.now),e.transaction.state="checkpointed",A(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function Ze(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),o=await h.readFile(t).catch(()=>{});r.afterHash=o?$(o):null;}}function Pe(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function qe(e,a,r){let t=c$1.resolve(e,a.cwd);if(!C(e,t))throw new Error(`Invocation cwd escapes workspace: ${a.cwd}`);if(a.args.length>100||a.args.some(i=>!i||/[\0\r\n]/.test(i)))throw new Error("Invocation contains invalid arguments.");let o=Pe(a.executable),s=c$1.isAbsolute(a.executable),d=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!C(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!s&&!d&&!Pa.has(o))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(i=>/^(?:--force|-f)$/i.test(i)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(i=>/(?:breaking|legacy-peer-deps)/i.test(i)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(o)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${o} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:t,executable:a.executable}}async function Ee(e){let a=qe(e.workspacePath,e.invocation,e.policy),r=await h.lstat(a.cwd).catch(()=>{});if(!r?.isDirectory()||r.isSymbolicLink()||!await H(e.workspacePath,a.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(a.executable)||/^\.{1,2}[\\/]/.test(a.executable)){let s=c$1.isAbsolute(a.executable)?a.executable:c$1.resolve(a.cwd,a.executable);if(!await H(e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let t=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),o=await execa(a.executable,e.invocation.args,{cwd:a.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ta,stdin:"ignore",extendEnv:false,env:{...t,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:o.exitCode??null,stdout:o.stdout??"",stderr:o.stderr??""}}function Ha(e){let a=b.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function Ba(e){let a=b.find(d=>d.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await h.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);if(!await H(e.workspacePath,t))throw new Error("The target producer working directory escapes the workspace boundary.");let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(process.execPath,[r,...Ha(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:ta,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}async function La(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=we(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=we(e.sourcePlan)?a.actions.filter(s=>t?r.has(s.id):s.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||s.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||s.projectPath===e.transaction.target.projectPath)):a.actions.filter(s=>r.has(s.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function Va(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(g=>!g.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(g=>g.id)),o=a.filter(g=>!t.has(g)),s=e.transaction.preconditions.map(g=>g.id).find(g=>g.startsWith(Ae))?.slice(Ae.length),d=r.actions.filter(g=>t.has(g.id)&&a.includes(g.id)),i=o.length===0&&!!s&&oa(d)!==s;return {current:o.length===0&&!i,missingActionIds:o,semanticDrift:i}}function U(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
- ${e.slice(-a)}`}async function Ka(e,a){if(a.type==="file-create")return i$1({projectPath:e,operation:a});if(a.type==="file-append")return j$1({projectPath:e,operation:a});if(a.type==="file-copy")return k({projectPath:e,operation:a});if(a.type==="package-json-script")return h$2({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m({projectPath:e,operation:a});if(a.type==="env-key-add")return n({projectPath:e,operation:a});if(a.type==="makefile-target")return o({projectPath:e,operation:a})}async function Ja(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!C(e.workspacePath,a)||!await H(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let r=pa(e.change.path);if(r)throw new Error(`${e.change.path}: ${r}`);let t=e.transaction.checkpoint.files.find(f=>f.path===e.change.path);if(!t)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let o=await h.readFile(a).catch(()=>{}),s=o?$(o):null;if(s!==t.beforeHash||s!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let d=await h.lstat(a).catch(()=>{});if(d?.isSymbolicLink()||d&&!d.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!d)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await h.remove(a);return}let i=e.change.content??"";if(Buffer.byteLength(i,"utf8")>aa)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await h.ensureDir(c$1.dirname(a));let g=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await h.writeFile(g,i,{encoding:"utf8",flag:"wx"}),await h.move(g,a,{overwrite:true});let n=await h.readFile(a);if($(n)!==$(i))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function Qe(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=D(e.dependencies.now),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):Ba))({workspacePath:e.workspacePath,transaction:e.transaction});if(e.stage.exitCode=r.exitCode,e.stage.stdoutTail=U(r.stdout),e.stage.stderrTail=U(r.stderr),r.exitCode!==0&&r.exitCode!==2)throw new Error(r.stderr||r.stdout||`Exact card producer exited with ${String(r.exitCode)}.`);if(e.stage.id==="target-precondition"){let t=await Va({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!t.current){let o=t.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${t.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${o} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await Ja({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=ye(a.action);if(r){let t=he(e.workspacePath,a.action);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);await Ka(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Ee)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=U(t.stdout),e.stage.stderrTail=U(t.stderr),t.exitCode!==0)throw new Error(t.stderr||t.stdout||`Repair command exited with ${t.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??Ee)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=U(a.stdout),e.stage.stderrTail=U(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=D(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await Ze(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=D(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await Ze(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ue(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",A(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let r=async s=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=N(s,["manual-repair","cancel"]),A(e.transaction,"decision",s,{status:"conflicted",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let s of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,s.path);if(!C(e.workspacePath,d)||!await H(e.workspacePath,d))return r(`Rollback refused because ${s.path} escaped the workspace boundary.`);let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()||i&&!i.isFile())return r(`Rollback refused because ${s.path} is no longer a regular file.`);let g=i?await h.readFile(d):void 0,n=g?$(g):null,f=s.afterHash!==void 0&&n===s.afterHash,k=a&&n===s.beforeHash;if(!f&&!k)return r(`Rollback refused because ${s.path} changed outside this transaction.`);if(!s.existed){t.push({entry:s,absolute:d});continue}if(!s.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${s.path}.`);let m=c$1.join(ae(e.workspacePath,e.transaction.transactionId),s.backupRef),x=await h.lstat(m).catch(()=>{});if(!x?.isFile()||x.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${s.path}.`);let I=await h.readFile(m);if($(I)!==s.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${s.path}.`);t.push({entry:s,absolute:d,backup:I});}for(let s of t){if(!s.entry.existed){await h.remove(s.absolute);continue}let d=s.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${s.entry.path}.`);let i=c$1.join(c$1.dirname(s.absolute),`.${c$1.basename(s.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await h.ensureDir(c$1.dirname(s.absolute)),await h.writeFile(i,d,{flag:"wx"}),s.entry.mode!==void 0&&await h.chmod(i,s.entry.mode),await h.move(i,s.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=D(e.dependencies.now);let o=e.transaction.stages.filter(s=>s.kind==="reconcile"&&s.invocation);for(let s of o){let d=s.invocation;if(!d)continue;let i=`rollback:${s.id}`,g=e.transaction.stages.find(k=>k.id===i&&k.kind==="rollback"),n=g??{id:i,kind:"rollback",status:"pending",required:true,risk:s.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};g||e.transaction.stages.push(n),n.status="running",n.startedAt=D(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,A(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let f;try{f=await(e.dependencies.runInvocation??Ee)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy});}catch(k){f={exitCode:null,stdout:"",stderr:k instanceof Error?k.message:String(k)};}if(n.exitCode=f.exitCode,n.stdoutTail=U(f.stdout),n.stderrTail=U(f.stderr),n.completedAt=D(e.dependencies.now),f.exitCode!==0)return n.status="failed",n.summary=f.stderr||f.stdout||`Rollback reconciliation exited with ${f.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=N(`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,["manual-repair","cancel"]),A(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",A(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,A(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}async function gt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await la(r,e.transactionId);try{let o=await ce({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(da(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=N("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,o,a.now),o;let s=await Ce(r,e.transactionId);if($(Q(s))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=N("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,o,a.now),o;let i=(await We({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(w=>w.status==="failed");if(i){let w=o.stages.find(p=>p.invocation&&`tool:${p.invocation.cwd}:${p.invocation.executable}`===i.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=N(`${i.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:i.id,message:i.message,...w?{executable:w}:{}}),A(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await R(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await ue({workspacePath:r,transaction:o,dependencies:a}),o}let g=new Map(we(s)?s.changes.map(w=>[`proposal:${w.id}`,{kind:"proposal",change:w}]):s.actions.map(w=>[`action:${w.id}`,{kind:"canonical",action:w}]));try{await ua({workspacePath:r,transaction:o});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision=N(w instanceof Error?w.message:String(w),["cancel"]),A(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await R(r,o,a.now),o}let n=o.stages.find(w=>w.id==="target-precondition");if(!n)return o.approval.status="expired",o.state="decision-required",o.decision=N("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await R(r,o,a.now),o;if(!await Qe({workspacePath:r,transaction:o,stage:n,actions:g,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=N(`Target precondition failed before checkpoint: ${n.summary}`,["cancel"]),A(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await R(r,o,a.now),o;try{await Ma({workspacePath:r,transaction:o,now:a.now});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision=N(w instanceof Error?w.message:String(w),["cancel"]),A(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await R(r,o,a.now),o}o.state="executing",await R(r,o,a.now);for(let w of o.stages.filter(p=>p.id!=="target-precondition"&&p.id!=="canonical-verify"&&p.kind!=="rollback"))if(!await Qe({workspacePath:r,transaction:o,stage:w,actions:g,dependencies:a})&&w.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N(`Required stage ${w.id} failed: ${w.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(w=>w.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=D(a.now),A(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await R(r,o,a.now);let m;try{m=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(w){m={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},k.stderrTail=U(w instanceof Error?w.message:String(w));}let x=m.status==="passed"&&m.exitCode===0?"passed":m.status==="failed"||m.exitCode===1?"failed":"blocked",I=await La({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:x}),W=I.status==="passed"&&x!=="failed";return k.status=W?"passed":"failed",k.completedAt=D(a.now),k.exitCode=m.exitCode,k.summary=W&&x==="passed"?"Selected repair target and canonical workspace verification passed.":W?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":I.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${x}.`,o.verification={status:W?"passed":"failed",targetStatus:I.status,workspaceStatus:x,remainingActionIds:I.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:m.exitCode,summary:k.summary},A(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),W?(o.state="closed",delete o.decision,A(o,"closed",k.summary,{status:"passed",now:a.now}),await R(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function za(e,a={}){let r=c$1.resolve(e.workspacePath),t=await la(r,e.transactionId);try{let o=await ce({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await ue({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ft(e,a={}){let r=await ce(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,A(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await R(e.workspacePath,r,a.now),r}async function kt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ce({workspacePath:r,transactionId:e.transactionId});if(t.state!=="decision-required"||!t.decision)throw new Error(`Repair transaction is not awaiting a decision: ${t.state}`);if(!t.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${t.decision.options.join(", ")}.`);if(e.decision==="rollback")return za({workspacePath:r,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(t.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,A(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await R(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Ce(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,A(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await R(r,t,a.now);let s={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(we(o))return _a({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return Oa({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function mt(e){let a=c$1.join(e,$e,"transactions"),r=await h.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>ce({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}export{ht as approveWorkspaceRepair,ft as cancelWorkspaceRepair,kt as decideWorkspaceRepair,Ha as exactCardProducerArgs,gt as executeWorkspaceRepair,ut as inspectWorkspaceRepairCapabilities,mt as listWorkspaceRepairTransactions,Oa as planWorkspaceRepair,_a as planWorkspaceRepairProposal,ce as readWorkspaceRepairTransaction,za as rollbackWorkspaceRepair};
@@ -1 +0,0 @@
1
- export{a as runWorkspaceStage}from'./chunk-GTJY55QK.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-IZLEMTES.js';