workspai 0.56.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 (144) hide show
  1. package/README.md +38 -8
  2. package/contracts/adopt-effects.v1.json +72 -0
  3. package/contracts/agent-customization-pack.v1.json +10 -0
  4. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +81 -0
  5. package/contracts/doctor-project-evidence.v1.json +27 -0
  6. package/contracts/doctor-workspace-evidence.v1.json +29 -0
  7. package/contracts/extension-cli-compatibility.v1.json +6 -0
  8. package/contracts/published-contract-catalog.v1.json +30 -0
  9. package/contracts/runtime-command-surface.v1.json +45 -0
  10. package/contracts/workspace-intelligence/doctor-summary.v1.json +3 -1
  11. package/contracts/workspace-intelligence/goal-agent-handoff.v1.json +96 -0
  12. package/contracts/workspace-intelligence/goal-index.v1.json +45 -0
  13. package/contracts/workspace-intelligence/goal-lifecycle-result.v1.json +96 -0
  14. package/contracts/workspace-intelligence/goal-pack.v1.json +250 -0
  15. package/contracts/workspace-intelligence/goal-plan-result.v1.json +46 -0
  16. package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +1 -0
  17. package/contracts/workspace-intelligence-architecture.v1.json +20 -0
  18. package/dist/analyze-MAU36FTX.js +1 -0
  19. package/dist/{artifact-remediation-plan-BPLON5VX.js → artifact-remediation-plan-JRX4XZ7C.js} +1 -1
  20. package/dist/autopilot-release-TA2L7SCB.js +1 -0
  21. package/dist/capabilities-command-HE2FICLG.js +1 -0
  22. package/dist/chunk-42Q5E2YV.js +1 -0
  23. package/dist/{workspace-knowledge-graph-snapshot-WB62AVDK.js → chunk-4NN5QWOB.js} +1 -1
  24. package/dist/chunk-4YICCES6.js +8 -0
  25. package/dist/{chunk-HASVV34S.js → chunk-6TNSCVR4.js} +1 -1
  26. package/dist/{chunk-PKIRVQLG.js → chunk-7IRGSM25.js} +1 -1
  27. package/dist/{chunk-NHTLE3WN.js → chunk-7KXRA5ST.js} +1 -1
  28. package/dist/{chunk-5RL254O2.js → chunk-7WUT5ZSO.js} +1 -1
  29. package/dist/{chunk-ESWFBSYM.js → chunk-A3JCETSF.js} +1 -1
  30. package/dist/{chunk-KR7CIEQR.js → chunk-AA4PNQKR.js} +1 -1
  31. package/dist/{chunk-5ZA4JYOP.js → chunk-AUCHMXUZ.js} +1 -1
  32. package/dist/{chunk-2L4PSZQB.js → chunk-C4NYG57I.js} +1 -1
  33. package/dist/{chunk-QFCKHUEP.js → chunk-CFBAGPB4.js} +1 -1
  34. package/dist/{chunk-WLCBXCZV.js → chunk-CHMCKYJJ.js} +1 -1
  35. package/dist/chunk-CNWUIXF3.js +1 -0
  36. package/dist/chunk-EEMRRCGR.js +2 -0
  37. package/dist/{chunk-QTCZPS5I.js → chunk-FXIE2WVG.js} +1 -1
  38. package/dist/{chunk-YJTEMJFV.js → chunk-FY6OHOXR.js} +1 -1
  39. package/dist/{chunk-W5ZFXKSL.js → chunk-G4VMNWSU.js} +1 -1
  40. package/dist/{chunk-ADL3CK44.js → chunk-GRGUPSNP.js} +1 -1
  41. package/dist/{chunk-XH7PDHBF.js → chunk-GVS5OFUB.js} +1 -1
  42. package/dist/{chunk-E53BGUOW.js → chunk-H545P6LN.js} +1 -1
  43. package/dist/chunk-HH54C3XJ.js +1 -0
  44. package/dist/{chunk-XMTLKDPP.js → chunk-HI7ONEFI.js} +1 -1
  45. package/dist/chunk-HYY5PQCV.js +1 -0
  46. package/dist/chunk-I5PDN2P2.js +13 -0
  47. package/dist/{chunk-V5EYVQ63.js → chunk-II4ROT6X.js} +1 -1
  48. package/dist/{chunk-GBMCHFOV.js → chunk-LGJAAPNR.js} +1 -1
  49. package/dist/{chunk-UQEQ6CXU.js → chunk-M2BK3XTP.js} +1 -1
  50. package/dist/{chunk-7PNARN6S.js → chunk-MFJ6ZP7S.js} +1 -1
  51. package/dist/{chunk-64JUYYRC.js → chunk-N3DFX4BY.js} +1 -1
  52. package/dist/chunk-NQ5H4R2I.js +83 -0
  53. package/dist/chunk-PCXBPQO6.js +1 -0
  54. package/dist/chunk-QXW3SLEX.js +1 -0
  55. package/dist/{chunk-KS4FB5W7.js → chunk-RJDGC6AQ.js} +1 -1
  56. package/dist/{chunk-ZPA6ECBJ.js → chunk-RMDVRNU7.js} +1 -1
  57. package/dist/chunk-SM55RK3C.js +91 -0
  58. package/dist/{chunk-LYVDRRDO.js → chunk-T63WRURN.js} +1 -1
  59. package/dist/{chunk-WOTTSPSF.js → chunk-TMOKXYAQ.js} +1 -1
  60. package/dist/{chunk-6HCAGHCY.js → chunk-TTLVG5AR.js} +1 -1
  61. package/dist/{chunk-5BGPGNRQ.js → chunk-VAWV3UKV.js} +1 -1
  62. package/dist/chunk-VIFTO53Y.js +1 -0
  63. package/dist/chunk-WP3CXMVA.js +2 -0
  64. package/dist/{chunk-IZLEMTES.js → chunk-WSDVFLHT.js} +1 -1
  65. package/dist/{chunk-SV2SP22H.js → chunk-XC26FNRL.js} +3 -3
  66. package/dist/chunk-YMY6EFX4.js +1 -0
  67. package/dist/{chunk-YM77FQB3.js → chunk-YYCPRYP7.js} +1 -1
  68. package/dist/{chunk-QAF26ZQX.js → chunk-ZDYGO3T7.js} +17 -17
  69. package/dist/{create-DLUWG46F.js → create-QIN56Y4M.js} +1 -1
  70. package/dist/{doctor-IZ4YOCYE.js → doctor-RP4Q2CKJ.js} +1 -1
  71. package/dist/goal-command-contract-CHE7U6YY.js +1 -0
  72. package/dist/goal-lifecycle-YTBU3ICP.js +1 -0
  73. package/dist/goal-pack-MYYH7K43.js +1 -0
  74. package/dist/index.d.ts +21 -2
  75. package/dist/index.js +168 -166
  76. package/dist/{pipeline-IBQYDLFF.js → pipeline-77NUVYQD.js} +1 -1
  77. package/dist/{project-intelligence-lens-SIU7IXKG.js → project-intelligence-lens-AM2B2PXU.js} +1 -1
  78. package/dist/project-test-coverage-MUSS7Z7V.js +1 -0
  79. package/dist/{verified-goal-M4GPOXNL.js → verified-goal-ZSIZYNVO.js} +1 -1
  80. package/dist/{workspace-3AAOUELG.js → workspace-LFESVKE7.js} +1 -1
  81. package/dist/{workspace-agent-sync-QGYLY7HH.js → workspace-agent-sync-JMRX6J2Y.js} +1 -1
  82. package/dist/{workspace-archive-BA3ONVXX.js → workspace-archive-MFHCFCDO.js} +1 -1
  83. package/dist/{workspace-context-JCLPRYNC.js → workspace-context-TBKRMVMT.js} +1 -1
  84. package/dist/{workspace-contract-IUUPBQXU.js → workspace-contract-KKVC2DUQ.js} +1 -1
  85. package/dist/workspace-explain-RGGZL5IW.js +1 -0
  86. package/dist/workspace-explain-contract-4ZZ6CJ44.js +1 -0
  87. package/dist/{workspace-feedback-PCZKXG5R.js → workspace-feedback-O6J3RQML.js} +1 -1
  88. package/dist/{workspace-foundation-7IGMO4CW.js → workspace-foundation-JQWT7YGC.js} +1 -1
  89. package/dist/{workspace-graph-stream-5YMLJXAJ.js → workspace-graph-stream-V5WOXP4B.js} +1 -1
  90. package/dist/workspace-graph-token-efficiency-TF23UYEF.js +1 -0
  91. package/dist/{workspace-history-CHJOABME.js → workspace-history-TOCRMJUJ.js} +1 -1
  92. package/dist/{workspace-intelligence-XHSUFTAT.js → workspace-intelligence-SDBIRKMK.js} +1 -1
  93. package/dist/{workspace-intelligence-evaluation-YMY3C5AW.js → workspace-intelligence-evaluation-E4UMWDAZ.js} +1 -1
  94. package/dist/{workspace-intelligence-runner-EN5V4KSC.js → workspace-intelligence-runner-DIMNL6CJ.js} +1 -1
  95. package/dist/{workspace-intelligence-runtime-registry-NCVHKCMP.js → workspace-intelligence-runtime-registry-YGWB2RRS.js} +1 -1
  96. package/dist/{workspace-knowledge-graph-VWQTIEYK.js → workspace-knowledge-graph-MUW6UAGI.js} +1 -1
  97. package/dist/{workspace-knowledge-graph-query-TXA3KVUV.js → workspace-knowledge-graph-query-6DAOXGGT.js} +1 -1
  98. package/dist/workspace-knowledge-graph-snapshot-7IU2QAXI.js +1 -0
  99. package/dist/{workspace-mcp-serve-NCAGGWQS.js → workspace-mcp-serve-2SWLIH4I.js} +1 -1
  100. package/dist/{workspace-model-NXFIKX26.js → workspace-model-VPFCKTYQ.js} +1 -1
  101. package/dist/{workspace-onboarding-OP22NHQ4.js → workspace-onboarding-GHI6UTQJ.js} +1 -1
  102. package/dist/{workspace-readme-IVJXSIBS.js → workspace-readme-RASXBZRQ.js} +1 -1
  103. package/dist/{workspace-registry-summary-A5VDPRHU.js → workspace-registry-summary-7QT7YMIU.js} +1 -1
  104. package/dist/workspace-repair-engine-AZTJIFCY.js +3 -0
  105. package/dist/workspace-run-VMZY6LIF.js +1 -0
  106. package/dist/{workspace-verify-TUVLFPPN.js → workspace-verify-RYCQZYYB.js} +1 -1
  107. package/dist/{workspace-watch-2ZNOYSUQ.js → workspace-watch-U3YGN3GG.js} +1 -1
  108. package/docs/From Code to Shared Understanding-B.png +0 -0
  109. package/docs/From Code to Shared Understanding.png +0 -0
  110. package/docs/README.md +2 -0
  111. package/docs/README_CONTENT_CONTRACT.md +25 -12
  112. package/docs/ci-workflows.md +9 -1
  113. package/docs/commands-reference.md +13 -1
  114. package/docs/contracts/ARTIFACT_CATALOG.md +11 -0
  115. package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +1 -0
  116. package/docs/contracts/README.md +16 -12
  117. package/docs/doctor-command.md +35 -11
  118. package/docs/from-code-to-shared-understanding.md +22 -17
  119. package/docs/goal-packs.md +174 -0
  120. package/docs/real-world-qualification.md +92 -0
  121. package/docs/workspace-knowledge-graph.md +24 -3
  122. package/docs/workspace-operations.md +14 -2
  123. package/docs/workspace-run.md +16 -4
  124. package/package.json +5 -1
  125. package/dist/analyze-HJ774J3E.js +0 -1
  126. package/dist/autopilot-release-CH57CGET.js +0 -1
  127. package/dist/capabilities-command-WEOGFCWF.js +0 -1
  128. package/dist/chunk-3U4VLIGW.js +0 -1
  129. package/dist/chunk-5EPPPMAS.js +0 -1
  130. package/dist/chunk-664GXRLD.js +0 -1
  131. package/dist/chunk-7Y3KVZJF.js +0 -8
  132. package/dist/chunk-BDN32Y2N.js +0 -81
  133. package/dist/chunk-D4RST2HE.js +0 -1
  134. package/dist/chunk-DIZSHNZ5.js +0 -2
  135. package/dist/chunk-DOIZANFA.js +0 -2
  136. package/dist/chunk-OX53L237.js +0 -13
  137. package/dist/chunk-QRWWYL52.js +0 -88
  138. package/dist/chunk-VGJVIHHR.js +0 -1
  139. package/dist/project-test-coverage-FRMVYTFB.js +0 -1
  140. package/dist/workspace-explain-CZGBVDE6.js +0 -1
  141. package/dist/workspace-explain-contract-KVQO57RC.js +0 -1
  142. package/dist/workspace-graph-token-efficiency-HK4KNWWP.js +0 -1
  143. package/dist/workspace-repair-engine-N4KXNSVL.js +0 -3
  144. package/dist/workspace-run-PXKC3ELS.js +0 -1
@@ -0,0 +1,3 @@
1
+ import {a as a$1}from'./chunk-FY6OHOXR.js';import {b,f}from'./chunk-QXW3SLEX.js';import {c as c$2}from'./chunk-YMY6EFX4.js';import {d as d$1,i as i$1,j as j$1,k,h as h$2,m,n,o}from'./chunk-SM55RK3C.js';import {c,e,j,d,g,b as b$1,i,f as f$1}from'./chunk-7IRGSM25.js';import {a as a$2}from'./chunk-AO2ZI42U.js';import {h as h$1}from'./chunk-NQ5H4R2I.js';import {a}from'./chunk-AFIFZTOY.js';import {e as e$1}from'./chunk-HH54C3XJ.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",ka="transaction.json",ma="source-plan.json",Xe="checkpoint",wa="engine.lock",ra=5*1024*1024,ba=25*1024*1024,va=25*1024*1024,oa=4*1024*1024,ya=900*1e3,Pa=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"]),Ra=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},xa=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 ja(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:${S(e).slice(0,16)}`,message:r.message??e}]}}function sa(e){let a=new Map,r=t=>a.set(ja(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:${S(t).slice(0,16)}`,message:t});}return [...a.values()]}function D(e){return (e?.()??new Date).toISOString()}function S(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 ia(e){return S(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 na(e){if(e.length===0)return;let a=ia(e);return {id:`${Ae}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function W(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 W(r,o)}function F(e,a){let r=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!W(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),ka)}function Se(e,a){return c$1.join(ae(e,a),ma)}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$1}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(!W(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 Ia(e){return h.readJson(e).catch(()=>({}))}function Ze(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function Aa(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 Qe(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ca(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 Qe(o)}for(let t of Aa(r)){let o=await h.stat(t).catch(()=>{});if(Qe(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 ca({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 Ea(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 $a(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=Ea(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 Ia(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",q=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",q]),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 C=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??C})),n(typeof P.test=="string"&&P.test.trim()?y({id:i$1("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Ze({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:Ze({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"),q=!b&&(P==="poetry"||p==="poetry"||await t("poetry.lock")),C=!b&&!q&&["python","python3","py"].includes(P)&&(e.action.invocation?.args??[]).some(V=>V==="venv")&&(e.action.invocation?.args??[]).some(V=>V===".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)||C)&&(j=O);let te=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):q?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&W(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&W(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),L=v(q?{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(q?{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:L}):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)),q=p.manifest==="composer.json"||p.adapterId==="deno"?/["']test["']\s*:/.test(b):p.manifest==="Gemfile"?await t("Rakefile"):true,C=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(q?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(C?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 T=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&T){let p=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g([T,"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 q=!p||/:test\b/.test(P);return n(q?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 da(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 Sa(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 pa(e,a={}){let r=he(e.workspacePath,e.action),t=F(e.workspacePath,r),o=await da(r),s=Sa(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 $a({...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 ca({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 ft(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=W(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??"."),!W(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=F(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await da(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 Ca(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 Wa(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 S(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 la(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(!W(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>ra){t.push(`Checkpoint file exceeds 5 MiB: ${s}`);continue}if(o+=i?.size??0,o>ba){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?S(g):null,...i?{mode:i.mode}:{}});}return {entries:r,errors:t}}function ua(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 Ta(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 qa(e){return Pa.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Na(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;W(e,t);){if((await h.readdir(t).catch(()=>[])).some(qa))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function Da(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!W(a,o))return false;let s=c$1.basename(o);return Ra.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function Fa(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 Oa(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 _a(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&&!W(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),Oa(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=Fa({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await pa({workspacePath:e.workspacePath,action:g},e.dependencies);o.push(...n.adapters);let f=Da(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 Ma(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,$)=>l.order-$.order||l.id.localeCompare($.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,$)=>l.order-$.order||l.id.localeCompare($.id)),i=new Map(d$1.map(l=>[l.id,l])),g=l=>{let $=new Set(l.map(se=>se.id)),K=[...l];for(;K.length>0;){let se=K.pop();for(let G of se?.dependsOn??[]){let Y=i.get(G);!Y||$.has(Y.id)||($.add(Y.id),K.push(Y));}}return d$1.filter(se=>$.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),T=e$1.maxRisk??"guarded",w={maxRisk:T,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=na(I);P&&p.push(P);let b=[],q=[],C=[],j=[],O=new Set(["manual-repair","cancel"]);for(let l of I){let $=ye(l),K=Wa(r,l);if(_[l.risk]<=_[T]||(j.push(`${l.id} exceeds the approved ${T} 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}`),!$&&!K&&j.push(`${l.id} has no typed operation or structured invocation.`),K)try{qe(r,K,w);}catch(G){let Y=G instanceof Error?G.message:String(G);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:$||K?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,...K?{invocation:K}:{}}),l.transaction){let G=await pa({workspacePath:r,action:l},a$2);b.push(...G.stages),q.push(...G.checkpointFiles),j.push(...G.blockers),C.push(...G.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 Ca({workspacePath:r,actions:I,dependencyFiles:q}),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 L=S(Q(t)),re=[...new Set(I.map(l=>l.projectPath).filter(Boolean))],V={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("-","")}`,J=p.some(l=>l.status==="failed")||j.length>0,ge=[...j,...p.filter(l=>l.status==="failed").map(l=>l.message)],u=[...new Map(C.map(l=>[`${l.projectPath}:${l.adapterId}`,l])).values()],E=sa({actions:I,adapters:u,preconditions:p,stages:b,decisionOptions:O,maxRisk:T,fallbackReasons:ge}),z={schemaVersion:c,transactionId:ee,revision:1,createdAt:de,updatedAt:de,workspace:{name:t.workspace.name,rootRef:"."},target:V,state:J?"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,...J?{decision:{reason:[...new Set(ge)].join(" "),options:[...O],causes:E}}:{},events:[],integrity:{sourceEvidenceHash:L,planHash:Te({sourceEvidenceHash:L,target:V,policy:w,preconditions:p,adapterEvaluations:u,stages:b,checkpointFiles:B.entries})}};A(z,"planned",J?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$2.now}),a(z,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),z),await Z(c$1.join(r,d),z),z}async function Ha(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));if(t.goalId){let u=await b({workspacePath:r,goalId:t.goalId});if(!u.active||u.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(u.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${u.goalPack?.state??"missing"}`);if(u.goalPack.scope.kind==="project"){let E=u.goalPack.scope.projects[0];if(!t.projectName||t.projectName!==E)throw new Error(`Goal-bound repair must declare the exact permitted projectName (${E}).`)}}let 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),E=await h.lstat(u).catch(()=>{});(!E?.isDirectory()||E.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$1=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$1.has(u.id)&&i.push(`Duplicate proposal change id: ${u.id}.`),k.has(u.path)&&i.push(`Multiple proposal changes target ${u.path}.`),f$1.add(u.id),k.add(u.path),m+=Buffer.byteLength(u.content??"","utf8"),m>va&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let E=ua(u.path);if(E&&i.push(`${u.path}: ${E}`),_[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 z=c$1.resolve(r,t.projectPath),oe=c$1.resolve(r,u.path);W(z,oe)||i.push(`${u.path} escapes the declared project scope.`);}}let x=[...k].sort(),I=await be(r,x);i.push(...I.errors);let T=new Map(I.entries.map(u=>[u.path,u]));for(let u of t.changes){let E=T.get(u.path);if(!E||E.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"&&!E.existed&&i.push(`${u.path} cannot be deleted because it does not exist.`),u.operation==="write"&&E.beforeHash!==null&&S(u.content??"")===E.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 Na(r,u.path));let p=await _a({workspacePath:r,proposal:t,projectRoots:[...w].sort(),maxRisk:o,policy:s,dependencies:a$2});i.push(...p.blockers);let P=p.stages,b$1=P.some(u=>u.status!=="skipped"&&["audit","test","build"].includes(u.kind));d$1.push({id:"validation-coverage",status:b$1?"passed":"unknown",message:b$1?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let q=[...new Set([...x,...p.checkpointFiles])].sort(),C=await be(r,q);i.push(...C.errors),d$1.push({id:"checkpoint-boundary",status:C.errors.length===0?"passed":"failed",message:C.errors.length===0?`${C.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:C.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($=>$.cardId===t.cardId&&(!t.projectName||$.projectName===t.projectName)&&(!t.projectPath||$.projectPath===t.projectPath)).map($=>$.id).sort();l.length>0&&(t.targetActionIds=l);}let E=new Set(t.targetActionIds??[]),z=u.actions.filter(l=>E.has(l.id)),oe=na(z);oe&&d$1.push(oe);}catch{}let te=S(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),L=`repair_${randomUUID().replaceAll("-","")}`,V=d$1.some(u=>u.status==="failed")||i.length>0,de=[...i,...d$1.filter(u=>u.status==="failed").map(u=>u.message)],ee=sa({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 J={schemaVersion:c,transactionId:L,revision:1,createdAt:B,updatedAt:B,workspace:{name:await Ta(r),rootRef:"."},target:M,state:V?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d$1,adapterEvaluations:p.adapters,checkpoint:{status:"pending",files:C.entries},stages:j,...V?{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:C.entries})}};A(J,"planned",V?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a(J,e,"Workspace repair transaction");let ge=ae(r,L);return await h.ensureDir(ge),await Z(Se(r,L),t),await Z(ve(r,L),J),await Z(c$1.join(r,d),J),t.goalId&&await f({workspacePath:r,goalId:t.goalId,transactionId:L}),J}async function kt(e,a={}){let r=await ce(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(la(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 S(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 ha(e,a){let r=c$1.join(e,$e,wa);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>ya&&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 ga(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 Ba(e){if(e.transaction.checkpoint.status==="captured")return;await ga(e);let a=c$1.join(ae(e.workspacePath,e.transaction.transactionId),Xe);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(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${Xe}/${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(S(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 ea(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?S(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(!W(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&&!W(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!s&&!d&&!xa.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:oa,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 La(e){let a=b$1.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 Va(e){let a=b$1.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,...La(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:oa,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 Ka(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 Ga(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&&ia(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 Ja(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 za(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!W(e.workspacePath,a)||!await H(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let r=ua(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?S(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")>ra)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(S(n)!==S(i))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function aa(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:""}):Va))({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 Ga({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 za({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 Ja(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 ea(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 ea(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(!W(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?S(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(S(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 mt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ha(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(la(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(S(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 ga({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 aa({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 Ba({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 aa({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 Ka({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:x}),T=I.status==="passed"&&x!=="failed";return k.status=T?"passed":"failed",k.completedAt=D(a.now),k.exitCode=m.exitCode,k.summary=T&&x==="passed"?"Selected repair target and canonical workspace verification passed.":T?"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:T?"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}),T?(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 Ua(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ha(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 wt(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 bt(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 Ua({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 Ha({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return Ma({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function vt(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{kt as approveWorkspaceRepair,wt as cancelWorkspaceRepair,bt as decideWorkspaceRepair,La as exactCardProducerArgs,mt as executeWorkspaceRepair,ft as inspectWorkspaceRepairCapabilities,vt as listWorkspaceRepairTransactions,Ma as planWorkspaceRepair,Ha as planWorkspaceRepairProposal,ce as readWorkspaceRepairTransaction,Ua as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-CHMCKYJJ.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-WSDVFLHT.js';
@@ -1 +1 @@
1
- export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-XH7PDHBF.js';
1
+ export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-GVS5OFUB.js';
@@ -1 +1 @@
1
- import {a}from'./chunk-ESWFBSYM.js';import {f as f$1,r,l}from'./chunk-5ZA4JYOP.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (l(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return f$1({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r$1){this.rebuild=r$1?.rebuild??(()=>r({...o})),this.now=r$1?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
1
+ import {a}from'./chunk-A3JCETSF.js';import {f as f$1,r,l}from'./chunk-AUCHMXUZ.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (l(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return f$1({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r$1){this.rebuild=r$1?.rebuild??(()=>r({...o})),this.now=r$1?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
package/docs/README.md CHANGED
@@ -77,6 +77,7 @@ or use `import` to copy or clone one into the workspace.
77
77
  | Create a workspace or project | [Creating workspaces and projects](./creating-workspaces-and-projects.md) | A registered project with canonical `.workspai` metadata |
78
78
  | Bring an existing repository under governance | [Workspace operations](./workspace-operations.md#import-and-adoption) | Source stays in place with `adopt`, or is copied/cloned with `import` |
79
79
  | Run the complete intelligence loop | [Unified runner](./workspace-intelligence-runner.md) | One ordered run report with durable stage evidence |
80
+ | Turn plain language into governed work | [Goal Packs](./goal-packs.md) | A scope-bound, evidence-pinned plan and portable agent handoff |
80
81
  | Repair a blocker through an approved transaction | [Workspace Repair Engine](./workspace-repair-engine.md) | Checkpointed execution, validation, canonical verify, and safe rollback |
81
82
  | Set a release, security, or coverage outcome | [Verified engineering goals](./workspace-intelligence-runner.md#verified-engineering-goals) | A durable success contract with a current evidence-backed verdict |
82
83
  | Ask an architecture or dependency question | [Workspace Knowledge Graph](./workspace-knowledge-graph.md) | A bounded answer with proof references rather than the whole graph |
@@ -102,6 +103,7 @@ with [AI Quickstart](./AI_QUICKSTART.md) only when that is your goal.
102
103
  | [workspace-run.md](./workspace-run.md) | Polyglot fleet orchestration (`workspace run`) |
103
104
  | [workspace-intelligence-runner.md](./workspace-intelligence-runner.md) | Canonical unified runner, execution envelope, report schema, exit codes, failure propagation, and CI consumption |
104
105
  | [workspace-repair-engine.md](./workspace-repair-engine.md) | CLI-owned plan, approval, checkpoint, execution, verification, decision, and rollback state machine |
106
+ | [goal-packs.md](./goal-packs.md) | Plain-language intent compilation, scope/evidence binding, agent handoff, and mutation boundary |
105
107
  | [workspace-knowledge-graph.md](./workspace-knowledge-graph.md) | Two-minute graph quickstart, proof model, AI/MCP consumption, performance, and honest token-efficiency measurement |
106
108
  | [graph-benchmark-methodology.md](./graph-benchmark-methodology.md) | Reproducible payload-reduction benchmark, formulas, claim boundaries, and publication rules |
107
109
  | [workspace-intelligence-evaluation.md](./workspace-intelligence-evaluation.md) | Provider usage, cost provenance, verified outcomes, comparison, and extension consumption |
@@ -18,21 +18,23 @@ versioned contracts and focused guides.
18
18
 
19
19
  The root README keeps this order:
20
20
 
21
- 1. product category, slogan, and three outcomes;
22
- 2. one copyable path for existing software and one guided path for new software;
23
- 3. a short outcome-oriented view of what Workspai provides;
24
- 4. the canonical Model → derived Graph boundary and intelligence chain;
25
- 5. consumer surfaces and goal-based documentation links;
26
- 6. package, contributor, community, and license routes.
21
+ 1. a problem-first product promise, slogan, and copyable first run;
22
+ 2. product category and three durable outcomes;
23
+ 3. one copyable path for existing software and one guided path for new software;
24
+ 4. a short outcome-oriented view of what Workspai provides;
25
+ 5. the canonical Model → derived Graph boundary and intelligence chain;
26
+ 6. consumer surfaces and goal-based documentation links;
27
+ 7. package, contributor, community, and license routes.
27
28
 
28
29
  The CLI README keeps this order:
29
30
 
30
- 1. product category, slogan, and value;
31
- 2. a two-minute existing-project path and the guided create path;
32
- 3. the small set of durable outputs a user should recognize;
33
- 4. the canonical Model → derived Graph boundary and intelligence chain;
34
- 5. everyday workflows grouped by goal;
35
- 6. outputs, requirements, documentation, troubleshooting, and contribution.
31
+ 1. a problem-first product promise, slogan, and copyable first run;
32
+ 2. product category and durable value;
33
+ 3. a two-minute existing-project path and the guided create path;
34
+ 4. the small set of durable outputs a user should recognize;
35
+ 5. the canonical Model → derived Graph boundary and intelligence chain;
36
+ 6. everyday workflows grouped by goal;
37
+ 7. outputs, requirements, documentation, troubleshooting, and contribution.
36
38
 
37
39
  ## What does not belong in a main README
38
40
 
@@ -110,6 +112,17 @@ task-success claim.
110
112
  - Link to deeper guidance instead of duplicating it.
111
113
  - Do not add a README section for every feature or release.
112
114
 
115
+ ## Media policy
116
+
117
+ - Keep videos outside the npm package tarball; use a stable website, CDN, or
118
+ GitHub Release asset.
119
+ - npm READMEs may use a lightweight poster or a bounded, silent GIF instead of
120
+ relying on an embedded video player. Link to the hosted MP4 when full
121
+ resolution or audio matters.
122
+ - Keep the poster or first GIF frame meaningful without playback and give it
123
+ useful alternative text.
124
+ - Do not commit generated social-video masters under `packages/cli/docs/`.
125
+
113
126
  ## Validation
114
127
 
115
128
  Run from `packages/cli`:
@@ -46,7 +46,7 @@ Validate or preview the current CLI announcement locally:
46
46
  npm --workspace workspai run check:release-announcement
47
47
  npm --workspace workspai run release:announcement -- \
48
48
  --product workspai-cli \
49
- --tag v0.55.0 \
49
+ --tag v0.58.0 \
50
50
  --markdown-output /tmp/workspai-discord-announcement.md
51
51
  ```
52
52
 
@@ -93,6 +93,14 @@ the exact preflight, 11-stage, artifact, and exit contract.
93
93
  | Docs drift guard | `npm run check:docs-drift` |
94
94
  | README command smoke | `npm run smoke:readme` |
95
95
  | Agent customization drift | `npm run check:agent-customization-drift -- --workspace <workspace-root>` |
96
+ | Cross-platform lockfile | `npm run check:cross-platform-lockfile` |
97
+
98
+ The root `postinstall` lifecycle runs the lockfile check before build or test
99
+ jobs can start. This prevents a lockfile regenerated from a platform-pruned
100
+ `node_modules` tree from reaching native Vitest/Rolldown startup on another
101
+ operating system. Restore an accidentally deleted lockfile from Git; perform a
102
+ deliberate full regeneration only with both the lockfile and `node_modules`
103
+ absent.
96
104
 
97
105
  ## Recommended pre-release checks
98
106
 
@@ -19,6 +19,8 @@ npx workspai pipeline [--json] [--strict] [--skip-verify] [--skip-analyze] [--sk
19
19
  npx workspai analyze [--workspace <path>] [--json] [--strict] [--output <file>]
20
20
  npx workspai readiness [--workspace <path>] [--json] [--strict] [--skip-verify]
21
21
  npx workspai autopilot release [--mode <audit|safe-fix|enforce>] [--json] [--output <file>] [--since <ref>] [--parallel] [--max-workers <n>]
22
+ npx workspai goal <intent> [--workspace <path>] [--scope <workspace|project:name>] [--for-agent <generic|claude|codex>] [--max-attempts <1-25>] [--refresh] [--dry-run] [--json]
23
+ npx workspai goal <--status [goal-id]|--list|--activate <goal-id>|--cancel <goal-id>|--prepare <goal-id>|--verify <goal-id>> [--workspace <path>] [--no-run] [--json]
22
24
  ```
23
25
 
24
26
  Recommended CI:
@@ -63,7 +65,7 @@ npx workspai workspace share [--output <file>] [--include-paths] [--no-doctor]
63
65
  npx workspai workspace contract init [--force] [--json]
64
66
  npx workspai workspace contract inspect [--json]
65
67
  npx workspai workspace contract verify [--strict] [--json]
66
- npx workspai workspace contract graph [--json]
68
+ npx workspai workspace contract graph [--output <graph.json>] [--json]
67
69
  npx workspai workspace intelligence run [--workspace <path>] [--for-agent <agent>] [--strict] [--json]
68
70
  npx workspai workspace goal plan <release-readiness|dependency-security|test-coverage> [--scope project:<name>] [--target <0-100>] [--allow-breaking] [--allow-force] [--no-build] [--no-tests] [--json]
69
71
  npx workspai workspace goal status <goal-id> [--json]
@@ -153,6 +155,16 @@ portable verdict is written to
153
155
  [Verified engineering goals](./workspace-intelligence-runner.md#verified-engineering-goals)
154
156
  for the supported scopes, safety constraints, and verification boundary.
155
157
 
158
+ Top-level `goal <intent>` is the plain-language planning front door. It binds
159
+ the intent to the current canonical Model and Graph, resolves project/workspace
160
+ scope, runs capability/retrieval preflight, and atomically writes a Goal Pack,
161
+ portable agent handoff, and active-goal index. Use `goal --status`, `--list`,
162
+ `--activate`, or `--cancel` for discovery/lifecycle; deterministic goals may use
163
+ `--prepare` and `--verify`. It does not silently mutate source or let an agent
164
+ claim verification. Lifecycle operations are mutually exclusive, cannot be
165
+ combined with an intent or planning-only flags, and `--no-run` is valid only
166
+ with `--verify`. See [Goal Packs](./goal-packs.md).
167
+
156
168
  `workspace feedback record` is a non-interactive machine interface. It requires
157
169
  exactly one JSON object on stdin and `--json`; an empty stdin or interactive TTY
158
170
  is rejected. Required fields are `actionId`, `summary`, and `outcome`. The
@@ -62,6 +62,9 @@ and model/graph freshness for the selected project.
62
62
  | `workspace remediation-plan --write` | `.workspai/reports/artifact-remediation-plan-last-run.json` | `artifact-remediation-plan-v1` | `contracts/artifact-remediation-plan.v1.json` |
63
63
  | `workspace repair *` | `.workspai/reports/workspace-repair-last-run.json` | `workspai.workspace-repair-transaction.v1` | `contracts/workspace-intelligence/workspace-repair-transaction.v1.json` |
64
64
  | `workspace repair capabilities` | CLI capability output | `workspai.workspace-repair-capabilities.v1` | `contracts/workspace-repair-capabilities.v1.json` |
65
+ | `goal <intent>` | `.workspai/reports/goal-pack-last-run.json` | `workspai.goal-pack.v1` | `contracts/workspace-intelligence/goal-pack.v1.json` |
66
+ | `goal <intent>` / lifecycle options | `.workspai/goals/index.json` | `workspai.goal-index.v1` | `contracts/workspace-intelligence/goal-index.v1.json` |
67
+ | `goal --status/--list/... --json` | stdout | `workspai.goal-lifecycle-result.v1` | `contracts/workspace-intelligence/goal-lifecycle-result.v1.json` |
65
68
  | `analyze` | `.workspai/reports/analyze-last-run.json` | `rapidkit-analyze-v1` | `contracts/analyze-last-run.v1.json` |
66
69
  | `readiness` | `.workspai/reports/release-readiness-last-run.json` | `release-readiness-v1` | `contracts/release-readiness.v1.json` |
67
70
  | `pipeline` | `.workspai/reports/pipeline-last-run.json` | `rapidkit-pipeline-v1` | `contracts/pipeline-last-run.v1.json` |
@@ -70,6 +73,14 @@ and model/graph freshness for the selected project.
70
73
 
71
74
  Side/cache (not gates): `.workspai/reports/doctor-workspace-cache.json` (`doctor-workspace-cache-v2`).
72
75
 
76
+ Every Goal Pack also has an immutable-instance directory under
77
+ `.workspai/goals/<goal-id>/` containing `goal-pack.json` and
78
+ `agent-handoff.json`. These are portable planning/projection artifacts, not
79
+ verification gates. Only CLI-owned verified-goal and Repair Engine evidence may
80
+ authorize mutation or claim completion.
81
+ The sibling `.workspai/goals/index.json` is the canonical active-goal discovery
82
+ and lifecycle registry; consumers must not infer activity from directory order.
83
+
73
84
  Doctor Studio handoff:
74
85
  `doctor-remediation-plan-v2` (`contracts/doctor-remediation-plan.v2.json`) is emitted in JSON
75
86
  responses and persisted to `.workspai/reports/doctor-remediation-plan-last-run.json` by
@@ -33,6 +33,7 @@ These commands are implemented and orchestrated by Workspai CLI:
33
33
  - `infra`
34
34
  - `commands`
35
35
  - `create`
36
+ - `goal`
36
37
  - `project`
37
38
  - `shell activate`
38
39
 
@@ -24,15 +24,17 @@ Do not copy a schema from `main` and assume it matches an older installed CLI.
24
24
 
25
25
  Canonical JSON lives in **`../../contracts/`** (CLI package root, published in the tarball).
26
26
 
27
- | Script | Purpose |
28
- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
29
- | `npm run generate:contracts` | Regenerate runtime surface, create planner, agent customization pack, import-stack parity, module-layout, infra-stack |
30
- | `npm run check:generated-contracts` | Verify committed JSON matches generators |
31
- | `npm run sync:parity-snapshot` | Copy canonical → vscode `contracts/` mirror |
32
- | `npm run check:parity-snapshot` | Verify mirrors match canonical |
33
- | `npm run validate:contracts` | Shared-contract checks and focused contract tests |
34
- | `npm run contracts:validate` | Comprehensive generated/shared contract, parity, runtime-conformance, and adversarial gate |
35
- | `npm run check:agent-customization-drift` | Verify generated agent customization files are committed in a consumer workspace |
27
+ | Script | Purpose |
28
+ | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
29
+ | `npm run generate:contracts` | Regenerate runtime surface, create planner, agent customization pack, import-stack parity, module-layout, infra-stack |
30
+ | `npm run check:generated-contracts` | Verify committed JSON matches generators |
31
+ | `npm run sync:parity-snapshot` | Copy canonical → vscode `contracts/` mirror |
32
+ | `npm run check:parity-snapshot` | Verify mirrors match canonical |
33
+ | `npm run validate:contracts` | Shared-contract checks and focused contract tests |
34
+ | `npm run contracts:validate` | Comprehensive generated/shared contract, parity, runtime-conformance, and adversarial gate |
35
+ | `npm run check:agent-customization-drift` | Verify generated agent customization files are committed in a consumer workspace |
36
+ | `npm run test:real-world -- ...` | Qualify explicitly selected linked repositories in isolated or cumulative workspaces |
37
+ | `npm run test:real-world:enterprise -- ...` | Exercise the read-mostly, export, archive, agent dry-run, snapshot, and destructive dry-run command surface |
36
38
 
37
39
  Workflow: change code → `npm run generate:contracts` → `npm run sync:parity-snapshot` → commit npm + vscode `contracts/`.
38
40
 
@@ -72,6 +74,7 @@ Published under `../../contracts/` (not duplicated in this folder):
72
74
  - `analyze-last-run.v1.json` — analyze evidence
73
75
  - `pipeline-last-run.v1.json` — governance pipeline orchestration
74
76
  - `project-entry-capability.v1.json` — open-ended adopt/import contract for readable projects
77
+ - `adopt-effects.v1.json` — dry-run disclosure of project metadata, conditional repository-control reconciliation, and workspace operations before adoption
75
78
  - `create-planner-capabilities.v1.json` — native, official, and existing capability lanes
76
79
  - `agent-customization-pack.v1.json` — generated instructions, prompts, skills, agents, optional hooks, MCP-ready design metadata, target matrix, and drift state for AI agent surfaces
77
80
  - `workspace-list.v1.json`, `workspace-sync.v1.json`, and `compatibility-matrix.v1.json` — workspace discovery, synchronization, and platform compatibility
@@ -119,10 +122,10 @@ CLI commands: see [commands-reference.md](../commands-reference.md) and the
119
122
 
120
123
  `rapidkit-cli-contracts.json` describes:
121
124
 
122
- - `VersionResponse` — `rapidkit version --json`
125
+ - `VersionResponse` — `workspai version --json`
123
126
  - `CommandsResponse` — `workspai commands --json`
124
- - `ProjectDetectResponse` — `rapidkit project detect --json`
125
- - `ModulesListResponseV1` — `rapidkit modules list --json-schema 1`
127
+ - `ProjectDetectResponse` — `workspai project detect --json`
128
+ - `ModulesListResponseV1` — `workspai modules list --json-schema 1`
126
129
 
127
130
  ## Versioning
128
131
 
@@ -135,3 +138,4 @@ CLI commands: see [commands-reference.md](../commands-reference.md) and the
135
138
  - [Documentation index](../README.md)
136
139
  - [commands-reference.md](../commands-reference.md)
137
140
  - [workspace-operations.md](../workspace-operations.md)
141
+ - [real-world-qualification.md](../real-world-qualification.md)
@@ -39,6 +39,10 @@ Checks:
39
39
 
40
40
  > Compatibility note: `npx workspai doctor --workspace` still works, but `doctor workspace` is the canonical form.
41
41
 
42
+ Both workspace forms use the canonical project-to-workspace resolver. After a
43
+ project is adopted, imported, or relinked, they can be launched from that
44
+ project directory and resolve its validated machine-local workspace binding.
45
+
42
46
  ### 3) Project Check (Canonical)
43
47
 
44
48
  ```bash
@@ -111,6 +115,9 @@ npx workspai doctor
111
115
  # Full check inside a workspace
112
116
  npx workspai doctor workspace
113
117
 
118
+ # Expand every probe and lifecycle capability (default output is summary-first)
119
+ npx workspai doctor workspace --verbose
120
+
114
121
  # Focus only on current project
115
122
  npx workspai doctor project
116
123
 
@@ -120,6 +127,9 @@ npx workspai doctor workspace --json
120
127
  # Compact agent/CI projection; full evidence is still written
121
128
  npx workspai doctor workspace --fresh --json=summary
122
129
 
130
+ # Review the governed plan before mutation
131
+ npx workspai doctor workspace --plan
132
+
123
133
  # Attempt safe fixes (interactive)
124
134
  npx workspai doctor workspace --fix
125
135
 
@@ -145,7 +155,7 @@ CI, and agents: it distinguishes blocking causes, advisory findings, unknowns, d
145
155
  subjects, vulnerability findings, not-applicable checks, and the next safe action. The complete
146
156
  probe and diagnosis evidence remains in `doctor-last-run.json` or `doctor-project-last-run.json`.
147
157
 
148
- ## One verdict, backed by every probe
158
+ ## One verdict, multi-axis accounting
149
159
 
150
160
  Doctor calculates one verdict from the host and every project probe:
151
161
 
@@ -153,12 +163,26 @@ Doctor calculates one verdict from the host and every project probe:
153
163
  - **Needs attention** means the current profile found advisory work.
154
164
  - **Blocked** means at least one error-level probe failed.
155
165
 
156
- The score and verdict use the same counts. A failed security, coverage, or
157
- runtime probe cannot be hidden behind a high percentage or a healthy host. New
158
- evidence includes the host/project score components and per-project probe
159
- summary; semantic validation rejects contradictory artifacts before they are
160
- written. Older v1 evidence remains readable so existing workspaces and IDEs do
161
- not break during migration.
166
+ The verdict is authoritative. Human output presents blocking, advisory,
167
+ unknown, contradictory, and not-applicable counts separately; it never calls a
168
+ single percentage “health.” The additive `healthScore.presentation` contract
169
+ labels its percentage as a diagnostic pass rate for accounting only. A failed
170
+ security, coverage, or runtime probe therefore cannot be hidden behind a high
171
+ percentage or a healthy host. Existing score fields remain readable for older
172
+ IDEs, while updated consumers prefer the multi-axis projection.
173
+
174
+ Doctor also publishes `projectArchetype` independently from `projectKind`.
175
+ `projectKind` describes the technical surface (backend, frontend, extension,
176
+ and so on); the archetype describes the product role (service, application,
177
+ library, SDK, platform, plugin, or monorepo). Service-only checks such as a
178
+ runtime health endpoint, database migrations, or an executable boot entrypoint
179
+ are retained as explicit `not-applicable` evidence for non-deployable
180
+ archetypes instead of becoming false warnings.
181
+
182
+ The default terminal view is summary-first and uses portable boundaries such
183
+ as `$WORKSPACE`, `$PROJECT`, and `external/<project>`. `--verbose` expands all
184
+ probes and lifecycle capabilities. JSON continues to retain canonical absolute
185
+ paths because local machine consumers need them for governed operations.
162
186
 
163
187
  ## Universal diagnosis core
164
188
 
@@ -192,10 +216,10 @@ The same diagnosis contract is used for Node, Python, Go, JVM, Rust, .NET, PHP,
192
216
  Clojure, Deno, Bun, Scala, Kotlin, C, C++, and unknown/custom projects. Runtime adapters gather
193
217
  different evidence; the diagnosis, causality, safety, and verification vocabulary stays the same.
194
218
  Composite projects publish every detected family under `project.runtimeFamilies`; Doctor keeps a
195
- primary runtime for compatibility and explicitly warns when secondary runtimes need their own
196
- project boundary or custom adapter instead of silently claiming full coverage. Every unevaluated
197
- secondary runtime is also published as a diagnosis unknown and proportionally lowers diagnosis
198
- completeness; a primary-only polyglot scan can never report 100%.
219
+ primary runtime for compatibility. A detected cross-language platform is evaluated through primary
220
+ and portable evidence, and asks for explicit custom adapters only for runtime-specific checks the
221
+ portable contract cannot represent. Every unevaluated secondary runtime remains a diagnosis unknown
222
+ and proportionally lowers completeness; a primary-only polyglot scan can never report 100%.
199
223
 
200
224
  Workspace project boundaries come from the canonical workspace contract/registry when available.
201
225
  A nested solution, test project, or manifest inside a registered project is treated as evidence for