workspai 0.65.0 → 0.67.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 (211) hide show
  1. package/README.md +28 -23
  2. package/contracts/agent-customization-pack.v1.json +4 -2
  3. package/contracts/analyze-last-run.v1.json +9 -1
  4. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +117 -0
  5. package/contracts/extension-cli-compatibility.v1.json +6 -0
  6. package/contracts/published-contract-catalog.v1.json +30 -0
  7. package/contracts/runtime-command-surface.v1.json +100 -2
  8. package/contracts/workspace-activity-board.v1.json +114 -0
  9. package/contracts/workspace-activity-event.v1.json +132 -0
  10. package/contracts/workspace-activity-monitor-fleet.v1.json +18 -0
  11. package/contracts/workspace-activity-monitor-snapshot.v1.json +161 -0
  12. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +17 -0
  13. package/contracts/workspace-intelligence/mcp-design.v1.json +49 -2
  14. package/contracts/workspace-intelligence/project-agent-entry.v1.json +3 -0
  15. package/contracts/workspace-intelligence/project-context-agent.v1.json +49 -7
  16. package/contracts/workspace-intelligence/project-knowledge-graph-reference.v1.json +51 -0
  17. package/contracts/workspace-intelligence/workspace-intelligence-benchmark.v1.json +196 -0
  18. package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +97 -2
  19. package/contracts/workspace-intelligence/workspace-skills-index.v1.json +34 -0
  20. package/contracts/workspace-intelligence-architecture.v1.json +17 -0
  21. package/contracts/workspace-intelligence-chain.v1.json +17 -0
  22. package/dist/analyze-IC2KRVCG.js +1 -0
  23. package/dist/{artifact-remediation-plan-XIQNI35L.js → artifact-remediation-plan-GFFHC2ZU.js} +1 -1
  24. package/dist/autopilot-release-RECEZAZI.js +1 -0
  25. package/dist/capabilities-command-X4WZIJNR.js +1 -0
  26. package/dist/chunk-2LIVMG5C.js +2 -0
  27. package/dist/chunk-2M62CU3O.js +2 -0
  28. package/dist/chunk-2MTJWPQ4.js +1 -0
  29. package/dist/chunk-2MVIRJJR.js +1 -0
  30. package/dist/chunk-2RPFCBS4.js +1 -0
  31. package/dist/chunk-3O7LZPKA.js +4 -0
  32. package/dist/chunk-3OGPTLI2.js +1 -0
  33. package/dist/{chunk-6TBTMWNA.js → chunk-4RV4JVGR.js} +1 -1
  34. package/dist/{chunk-YYQEWAES.js → chunk-4WVOAX2V.js} +1 -1
  35. package/dist/{chunk-N4QQADXX.js → chunk-5EVDW7JM.js} +1 -1
  36. package/dist/{chunk-J3X56S7L.js → chunk-5ME4W4LN.js} +1 -1
  37. package/dist/chunk-5OA33JH2.js +2 -0
  38. package/dist/chunk-5TY74LLW.js +2 -0
  39. package/dist/chunk-6254CWUY.js +49 -0
  40. package/dist/{chunk-D5YJOQYK.js → chunk-6E2Y3XGT.js} +1 -1
  41. package/dist/chunk-ARUFY5W3.js +1 -0
  42. package/dist/chunk-B4IVVTMQ.js +2 -0
  43. package/dist/{chunk-HDNATYW7.js → chunk-BHFRP7TV.js} +1 -1
  44. package/dist/{chunk-KTN2ARZJ.js → chunk-BHM6RHTA.js} +3 -3
  45. package/dist/chunk-BRYJTW6S.js +2 -0
  46. package/dist/{chunk-HCFWT42C.js → chunk-BUYLM6QV.js} +1 -1
  47. package/dist/chunk-CPR2CMOY.js +1 -0
  48. package/dist/{chunk-XGE2FDI4.js → chunk-CZVT7T2X.js} +1 -1
  49. package/dist/chunk-EHCKITR4.js +2 -0
  50. package/dist/chunk-ENZPM52J.js +1 -0
  51. package/dist/chunk-FPDH3N3A.js +7 -0
  52. package/dist/{chunk-PXWKMPPI.js → chunk-FX5J6JCK.js} +1 -1
  53. package/dist/chunk-FY4X2VOE.js +39 -0
  54. package/dist/chunk-GIQ4SDRJ.js +1 -0
  55. package/dist/chunk-H77ZNH5O.js +1 -0
  56. package/dist/{chunk-2RL6RRT2.js → chunk-HQLBO23O.js} +50 -50
  57. package/dist/chunk-HYE5UHPV.js +2 -0
  58. package/dist/{chunk-D65FCQIO.js → chunk-IKUFNK46.js} +1 -1
  59. package/dist/{chunk-WRQWVSBJ.js → chunk-IQQMFRWM.js} +1 -1
  60. package/dist/chunk-JCGSIDMC.js +2 -0
  61. package/dist/chunk-KENOAC2Q.js +13 -0
  62. package/dist/chunk-KQ2TMI26.js +97 -0
  63. package/dist/chunk-L5Q2S5GY.js +3 -0
  64. package/dist/chunk-LPCZHKD5.js +1 -0
  65. package/dist/chunk-N4QFNOAI.js +1 -0
  66. package/dist/chunk-NMXGSVMD.js +1 -0
  67. package/dist/{chunk-GQSRNUCU.js → chunk-NVND4727.js} +3 -3
  68. package/dist/{chunk-W6FHVXNL.js → chunk-OCNPOYMA.js} +1 -1
  69. package/dist/chunk-PSYQ6IJA.js +12 -0
  70. package/dist/{chunk-VRGEPPUB.js → chunk-QMQBX3RV.js} +1 -1
  71. package/dist/{chunk-YUGKQ44M.js → chunk-SLFOUSRW.js} +1 -1
  72. package/dist/chunk-SRLWHOLF.js +1 -0
  73. package/dist/chunk-SVYY55IS.js +157 -0
  74. package/dist/chunk-SX6A656X.js +1 -0
  75. package/dist/{chunk-X6TNBARH.js → chunk-TABXSDTR.js} +2 -2
  76. package/dist/chunk-THIG2YQP.js +681 -0
  77. package/dist/chunk-TP7VKEUF.js +1 -0
  78. package/dist/chunk-U5ENEDJA.js +7 -0
  79. package/dist/chunk-UTV4DTNM.js +1 -0
  80. package/dist/chunk-VI4ZRAY6.js +1 -0
  81. package/dist/chunk-VQZ5PI5J.js +1 -0
  82. package/dist/chunk-VWBMDGPY.js +9 -0
  83. package/dist/chunk-XDPTAV2T.js +2 -0
  84. package/dist/chunk-XWKGZRHN.js +1 -0
  85. package/dist/chunk-Y35VLVF6.js +5 -0
  86. package/dist/{chunk-VYDURWN7.js → chunk-Y4Z6CEII.js} +1 -1
  87. package/dist/chunk-YYY2WXOH.js +1 -0
  88. package/dist/chunk-ZGHJIQXL.js +1 -0
  89. package/dist/chunk-ZI2E7P6O.js +4 -0
  90. package/dist/{create-ALT2ME6H.js → create-72ITVZXV.js} +1 -1
  91. package/dist/{demo-kit-QHIDCSBI.js → demo-kit-5UQH2OXC.js} +1 -1
  92. package/dist/{doctor-RW4R3O5C.js → doctor-CVYUESRQ.js} +1 -1
  93. package/dist/{dotnet-webapi-clean-AVHPJG7Y.js → dotnet-webapi-clean-YEHYIGOT.js} +1 -1
  94. package/dist/{goal-lifecycle-VYOKS6E6.js → goal-lifecycle-H55AGFCB.js} +1 -1
  95. package/dist/goal-pack-6OBZOPCD.js +1 -0
  96. package/dist/{gofiber-standard-47S2GYAO.js → gofiber-standard-C44IIQYH.js} +1 -1
  97. package/dist/{gogin-standard-EWB4XNOI.js → gogin-standard-X7VKACVR.js} +1 -1
  98. package/dist/index.d.ts +20 -2
  99. package/dist/index.js +177 -177
  100. package/dist/live-command-5VXPR43F.js +15 -0
  101. package/dist/{pipeline-U4N2DVD7.js → pipeline-SKYOXWHW.js} +1 -1
  102. package/dist/{project-agent-entry-YAQCHIMP.js → project-agent-entry-5IUBEREI.js} +1 -1
  103. package/dist/project-intelligence-lens-LQCN65P2.js +1 -0
  104. package/dist/{project-test-coverage-4S7MEQ6T.js → project-test-coverage-KD4LLFGV.js} +1 -1
  105. package/dist/{pythonRapidkitExec-VAW5XE4Z.js → pythonRapidkitExec-44ORGQ4R.js} +1 -1
  106. package/dist/{rust-axum-M5X4ZC4Z.js → rust-axum-JKZTZDRZ.js} +1 -1
  107. package/dist/{springboot-standard-Y5ADLZMQ.js → springboot-standard-PI4FLTAN.js} +1 -1
  108. package/dist/verified-goal-HN7G532B.js +1 -0
  109. package/dist/{workspace-HGUZWNAB.js → workspace-5W7FYGDQ.js} +1 -1
  110. package/dist/{workspace-agent-sync-GEN3KBAX.js → workspace-agent-sync-OZCDQORK.js} +1 -1
  111. package/dist/{workspace-archive-ZBCKJHXS.js → workspace-archive-NOSGRKRZ.js} +1 -1
  112. package/dist/{workspace-context-4WIWFW26.js → workspace-context-L65BR5L6.js} +1 -1
  113. package/dist/{workspace-contract-7DXK4GF5.js → workspace-contract-JYHNEJPV.js} +1 -1
  114. package/dist/workspace-explain-SUBK6FLO.js +1 -0
  115. package/dist/workspace-explain-contract-WMREJWHF.js +1 -0
  116. package/dist/{workspace-feedback-RQ4TGJW6.js → workspace-feedback-MWGCT5R2.js} +1 -1
  117. package/dist/{workspace-foundation-J3NNRMI3.js → workspace-foundation-VIB3PXNH.js} +1 -1
  118. package/dist/{workspace-graph-stream-PQI7OGCE.js → workspace-graph-stream-45JHE4MG.js} +1 -1
  119. package/dist/workspace-graph-token-efficiency-NPECU6Y5.js +1 -0
  120. package/dist/{workspace-history-SYCDK7FO.js → workspace-history-JKW3VJO3.js} +1 -1
  121. package/dist/{workspace-intelligence-6FS26JOQ.js → workspace-intelligence-3C47PK4L.js} +1 -1
  122. package/dist/workspace-intelligence-benchmark-SRDIHX3X.js +1 -0
  123. package/dist/workspace-intelligence-evaluation-OJIQS5SN.js +1 -0
  124. package/dist/{workspace-intelligence-runner-XYUPCSLN.js → workspace-intelligence-runner-OWN5ZI6W.js} +1 -1
  125. package/dist/{workspace-intelligence-runtime-registry-IW6J53LO.js → workspace-intelligence-runtime-registry-UKFB3BI7.js} +1 -1
  126. package/dist/workspace-knowledge-graph-AKG5NUU6.js +1 -0
  127. package/dist/{workspace-knowledge-graph-contract-L3CLAM2M.js → workspace-knowledge-graph-contract-X52KXBXJ.js} +1 -1
  128. package/dist/{workspace-knowledge-graph-query-FZXSPWGK.js → workspace-knowledge-graph-query-DXA4CROE.js} +1 -1
  129. package/dist/workspace-knowledge-graph-snapshot-SNI5K2RL.js +1 -0
  130. package/dist/{workspace-marker-7NHMDIRL.js → workspace-marker-XGAWZZDX.js} +1 -1
  131. package/dist/workspace-mcp-serve-PK226GMV.js +3 -0
  132. package/dist/workspace-model-R4ISKDB2.js +1 -0
  133. package/dist/{workspace-onboarding-X3PWRIIS.js → workspace-onboarding-Y5RPEFUD.js} +1 -1
  134. package/dist/{workspace-python-engine-state-J4QKW55K.js → workspace-python-engine-state-BE4A3BL5.js} +1 -1
  135. package/dist/{workspace-readme-G7TZ3V5T.js → workspace-readme-PL5V3UDH.js} +2 -2
  136. package/dist/{workspace-registry-summary-LJN4WHIZ.js → workspace-registry-summary-STGUGROG.js} +1 -1
  137. package/dist/workspace-repair-engine-FNLL5ZDK.js +3 -0
  138. package/dist/workspace-run-GFBFGUFM.js +1 -0
  139. package/dist/{workspace-verify-USRRIM2F.js → workspace-verify-AXVX3PF3.js} +1 -1
  140. package/dist/{workspace-watch-43YZPLF7.js → workspace-watch-RLBEJKXE.js} +1 -1
  141. package/docs/DEVELOPMENT.md +19 -0
  142. package/docs/README.md +19 -16
  143. package/docs/SETUP.md +10 -0
  144. package/docs/agent-entry.md +22 -7
  145. package/docs/ci-workflows.md +1 -1
  146. package/docs/commands-reference.md +58 -8
  147. package/docs/contracts/ARTIFACT_CATALOG.md +64 -44
  148. package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +1 -0
  149. package/docs/contracts/NAMING_AND_COEXISTENCE.md +20 -18
  150. package/docs/contracts/README.md +7 -3
  151. package/docs/real-world-qualification.md +19 -3
  152. package/docs/workspace-intelligence-benchmark.md +82 -0
  153. package/docs/workspace-knowledge-graph.md +95 -27
  154. package/docs/workspace-live-activity.md +209 -0
  155. package/docs/workspace-operations.md +32 -9
  156. package/package.json +4 -2
  157. package/dist/analyze-5PDVWECJ.js +0 -1
  158. package/dist/autopilot-release-JVIJCTKX.js +0 -1
  159. package/dist/capabilities-command-LHM3XIS6.js +0 -1
  160. package/dist/chunk-2647BYBC.js +0 -1
  161. package/dist/chunk-27UR373Z.js +0 -1
  162. package/dist/chunk-2C5ZBVBI.js +0 -2
  163. package/dist/chunk-6JWNDWOA.js +0 -1
  164. package/dist/chunk-CCDGHPEJ.js +0 -2
  165. package/dist/chunk-DFG33SBR.js +0 -2
  166. package/dist/chunk-FY4IIAIF.js +0 -1
  167. package/dist/chunk-HEZZ72V4.js +0 -94
  168. package/dist/chunk-HN7P4T3B.js +0 -681
  169. package/dist/chunk-ILIBOMYL.js +0 -1
  170. package/dist/chunk-J7QYANXK.js +0 -8
  171. package/dist/chunk-JD3A5QM6.js +0 -2
  172. package/dist/chunk-JQLJBK5N.js +0 -1
  173. package/dist/chunk-KLSSPJTV.js +0 -1
  174. package/dist/chunk-L22EABIC.js +0 -7
  175. package/dist/chunk-LNXIMF3O.js +0 -1
  176. package/dist/chunk-MDTI3UEB.js +0 -1
  177. package/dist/chunk-MOSXTVPU.js +0 -1
  178. package/dist/chunk-MYJQGGIU.js +0 -5
  179. package/dist/chunk-NOV6723U.js +0 -1
  180. package/dist/chunk-NYEAMMUL.js +0 -1
  181. package/dist/chunk-NZ3WZYD5.js +0 -1
  182. package/dist/chunk-O5B2L3R2.js +0 -1
  183. package/dist/chunk-OWB5KWSS.js +0 -13
  184. package/dist/chunk-P5PSZQPB.js +0 -2
  185. package/dist/chunk-QCKWQFCD.js +0 -1
  186. package/dist/chunk-QI3HG6IG.js +0 -144
  187. package/dist/chunk-SWGSFLTC.js +0 -1
  188. package/dist/chunk-THIOE2PB.js +0 -2
  189. package/dist/chunk-U5FCQTVL.js +0 -4
  190. package/dist/chunk-UXEO5QCF.js +0 -33
  191. package/dist/chunk-VR6XMUF3.js +0 -2
  192. package/dist/chunk-VVJK5NFY.js +0 -2
  193. package/dist/chunk-VXKWWX7S.js +0 -8
  194. package/dist/chunk-W322YDHS.js +0 -49
  195. package/dist/chunk-WPRLXKWC.js +0 -8
  196. package/dist/chunk-Y5YAP4F3.js +0 -2
  197. package/dist/chunk-YN5X2FTP.js +0 -1
  198. package/dist/chunk-YOCN7GF4.js +0 -1
  199. package/dist/goal-pack-YWPI43QL.js +0 -1
  200. package/dist/project-intelligence-lens-MRQR2LQW.js +0 -1
  201. package/dist/verified-goal-WM34TTGE.js +0 -1
  202. package/dist/workspace-explain-TE2LGOAV.js +0 -1
  203. package/dist/workspace-explain-contract-V2IVSROX.js +0 -1
  204. package/dist/workspace-graph-token-efficiency-2I4X374C.js +0 -1
  205. package/dist/workspace-intelligence-evaluation-CQDKOYZZ.js +0 -1
  206. package/dist/workspace-knowledge-graph-SWCKDTPF.js +0 -1
  207. package/dist/workspace-knowledge-graph-snapshot-M572JRB4.js +0 -1
  208. package/dist/workspace-mcp-serve-IBMTFQDY.js +0 -3
  209. package/dist/workspace-model-ZL6WCICX.js +0 -1
  210. package/dist/workspace-repair-engine-NX7I632M.js +0 -3
  211. package/dist/workspace-run-6GT5OBQ5.js +0 -1
@@ -0,0 +1,3 @@
1
+ import {c as c$2}from'./chunk-N4QFNOAI.js';import {d as d$3,i,j as j$1,k,h as h$1,m as m$2,n,o}from'./chunk-KQ2TMI26.js';import {a as a$2}from'./chunk-IQQMFRWM.js';import {a,c,h,b,e,j,g,d as d$2}from'./chunk-4WVOAX2V.js';import {m as m$1}from'./chunk-SVYY55IS.js';import {l,p}from'./chunk-GIQ4SDRJ.js';import {a as a$3}from'./chunk-ENZPM52J.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {p as p$1}from'./chunk-EHCKITR4.js';import {c as c$1}from'./chunk-XDPTAV2T.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$3,d as d$1}from'./chunk-EWZZUQBR.js';import {e as e$1}from'./chunk-ZGHJIQXL.js';import {c as c$4,b as b$1}from'./chunk-5TY74LLW.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import d from'path';import {execa}from'execa';import m from'fs-extra';var Le=".workspai/repair",Ma="transaction.json",_a="source-plan.json",ka="checkpoint",La="engine.lock",Ia=5*1024*1024,Ga=25*1024*1024,za=25*1024*1024,Aa=4*1024*1024,Ka=900*1e3,Va=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),Ja=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"]),G={safe:0,guarded:1,invasive:2},Ua=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 Ya(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function O(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${C(e).slice(0,16)}`,message:r.message??e}]}}function Ea(e){let a=new Map,r=t=>a.set(Ya(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=We(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}:{}}),G[t.risk]>G[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(i=>i.invocation&&`tool:${i.invocation.cwd}:${i.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:${C(t).slice(0,16)}`,message:t});}return [...a.values()]}function H(e){return (e?.()??new Date).toISOString()}function C(e){return createHash("sha256").update(e).digest("hex")}function K(e){return Array.isArray(e)?`[${e.map(K).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)}:${K(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function wa(e){return C(K({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function $a(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=wa(a),t=(await jt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&wa(o)===r);if(t)return await re(d.join(e,b),t),t}var He="causal-action-integrity:";function Sa(e){return C(K([...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 Ca(e){if(e.length===0)return;let a=Sa(e);return {id:`${He}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Xa(e){return K({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function ba(e){return new Set(e.map(Xa))}function I(e,a){let r=d.relative(d.resolve(e),d.resolve(a));return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}async function z(e,a){let r=await m.realpath(e).catch(()=>d.resolve(e)),t=d.resolve(a);for(;!await m.pathExists(t);){let i=d.dirname(t);if(i===t)return false;t=i;}let o=await m.realpath(t).catch(()=>d.resolve(t));return I(r,o)}function te(e,a,r){let t=d.isAbsolute(a)?d.resolve(a):d.resolve(e,a);if(!I(e,t)&&!(r&&I(d.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!I(e,t)&&r){let o=d.resolve(r),i=d.relative(o,t).split(d.sep).join("/"),n=`external/${d.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return d.relative(e,t).split(d.sep).join("/")||"."}function X(e){let a=e.replaceAll("\\","/").replace(/^\.\//,""),r=/^external\/([^/]+)(?:\/(.*))?$/.exec(a);if(!r)return;let t=r[2]??"";if(!t.split("/").some(o=>o===".."))return {root:`external/${r[1]}`,suffix:t}}async function T(e){if(d.isAbsolute(e.value))return d.resolve(e.value);let a=X(e.value);if(!a)return d.resolve(e.workspacePath,e.value);if(e.projectBoundary)return d.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$1({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&d.basename(d.resolve(o.externalPath))===a.root.slice(9)||e.projectName!==void 0&&o.slug===e.projectName);if(!t?.externalPath)throw new Error(`Portable external project reference is not canonically registered: ${a.root}`);return d.resolve(t.externalPath,a.suffix||".")}function je(e,a,r,t){let o=te(e,a,r),i=X(o);return !i||!t?o:i.suffix?`${t}/${i.suffix}`:t}async function Za(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&I(e.workspacePath,a)&&!X(e.proposal.projectPath??""))return a;let{contract:t}=await p$1({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?d.resolve(i.externalPath):d.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,u=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&u});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?d.resolve(o.externalPath):d.resolve(e.workspacePath,o.relativePath)}function ce(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return d.join(e,Le,"transactions",a)}async function ae(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return d.join(ce(e,a),Ma)}function Ge(e,a){return d.join(ce(e,a),_a)}async function re(e,a){await m.ensureDir(d.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await m.writeJson(r,a,{spaces:2}),await m.move(r,e,{overwrite:true});}function E(e,a,r,t={}){let o={sequence:e.events.length+1,at:H(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r};e.events.push(o);let i=t.status??a,n=a==="failed"||i==="failed"?"failed":a==="cancelled"?"cancelled":a==="closed"||i==="passed"||i==="completed"?"succeeded":a==="rollback"?"rolled-back":i==="blocked"?"blocked":"running";t.stageId?c$4({blockId:`repair.${t.stageId}`,status:n,message:r,component:"workspace-repair",attributes:{transactionId:e.transactionId,repairEventType:a}}):b$1({kind:n==="failed"?"operation.failed":n==="succeeded"||n==="rolled-back"?"operation.completed":"operation.started",status:n,component:"workspace-repair",message:r,correlationId:e.transactionId,attributes:{repairEventType:a}});}async function x(e,a,r){a.revision+=1,a.updatedAt=H(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(d.join(e,b),a);}async function le(e){let a$2=await m.readJson(Se(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function Ce(e,a){return await m.readJson(Ge(e,a))}function ne(e){return e.schemaVersion===d$2}async function de(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=await T({workspacePath:e,value:t,projectBoundary:r,projectName:a.projectName});if(!I(e,o)&&!X(t)&&!(r&&d.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:te(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Oe(e){return m.readFile(e,"utf8").catch(()=>"")}async function Qa(e){return m.readJson(e).catch(()=>({}))}function va(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function et(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=d.extname(e).length>0;return (process.env.PATH??"").split(d.delimiter).filter(Boolean).flatMap(t=>r?[d.join(t,e)]:a.map(o=>d.join(t,`${e}${o}`)))}function Pa(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ya(e,a){try{let r=await execa(e,["--version"],{cwd:a,shell:false,reject:false,timeout:5e3,maxBuffer:65536,stdin:"ignore"});return r.exitCode!==void 0&&r.exitCode!==null}catch{return false}}async function Wa(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(d.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=d.isAbsolute(r)?r:d.resolve(a,r),o=await m.stat(t).catch(()=>{});return Pa(o)&&ya(t,a)}for(let t of et(r)){let o=await m.stat(t).catch(()=>{});if(Pa(o)&&await ya(t,a))return true}return false}async function ze(e){let a=new Set;for(let i of e.stages){if(i.kind!=="repair"||!i.invocation)continue;let n=Te(i.invocation.executable);if(!["python","python3","py"].includes(n)||!i.invocation.args.includes("venv")||!i.invocation.args.includes(".venv"))continue;let s=await T({workspacePath:e.workspacePath,value:i.invocation.cwd});a.add(d.normalize(d.join(s,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(i=>i.required&&i.status!=="skipped"&&i.invocation).map(i=>i.invocation),t=new Map;for(let i of r)t.set(`${i.cwd}\0${i.executable}`,i);let o=[];for(let i of t.values()){let n=await T({workspacePath:e.workspacePath,value:i.cwd}),s=d.isAbsolute(i.executable)?d.normalize(i.executable):d.normalize(d.resolve(n,i.executable));if(a.has(s)){o.push({id:`tool:${i.cwd}:${i.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${i.executable} (${i.cwd}).`});continue}let u=await Wa({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:u?"passed":"failed",message:u?`Required repair executable is available: ${i.executable} (${i.cwd}).`:`Required repair executable is unavailable: ${i.executable} (${i.cwd}). Install or configure it, then create a fresh plan.`});}return o}function oe(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function P(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 at(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 tt(e){let a=await de(e.workspacePath,e.action,e.authorizedProjectRoot),r=X(e.action.projectPath??"")?.root??te(e.workspacePath,a,a),t=async g=>m.pathExists(d.join(a,g)),o=new Set,i=[],n=[],s=g=>`${r}:${e.adapterId}:${g}`,u=g=>g.forEach(f=>o.add(te(e.workspacePath,d.join(a,f),a))),c=g=>{i.push(g),g.required&&g.status==="blocked"&&n.push(g.summary);},p=at(e.workspacePath,a,e.action),k=()=>{let g$1=g.find(f=>f.id===e.adapterId);if(!g$1)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:g$1.id,ecosystem:g$1.ecosystem,projectPath:r,manifests:g$1.manifests,support:g$1.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(f=>f.required&&f.invocation).map(f=>f.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${g$1.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let g=await Qa(d.join(a,"package.json")),f=g.scripts&&typeof g.scripts=="object"&&!Array.isArray(g.scripts)?g.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",B=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";u(["package.json",B]),c(P({id:s("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 V=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 c(P({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:p??V})),c(typeof f.test=="string"&&f.test.trim()?P({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):oe(s("test"),"test","No test script is declared.")),c(typeof f.build=="string"&&f.build.trim()?P({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):oe(s("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){u(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let g=e.action.transaction?.ecosystem.toLowerCase(),f=d.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=f==="uv"||g==="uv"||await t("uv.lock"),B=!b&&(f==="poetry"||g==="poetry"||await t("poetry.lock")),V=!b&&!B&&["python","python3","py"].includes(f)&&(e.action.invocation?.args??[]).some(M=>M==="venv")&&(e.action.invocation?.args??[]).some(M=>M===".venv"),W=process.platform==="win32"?"python":"python3",D=d.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await m.pathExists(D)||V)&&(W=D);let _=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):B?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:_})),c(P({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:p}));let L=await Oe(d.join(a,"pyproject.toml")),pe=await t("tests")||/\[tool\.pytest/i.test(L),Z=v(B?{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:W,args:["-m","pytest"],purpose:"test"}),se=v(B?{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:W,args:["-m","build"],purpose:"build"});return c(pe?P({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:Z}):oe(s("test"),"test","No Python test surface is declared.")),c(/\[build-system\]/i.test(L)?P({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:se}):oe(s("build"),"build","No Python build contract is declared.")),k()}let w=[{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 g of w){if(g.adapterId!==e.adapterId)continue;let f=await t(g.manifest)?g.manifest:g.alternateManifest&&await t(g.alternateManifest)?g.alternateManifest:void 0;if(!f)continue;u(g.files),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${f} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.reconcile[0],args:g.reconcile[1],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:p??(g.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:g.audit[0],args:g.audit[1],purpose:"audit"}):void 0)}));let b=await Oe(d.join(a,f)),B=g.manifest==="composer.json"||g.adapterId==="deno"?/["']test["']\s*:/.test(b):g.manifest==="Gemfile"?await t("Rakefile"):true,V=g.manifest==="composer.json"||g.manifest==="deno.json"?/["']build["']\s*:/.test(b):g.manifest==="Gemfile"?(await m.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return c(B?P({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.test[0],args:g.test[1],purpose:"test"})}):oe(s("test"),"test","No test contract is declared.")),c(V?P({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.build[0],args:g.build[1],purpose:"build"})}):oe(s("build"),"build","No build contract is declared.")),k()}let j=await m.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&j.some(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g)))return u(["Directory.Packages.props","packages.lock.json",...j.filter(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g))]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:p??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),c(P({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),c(P({id:s("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 y=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return u(["pom.xml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["dependency:resolve"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["package","-DskipTests"],purpose:"build"})})),k();let $=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&$){let g=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return u([$,"gradle.lockfile","gradle/libs.versions.toml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["dependencies"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["build","-x","test"],purpose:"build"})})),k()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let g=q==="deps.edn",f=await Oe(d.join(a,q)),b=g?"clojure":"lein";u([q]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-P"]:["deps"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:p}));let B=!g||/:test\b/.test(f);return c(B?P({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-M:test"]:["test"],purpose:"test"})}):oe(s("test"),"test","No Clojure :test alias is declared.")),c(g?oe(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):P({id:s("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")?(u(["build.sbt"]),c(P({id:s("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"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),c(P({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),k())}async function Ta(e){let a=i=>m.pathExists(d.join(e,i)),r=await m.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(i=>/\.(?:cs|fs|vb)proj$|\.slnx?$/i.test(i))&&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(g.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function rt(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 Na(e,a={}){let r=await de(e.workspacePath,e.action,e.authorizedProjectRoot),t=X(e.action.projectPath??"")?.root??te(e.workspacePath,r,r),o=await Ta(r),i=rt(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let c=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[P({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:i,ecosystem:g.find(p=>p.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:c}]}}if(n.length===0){let c=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[P({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:c}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let c of n){let p=await tt({...e,adapterId:c});s.stages.push(...p.stages),s.checkpointFiles.push(...p.checkpointFiles),s.blockers.push(...p.blockers),s.adapters.push(...p.adapters);}s.stages=[...new Map(s.stages.map(c=>[c.id,c])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let u=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let c=new Set(e.action.transaction.requiredStages),p=Te(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],w=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(p)&&k.includes("venv")&&k.includes(".venv");w&&u.add(d.normalize(d.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(j=>j.kind==="reconcile"?w&&c.has("reconcile"):c.has(j.kind)),s.blockers=s.stages.filter(j=>j.required&&j.status==="blocked").map(j=>j.summary);}for(let c of s.adapters){let p=s.stages.filter(w=>w.id.startsWith(`${c.projectPath}:${c.adapterId}:`)),k=[];c.requiredExecutables=[...new Set(p.filter(w=>w.required&&w.invocation).map(w=>w.invocation.executable))];for(let w of p){if(!w.required||!w.invocation)continue;let j=await T({workspacePath:e.workspacePath,value:w.invocation.cwd,projectBoundary:r}),y=d.isAbsolute(w.invocation.executable)?d.normalize(w.invocation.executable):d.normalize(d.resolve(j,w.invocation.executable));u.has(y)||await Wa({workspacePath:e.workspacePath,invocation:w.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||k.push(w.invocation.executable);}c.missingExecutables=[...new Set(k)],c.missingExecutables.length>0&&(c.status="partial",c.message=`Required executable(s) unavailable: ${c.missingExecutables.join(", ")}.`);}if(n.length===1){let c=`:${n[0]}:`;for(let p of s.stages)p.id=p.id.replace(c,":");}return s}async function Xt(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=d.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let i=e.project.trim(),n=await m$1(r),s=i.replace(/\\/g,"/").replace(/^\.\//,""),u=d.resolve(r,i),c=n.resolved.filter(p=>{let k=I(r,p.projectPath)?te(r,p.projectPath):void 0;return p.name===i||k===s||d.resolve(p.projectPath)===u});if(c.length===0){let p=n.skipped.find(k=>k.name===i);throw p?new Error(`Registered project is unavailable for repair capability inspection: ${i} (${p.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i}.`)}if(c.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i}.`);t=d.resolve(c[0].projectPath),o=c[0].name;}else {if(t=d.resolve(r,e.projectPath??"."),!I(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=te(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ta(t)}}}function We(e){if(e.command){let a=d$3(e.command);if(a)return a}return a$4(e.operation)??void 0}async function ot(e){let a=new Set,r=e.actions[0]?await de(e.workspacePath,e.actions[0]):void 0,t=X(e.actions[0]?.projectPath??"")?e.actions[0]?.projectPath:void 0;for(let o of e.dependencyFiles){let i=await T({workspacePath:e.workspacePath,value:o,projectBoundary:r,projectName:e.actions[0]?.projectName});a.add(je(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await de(e.workspacePath,o),n=X(o.projectPath??"")?i:e.workspacePath;if(!await z(n,i))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${i}`);let s=o.transaction?.kind==="dependency-materialization"&&o.transaction.sourceMutationRequired===false;for(let p of s?[]:o.files){let k=await T({workspacePath:e.workspacePath,value:p,projectBoundary:X(p)?i:void 0,projectName:o.projectName});if(!await z(n,k))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${p}`);a.add(je(e.workspacePath,k,i,X(o.projectPath??"")?o.projectPath:void 0));}let u=We(o);if(!u)continue;let c="path"in u?u.path:void 0;if(c){let p=d.resolve(i,c);if(!await z(n,p))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${c}`);a.add(je(e.workspacePath,p,i,X(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function st(e,a){if(!a.invocation)return;let r=await de(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ke(e){return C(K({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 Ve(e){return Ke({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})}function qa(e){return C(K({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Zt(e){let a=d.resolve(e.workspacePath),r=await le({workspacePath:a,transactionId:e.transactionId}),t=await Ce(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Ve(r)!==r.integrity.planHash||!r.integrity.closureHash||qa(r)!==r.integrity.closureHash||C(K(t))!==r.integrity.sourceEvidenceHash||!ne(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=await ae(a,r);for(let i of r.checkpoint.files){let n=await T({workspacePath:a,value:i.path,projectBoundary:o,projectName:r.target.projectName});if(!I(a,n)&&!(o&&I(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await m.lstat(n).catch(()=>{});if(!s){if(i.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${i.path}`);continue}if(!s.isFile()||s.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${i.path}`);let u=await m.readFile(n);if(i.afterHash!==C(u))throw new Error(`Goal repair output changed after transaction closure: ${i.path}`);if(i.mode!==void 0&&s.mode!==i.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${i.path}`)}return r.verification.sourceBinding}async function $e(e,a,r){let t=[],o=[],i=0;for(let n of a){let s=await T({workspacePath:e,value:n,projectBoundary:r}),u=r&&I(d.resolve(r),s)?d.resolve(r):e;if(!I(u,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await z(u,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let c=await m.lstat(s).catch(()=>{});if(c?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(c&&!c.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(c&&c.size>Ia){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=c?.size??0,i>Ga){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=c?await m.readFile(s):void 0;t.push({path:n,existed:!!c,beforeHash:p?C(p):null,...c?{mode:c.mode}:{}});}return {entries:t,errors:o}}function Ba(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."}function it(e,a){if(!(!/\.json$/i.test(e)||a===void 0))try{JSON.parse(a);return}catch{return `${e} must contain valid JSON; comments and trailing syntax are not allowed.`}}async function nt(e){let a=await m.readJson(d.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():d.basename(e)}function ct(e){return Va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function dt(e,a){let r=d.resolve(e,a),t=d.dirname(r);for(;I(e,t);){if((await m.readdir(t).catch(()=>[])).some(ct))return t;if(d.resolve(t)===d.resolve(e))break;t=d.dirname(t);}return e}function lt(e,a,r){return r.some(t=>{let o=d.resolve(e,t.path);if(!I(a,o))return false;let i=d.basename(o);return Ja.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function pt(e){let a=!I(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:te(e.workspacePath,e.projectPath,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 ut(e,a){let r=Te(a.executable),[t="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(r);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["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(s=>/^(?:test|build|check|verify|package)$/i.test(s))||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 ht(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let u=d.resolve(e.workspacePath,s.cwd),c=te(e.workspacePath,u,n),p=await m.lstat(u).catch(()=>{});if(!p?.isDirectory()||p.isSymbolicLink()||!await z(n??e.workspacePath,u)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!I(n,u)){t.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(G[s.risk]>G[e.maxRisk]){t.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:u,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Je(e.workspacePath,k,e.policy,e.projectRoots),ut(s,k);}catch(w){t.push(w instanceof Error?w.message:String(w));continue}a.push(P({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:k})),i.add(`${c}:${s.kind}`);}for(let s of e.projectRoots){let u=pt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),c=await Na({workspacePath:e.workspacePath,action:u,authorizedProjectRoot:s},e.dependencies);o.push(...c.adapters);let p=lt(e.workspacePath,s,e.proposal.changes);if(p){for(let w of c.checkpointFiles)r.add(w);t.push(...c.blockers);}let k=te(e.workspacePath,s,s);for(let w of c.stages)!p&&!["test","build"].includes(w.kind)||i.has(`${k}:${w.kind}`)||a.push(w);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function gt(e,a$3={}){let r=d.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(h=>h.cardId===e.cardId).filter(h=>!e.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),i=e.actionId?o.filter(h=>h.id===e.actionId):o,n=t.actions.filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),s=new Map(n.map(h=>[h.id,h])),u=h=>{let R=new Set(h.map(J=>J.id)),F=[...h];for(;F.length>0;){let J=F.pop();for(let U of J?.dependsOn??[]){let Y=s.get(U);!Y||R.has(Y.id)||(R.add(Y.id),F.push(Y));}}return n.filter(J=>R.has(J.id))},c$1=i.filter(h=>h.findingStatus==="blocking"||h.notes.includes("Doctor finding status: blocking")),p=c$1.length>0?c$1:i.filter(h=>h.findingStatus!=="informational"),k=e.actionId?i.filter(h=>h.id===e.actionId):[],w=[...p].sort((h,R)=>{let F=h.status==="ready"||h.status==="review-required"?0:1,J=R.status==="ready"||R.status==="review-required"?0:1;return F-J||h.order-R.order||h.id.localeCompare(R.id)})[0],j=w?p.filter(h=>h.cardId===w.cardId&&h.findingId===w.findingId&&h.causalKey===w.causalKey&&h.projectName===w.projectName&&h.projectPath===w.projectPath):[],y=u(e.actionId?k:j),$=e.maxRisk??"guarded",q={maxRisk:$,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},g=[{id:"workspace-root",status:await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:y.length>0?"passed":"failed",message:y.length>0?`${y.length} governed action(s) selected.`:"No governed remediation action matches this target."}],f=Ca(y);f&&g.push(f);let b$1=[],B=[],V=[],W=[],D=new Set(["replan","manual-repair","cancel"]);for(let h of y){let R=We(h),F=await st(r,h);if(G[h.risk]<=G[$]||(W.push(`${h.id} exceeds the approved ${$} risk ceiling.`),D.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),(h.status==="blocked"||h.status==="guidance-only")&&W.push(`${h.id} is ${h.status}: ${h.blocker}`),!R&&!F&&W.push(`${h.id} has no typed operation or structured invocation.`),F)try{Je(r,F,q);}catch(U){let Y=U instanceof Error?U.message:String(U);W.push(Y),/Force-based/.test(Y)&&D.add("allow-force"),/Breaking dependency/.test(Y)&&D.add("allow-breaking");}if(b$1.push({id:`action:${h.id}`,kind:"repair",status:R||F?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,...F?{invocation:F}:{}}),h.transaction){let U=await Na({workspacePath:r,action:h},a$3);b$1.push(...U.stages),B.push(...U.checkpointFiles),W.push(...U.blockers),V.push(...U.adapters);}}let _=[...new Map(b$1.map(h=>[h.id,h])).values()];b$1.splice(0,b$1.length,..._),b$1.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$1.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$1.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),g.push(...await ze({workspacePath:r,stages:b$1,toolAvailable:a$3.toolAvailable}));let L=await ot({workspacePath:r,actions:y,dependencyFiles:B}),pe=y[0]?await de(r,y[0]):void 0,Z=await $e(r,L,pe);g.push({id:"rollback-coverage",status:y.some(h=>h.mode==="edit-file"||h.mode==="run-command")&&L.length===0?"failed":"passed",message:L.length>0?`${L.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),g.push({id:"structured-execution",status:b$1.some(h=>h.required&&h.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),g.push({id:"checkpoint-boundary",status:Z.errors.length===0?"passed":"failed",message:Z.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":Z.errors.join(" ")});let se=C(K(t)),M=[...new Set(y.map(h=>h.projectPath).filter(Boolean))],xe=[...new Set(y.map(h=>h.projectName).filter(Boolean))],ue=xe.length===1?xe[0]:void 0,Ie=M.length===1&&xe.length<=1,ie={cardId:e.cardId,scope:Ie?"project":"workspace",...ue?{projectName:ue}:{},...M.length===1?{projectPath:M[0]}:{},actionIds:y.map(h=>h.id)},ke=H(a$3.now),he=`repair_${randomUUID().replaceAll("-","")}`,Q=g.some(h=>h.status==="failed")||W.length>0,we=[...W,...g.filter(h=>h.status==="failed").map(h=>h.message)],be=[...new Map(V.map(h=>[`${h.projectPath}:${h.adapterId}`,h])).values()],l=Ea({actions:y,adapters:be,preconditions:g,stages:b$1,decisionOptions:D,maxRisk:$,fallbackReasons:we}),S={schemaVersion:a,transactionId:he,revision:1,createdAt:ke,updatedAt:ke,workspace:{name:t.workspace.name,rootRef:"."},target:ie,state:Q?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:g,adapterEvaluations:be,checkpoint:{status:L.length>0?"pending":"unavailable",files:Z.entries},stages:b$1,...Q?{decision:{reason:[...new Set(we)].join(" "),options:[...D],causes:l}}:{},events:[],integrity:{sourceEvidenceHash:se,planHash:Ke({sourceEvidenceHash:se,target:ie,policy:q,preconditions:g,adapterEvaluations:be,stages:b$1,checkpointFiles:Z.entries})}};E(S,"planned",Q?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let N=await $a(r,S);if(N)return N;let ge=ce(r,he);return await m.ensureDir(ge),await re(Ge(r,he),t),await re(Se(r,he),S),await re(d.join(r,b),S),S}async function ft(e,a={}){let r=e.proposal.goalId;if(!r)return Ra(e,a);let t=d.resolve(e.workspacePath);return c$1(t,`.workspai/goals/${r}/repair-proposal`,()=>Ra({...e,workspacePath:t},a))}async function Ra(e$1,a$3={}){a$1(e$1.proposal,e,"Workspace repair proposal");let r=d.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal));if(t.goalId){let l$1=await l({workspacePath:r,goalId:t.goalId});if(!l$1.active||l$1.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(l$1.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${l$1.goalPack?.state??"missing"}`);if((l$1.active.repairTransactionIds??(l$1.active.repairTransactionId?[l$1.active.repairTransactionId]:[])).length>=l$1.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${l$1.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(l$1.goalPack.scope.kind==="project"||l$1.goalPack.scope.kind==="project-set"){let N=l$1.goalPack.scope.projects;if(!t.projectName||!N.includes(t.projectName))throw new Error(l$1.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${N[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${N.join(", ")}).`)}}let o=e$1.maxRisk??"guarded",i={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},n=[],s=[],u=new Set(["replan","manual-repair","cancel"]),c$1=await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"));n.push({id:"workspace-root",status:c$1?"passed":"failed",message:c$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let p$1;try{p$1=await Za({workspacePath:r,proposal:t});}catch(l){s.push(l instanceof Error?l.message:String(l));}let k=p$1&&!I(r,p$1)&&t.projectName?`external/${t.projectName}`:void 0;if(p$1&&(t.projectName||t.projectPath)&&(t.projectPath=k??d.relative(r,p$1).split(d.sep).join("/")),t.projectPath){let l=p$1??d.resolve(r,t.projectPath),S=await m.lstat(l).catch(()=>{});(!S?.isDirectory()||S.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(l=>({...l,cwd:je(r,l.cwd,p$1,k)}));let w=new Set,j=new Set,y=0;for(let l of t.changes){l.path=je(r,l.path,p$1,k),l.path==="."&&s.push(`${l.id} cannot replace the workspace root.`),w.has(l.id)&&s.push(`Duplicate proposal change id: ${l.id}.`),j.has(l.path)&&s.push(`Multiple proposal changes target ${l.path}.`),w.add(l.id),j.add(l.path),y+=Buffer.byteLength(l.content??"","utf8"),y>za&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let S=Ba(l.path);if(S&&s.push(`${l.path}: ${S}`),l.operation==="write"){let N=it(l.path,l.content);N&&s.push(N);}if(G[l.risk]>G[o]&&(s.push(`${l.id} exceeds the approved ${o} risk ceiling.`),u.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let N=p$1??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ge=await T({workspacePath:r,value:l.path,projectBoundary:N,projectName:t.projectName});I(N,ge)||s.push(`${l.path} escapes the declared project scope.`);}}let $=[...j].sort(),q=await $e(r,$,p$1);s.push(...q.errors);let g=new Map(q.entries.map(l=>[l.path,l]));for(let l of t.changes){let S=g.get(l.path);if(!S||S.beforeHash!==l.expectedBeforeHash){s.push(`${l.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}l.operation==="delete"&&!S.existed&&s.push(`${l.path} cannot be deleted because it does not exist.`),l.operation==="write"&&S.beforeHash!==null&&C(l.content??"")===S.beforeHash&&s.push(`${l.path} is a no-op and cannot prove source progress.`);}n.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let f=new Set;if(t.projectPath)f.add(p$1??d.resolve(r,t.projectPath));else for(let l of t.changes)f.add(await dt(r,l.path));let b$1=await ht({workspacePath:r,proposal:t,projectRoots:[...f].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...b$1.blockers);let B=b$1.stages,V=B.some(l=>l.status!=="skipped"&&["audit","test","build"].includes(l.kind));n.push({id:"validation-coverage",status:V?"passed":"unknown",message:V?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let W=[...new Set([...$,...b$1.checkpointFiles])].sort(),D=await $e(r,W,p$1);s.push(...D.errors),n.push({id:"checkpoint-boundary",status:D.errors.length===0?"passed":"failed",message:D.errors.length===0?`${D.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:D.errors.join(" ")});let _=[{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(l=>({id:`proposal:${l.id}`,kind:"repair",status:G[l.risk]<=G[o]?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,changedPaths:[l.path]})),...B,{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."}];n.push(...await ze({workspacePath:r,stages:_,toolAvailable:a$3.toolAvailable}));let L=new Set(_.map(l=>l.id));L.size!==_.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:L.size===_.length?"passed":"failed",message:L.size===_.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let l=false,S=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),N=S.actions.filter(A=>A.cardId===t.cardId&&(!t.projectName||A.projectName===t.projectName)&&(!t.projectPath||A.projectPath===t.projectPath));if(!t.targetActionIds?.length){let A=ba(N);A.size===1?t.targetActionIds=N.map(Oa=>Oa.id).sort():A.size>1&&(l=true,s.push(`Repair proposal target is ambiguous: ${A.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ge=[...new Set(t.targetActionIds??[])],h=new Set(ge),R=S.actions.filter(A=>h.has(A.id)),F=new Set(R.map(A=>A.id)),J=ge.filter(A=>!F.has(A));J.length>0&&(l=true,s.push(`Repair proposal references stale or unknown causal action ids: ${J.join(", ")}.`)),R.filter(A=>A.cardId!==t.cardId||t.projectName!==void 0&&A.projectName!==t.projectName||t.projectPath!==void 0&&A.projectPath!==t.projectPath).length>0&&(l=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let Y=ba(R);Y.size>1&&(l=true,s.push(`Repair proposal combines ${Y.size} independent causal finding families. Create one transaction per finding family.`)),R.length>0&&!t.blockerSignature&&(l=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(R.map(A=>A.projectName??A.projectPath).filter(A=>!!A)).size>0&&!t.projectName&&!t.projectPath&&(l=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),R.length>0&&R.every(A=>A.mode==="run-command"&&A.transaction?.kind==="dependency-materialization"&&A.transaction.sourceMutationRequired===false)&&(l=true,s.push("The selected causal action is command-owned and declares that source mutation is not required. Execute the canonical action instead of submitting a model source proposal.")),n.push({id:"causal-target-binding",status:!l&&(R.length>0||N.length===0)?"passed":"failed",message:R.length>0?`${R.length} action(s) bind this proposal to one canonical causal target.`:N.length===0?"No canonical remediation action exists; the bounded source proposal remains the explicit target.":"A single canonical causal target is required before source mutation."});let Ue=Ca(R);Ue&&n.push(Ue);}catch{}let pe=C(K(t)),Z={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(l=>`proposal:${l.id}`)},se=H(a$3.now),M=`repair_${randomUUID().replaceAll("-","")}`,ue=n.some(l=>l.status==="failed")||s.length>0,Ie=[...s,...n.filter(l=>l.status==="failed"&&l.id!=="proposal-boundary").map(l=>l.message)],ie=Ea({adapters:b$1.adapters,preconditions:n,stages:_,decisionOptions:u,maxRisk:o,fallbackReasons:Ie});for(let l of t.changes)G[l.risk]<=G[o]||ie.push({kind:"risk-approval",id:`risk:${l.id}`,message:`${l.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let ke=ie.length>0&&ie.every(l=>l.kind==="failed-precondition")&&n.some(l=>l.id==="proposal-boundary"&&l.status==="failed"),he=ke?["replan","cancel"]:[...u],Q={schemaVersion:a,transactionId:M,revision:1,createdAt:se,updatedAt:se,workspace:{name:await nt(r),rootRef:"."},target:Z,state:ue?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:b$1.adapters,checkpoint:{status:"pending",files:D.entries},stages:_,...ue?{decision:{reason:[...new Set(Ie)].join(" "),options:he,causes:ie}}:{},events:[],integrity:{sourceEvidenceHash:pe,planHash:Ke({sourceEvidenceHash:pe,target:Z,policy:i,preconditions:n,adapterEvaluations:b$1.adapters,stages:_,checkpointFiles:D.entries})}};E(Q,"planned",ue?ke?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(Q,c,"Workspace repair transaction");let we=await $a(r,Q);if(we)return we;let be=ce(r,M);return await m.ensureDir(be),await re(Ge(r,M),t),await re(Se(r,M),Q),await re(d.join(r,b),Q),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:M}),Q}async function Qt(e,a={}){let r=await le(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Ve(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=O("The compiled repair plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return C(K(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=O("The persisted source plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:H(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",E(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await x(e.workspacePath,r,a.now),r)}async function Da(e,a){let r=d.join(e,Le,La);await m.ensureDir(d.dirname(r));try{let t=await m.stat(r),o=await m.readJson(r).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,n=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&n)try{process.kill(n,0),s=true;}catch(c){s=c!==null&&typeof c=="object"&&"code"in c&&c.code==="EPERM";}let u=!!(i&&i!==hostname());!s&&!u&&Date.now()-t.mtimeMs>Ka&&await m.remove(r);}catch{}try{await m.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 m.readJson(r).catch(async()=>{let o=await m.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await m.remove(r);}}async function Fa(e){let a=await ae(e.workspacePath,e.transaction),r=await $e(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let i=t.get(o.path);if(!i||o.existed!==i.existed||o.beforeHash!==i.beforeHash||o.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function mt(e){if(e.transaction.checkpoint.status==="captured")return;await Fa(e);let a=d.join(ce(e.workspacePath,e.transaction.transactionId),ka);await m.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=await ae(e.workspacePath,e.transaction),i=await T({workspacePath:e.workspacePath,value:t.path,projectBoundary:o,projectName:e.transaction.target.projectName}),n=t.existed?await m.readFile(i):void 0;if(n&&C(n)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let s=`${ka}/${String(r).padStart(4,"0")}.bin`;if(n){let u=d.join(ce(e.workspacePath,e.transaction.transactionId),s),c=`${u}.${process.pid}.${randomUUID()}.tmp`;await m.writeFile(c,n,{flag:"wx"});let p=await m.readFile(c);if(C(p)!==t.beforeHash)throw await m.remove(c),new Error(`Checkpoint backup verification failed for ${t.path}.`);await m.move(c,u,{overwrite:true}),t.backupRef=s;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=H(e.now),e.transaction.state="checkpointed",E(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function ja(e,a){let r=await ae(e,a);for(let t of a.checkpoint.files){let o=await T({workspacePath:e,value:t.path,projectBoundary:r,projectName:a.target.projectName}),i=await m.readFile(o).catch(()=>{});t.afterHash=i?C(i):null;}}function Te(e){return d.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Je(e,a,r,t=[]){let o=d.resolve(e,a.cwd);if(!(I(e,o)||t.some(c=>I(c,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(c=>!c||/[\0\r\n]/.test(c)))throw new Error("Invocation contains invalid arguments.");let n=Te(a.executable),s=d.isAbsolute(a.executable),u=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!I(e,a.executable)&&!t.some(c=>I(c,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!s&&!u&&!Ua.has(n))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(c=>/^(?:--force|-f)$/i.test(c)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(c=>/(?:breaking|legacy-peer-deps)/i.test(c)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(n)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${n} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function Me(e){let a=e.projectBoundary?[d.resolve(e.projectBoundary)]:[],r=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary}),t=Je(e.workspacePath,{...e.invocation,cwd:r},e.policy,a),o=await m.lstat(t.cwd).catch(()=>{});if(!o?.isDirectory()||o.isSymbolicLink()||!await z(e.projectBoundary??e.workspacePath,t.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(d.isAbsolute(t.executable)||/^\.{1,2}[\\/]/.test(t.executable)){let s=d.isAbsolute(t.executable)?t.executable:d.resolve(t.cwd,t.executable);if(!await z(e.projectBoundary??e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),n=await execa(t.executable,e.invocation.args,{cwd:t.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:Aa,stdin:"ignore",extendEnv:false,env:{...i,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:n.exitCode??null,stdout:n.stdout??"",stderr:n.stderr??""}}function kt(e){let a=j.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 wt(e){let a=j.find(p=>p.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 m.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?await T({workspacePath:e.workspacePath,value:e.transaction.target.projectPath,projectName:e.transaction.target.projectName}):d.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.`);let o=a.scope==="project"?t:e.workspacePath;if(!await z(o,t))throw new Error("The target producer working directory escapes the workspace boundary.");let i=d.resolve(t,a.producerArtifact);if(!I(t,i)||!await z(t,d.dirname(i)))throw new Error("The target producer artifact escapes its canonical scope.");let n=await m.stat(i).catch(()=>{}),s=Object.fromEntries(Object.entries(process.env).filter(([p])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(p))),u=await execa(process.execPath,[r,...kt(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:Aa,stdin:"ignore",extendEnv:false,env:{...s,NO_COLOR:"1",CI:process.env.CI??"1"}}),c=await m.stat(i).catch(()=>{});return {exitCode:u.exitCode??null,stdout:u.stdout??"",stderr:u.stderr??"",evidenceProduced:!!(c?.isFile()&&(!n||c.mtimeMs!==n.mtimeMs||c.ctimeMs!==n.ctimeMs||c.size!==n.size))}}async function bt(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$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=ne(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=ne(e.sourcePlan)?a.actions.filter(i=>t?r.has(i.id):i.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||i.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||i.projectPath===e.transaction.target.projectPath)):a.actions.filter(i=>r.has(i.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(i=>i.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function vt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(u=>!u.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(u=>u.id)),o=a.filter(u=>!t.has(u)),i=e.transaction.preconditions.map(u=>u.id).find(u=>u.startsWith(He))?.slice(He.length),n=r.actions.filter(u=>t.has(u.id)&&a.includes(u.id)),s=o.length===0&&!!i&&Sa(n)!==i;return {current:o.length===0&&!s,missingActionIds:o,semanticDrift:s}}function ee(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function Pt(e,a){if(a.type==="file-create")return i({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$1({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m$2({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 yt(e){let a=await ae(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!I(a,r)||!await z(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Ba(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(k=>k.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await m.readFile(r).catch(()=>{}),n=i?C(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await m.lstat(r).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!s)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await m.remove(r);return}let u=e.change.content??"";if(Buffer.byteLength(u,"utf8")>Ia)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await m.ensureDir(d.dirname(r));let c=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await m.writeFile(c,u,{encoding:"utf8",flag:"wx"}),await m.move(c,r,{overwrite:true});let p=await m.readFile(r);if(C(p)!==C(u))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function xa(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=H(e.dependencies.now),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await x(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:""}):wt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=ee(r.stdout),e.stage.stderrTail=ee(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=ee(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await vt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let i=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${i} 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 yt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=We(a.action);if(r){let t=await de(e.workspacePath,a.action),o=await ae(e.workspacePath,e.transaction)??e.workspacePath;if(!await z(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await Pt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=ee(t.stdout),e.stage.stderrTail=ee(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??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=ee(a.stdout),e.stage.stderrTail=ee(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=H(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 ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false}}async function Re(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",E(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=O(n,["manual-repair","cancel"]),E(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ae(e.workspacePath,e.transaction)??e.workspacePath;for(let n of e.transaction.checkpoint.files){let s=await T({workspacePath:e.workspacePath,value:n.path,projectBoundary:o,projectName:e.transaction.target.projectName});if(!I(o,s)||!await z(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let u=await m.lstat(s).catch(()=>{});if(u?.isSymbolicLink()||u&&!u.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let c=u?await m.readFile(s):void 0,p=c?C(c):null,k=n.afterHash!==void 0&&p===n.afterHash,w=a&&p===n.beforeHash;if(!k&&!w)return r(`Rollback refused because ${n.path} changed outside this transaction.`);if(!n.existed){t.push({entry:n,absolute:s});continue}if(!n.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${n.path}.`);let j=d.join(ce(e.workspacePath,e.transaction.transactionId),n.backupRef),y=await m.lstat(j).catch(()=>{});if(!y?.isFile()||y.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let $=await m.readFile(j);if(C($)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:$});}for(let n of t){if(!n.entry.existed){await m.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let u=d.join(d.dirname(n.absolute),`.${d.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await m.ensureDir(d.dirname(n.absolute)),await m.writeFile(u,s,{flag:"wx"}),n.entry.mode!==void 0&&await m.chmod(u,n.entry.mode),await m.move(u,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=H(e.dependencies.now);let i=e.transaction.stages.filter(n=>n.kind==="reconcile"&&n.invocation);for(let n of i){let s=n.invocation;if(!s)continue;let u=`rollback:${n.id}`,c=e.transaction.stages.find(w=>w.id===u&&w.kind==="rollback"),p=c??{id:u,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};c||e.transaction.stages.push(p),p.status="running",p.startedAt=H(e.dependencies.now),delete p.completedAt,delete p.exitCode,delete p.stdoutTail,delete p.stderrTail,E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let k;try{k=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});}catch(w){k={exitCode:null,stdout:"",stderr:w instanceof Error?w.message:String(w)};}if(p.exitCode=k.exitCode,p.stdoutTail=ee(k.stdout),p.stderrTail=ee(k.stderr),p.completedAt=H(e.dependencies.now),k.exitCode!==0)return p.status="failed",p.summary=k.stderr||k.stdout||`Rollback reconciliation exited with ${k.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=O(`Source files were restored, but the installed dependency tree could not be reconciled: ${p.summary}`,["manual-repair","cancel"]),E(e.transaction,"decision",e.transaction.decision.reason,{stageId:p.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false;p.status="passed",p.summary="Installed dependency tree reconciled with the restored source state.",E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,E(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}async function er(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({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(Ve(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let i=await Ce(r,e.transactionId);if(C(K(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;if(o.state==="approved"&&ne(i)&&i.goalId){let f=await l({workspacePath:r,goalId:i.goalId}),b=f.active?.repairTransactionIds??(f.active?.repairTransactionId?[f.active.repairTransactionId]:[]);if(f.index.activeGoalId!==i.goalId||!b.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let s=(await ze({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(s){let f=o.stages.find(b=>b.invocation&&`tool:${b.invocation.cwd}:${b.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=O(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...f?{executable:f}:{}}),E(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await x(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 Re({workspacePath:r,transaction:o,dependencies:a}),o}let u=new Map(ne(i)?i.changes.map(f=>[`proposal:${f.id}`,{kind:"proposal",change:f}]):i.actions.map(f=>[`action:${f.id}`,{kind:"canonical",action:f}]));try{await Fa({workspacePath:r,transaction:o});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await x(r,o,a.now),o}let c=o.stages.find(f=>f.id==="target-precondition");if(!c)return o.approval.status="expired",o.state="decision-required",o.decision=O("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await x(r,o,a.now),o;if(!await xa({workspacePath:r,transaction:o,stage:c,actions:u,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=O(`Target precondition failed before checkpoint: ${c.summary}`,["cancel"]),E(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await x(r,o,a.now),o;try{await mt({workspacePath:r,transaction:o,now:a.now});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await x(r,o,a.now),o}o.state="executing",await x(r,o,a.now);for(let f of o.stages.filter(b=>b.id!=="target-precondition"&&b.id!=="canonical-verify"&&b.kind!=="rollback"))if(!await xa({workspacePath:r,transaction:o,stage:f,actions:u,dependencies:a})&&f.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(`Required stage ${f.id} failed: ${f.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(f=>f.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=H(a.now),E(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await x(r,o,a.now);let w;try{w=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(f){w={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},k.stderrTail=ee(f instanceof Error?f.message:String(f));}let j=w.status==="passed"&&w.exitCode===0?"passed":w.status==="failed"||w.exitCode===1?"failed":"blocked",y=await bt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:j}),$=y.status==="passed"&&j!=="failed",q,g;if($&&ne(i)&&i.goalId){let f=await a$3(r);if(f.status==="miss")$=false,g=`Goal-bound repair could not seal its post-repair Model/Graph source state (${f.reason}).`;else {let b=f.graph.source.inputs?.hash;b?q={modelHash:d$1(f.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$3(f.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:b}:($=false,g="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return k.status=$?"passed":"failed",k.completedAt=H(a.now),k.exitCode=w.exitCode,k.summary=$&&j==="passed"?"Selected repair target and canonical workspace verification passed.":$?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":g||(y.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${j}.`),o.verification={status:$?"passed":"failed",targetStatus:y.status,workspaceStatus:j,remainingActionIds:y.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:w.exitCode,summary:k.summary,...q?{sourceBinding:q}:{}},E(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),$?(o.state="closed",delete o.decision,E(o,"closed",k.summary,{status:"passed",now:a.now}),o.integrity.closureHash=qa(o),await x(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Rt(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({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 Re({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ar(e,a={}){let r=await le(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,E(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await x(e.workspacePath,r,a.now),r}async function tr(e,a={}){let r=d.resolve(e.workspacePath),t=await le({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 Rt({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,E(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 x(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,E(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await x(r,t,a.now);let i={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(ne(o))return ft({workspacePath:r,proposal:o,...i},a);let n=t.target.actionIds.map(s=>s.startsWith("action:")?s.slice(7):s);return gt({workspacePath:r,cardId:t.target.cardId,...n.length===1?{actionId:n[0]}:{},projectName:t.target.projectName,...i},a)}async function jt(e){let a=d.join(e,Le,"transactions"),r=await m.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>le({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Qt as approveWorkspaceRepair,Zt as assertClosedGoalRepairTransactionCurrent,ar as cancelWorkspaceRepair,tr as decideWorkspaceRepair,kt as exactCardProducerArgs,er as executeWorkspaceRepair,Xt as inspectWorkspaceRepairCapabilities,jt as listWorkspaceRepairTransactions,gt as planWorkspaceRepair,ft as planWorkspaceRepairProposal,le as readWorkspaceRepairTransaction,Rt as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-Y35VLVF6.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-OCNPOYMA.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-NOV6723U.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-YYY2WXOH.js';
@@ -1 +1 @@
1
- import {a}from'./chunk-XGE2FDI4.js';import {d,p,j as j$1}from'./chunk-FY4IIAIF.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 (j$1(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 d({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){this.rebuild=r?.rebuild??(()=>p({...o})),this.now=r?.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-CZVT7T2X.js';import {d,s,m as m$1}from'./chunk-TP7VKEUF.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 (m$1(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 d({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){this.rebuild=r?.rebuild??(()=>s({...o})),this.now=r?.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};
@@ -64,6 +64,25 @@ npm run test:scenarios:full
64
64
  npm run test:runtime-matrix:full
65
65
  ```
66
66
 
67
+ ### Pre-push gate cache
68
+
69
+ The local pre-push workflow content-addresses the runtime contract matrix and
70
+ official-generator dry-run smoke. A successful result is reused for up to 24
71
+ hours only when the built CLI, relevant contracts/templates/scripts, package
72
+ metadata, lockfile, platform, architecture, Node version and command are
73
+ unchanged. Failed runs are never cached. CI always executes both gates fresh.
74
+
75
+ ```bash
76
+ # Force every cached pre-push gate to execute again.
77
+ WORKSPAI_PREPUSH_CACHE=0 git push
78
+
79
+ # Override the local TTL in milliseconds (zero disables reuse).
80
+ WORKSPAI_PREPUSH_CACHE_TTL_MS=0 git push
81
+ ```
82
+
83
+ Cache records live under `node_modules/.cache/workspai-prepush-gates` and are
84
+ disposable. Other pre-push checks remain uncached.
85
+
67
86
  ## Manual smoke
68
87
 
69
88
  ```bash
package/docs/README.md CHANGED
@@ -26,6 +26,7 @@ cat .workspai/reports/workspace-context-agent.json | head -30
26
26
  ```
27
27
 
28
28
  That is it. Your project now has:
29
+
29
30
  - A **Workspace Model** describing every project, runtime, and dependency
30
31
  - A **Knowledge Graph** with searchable, proof-backed relationships
31
32
  - **Agent grounding** files (`AGENTS.md`, Cursor rules, Claude rules, etc.)
@@ -76,22 +77,23 @@ or use `import` to copy or clone one into the workspace.
76
77
 
77
78
  ## Choose a guide by goal
78
79
 
79
- | I want to… | Start here | Expected outcome |
80
- | ------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
81
- | Create a workspace or project | [Creating workspaces and projects](./creating-workspaces-and-projects.md) | A registered project with canonical `.workspai` metadata |
82
- | 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` |
83
- | Run the complete intelligence loop | [Unified runner](./workspace-intelligence-runner.md) | One ordered run report with durable stage evidence |
84
- | Turn plain language into governed work | [Goal Packs](./goal-packs.md) | A scope-bound, evidence-pinned plan and portable agent handoff |
85
- | Ground an agent before broad source discovery | [Canonical-first agent entry](./agent-entry.md) | A portable receipt for host discovery, evidence integrity, and freshness |
86
- | Repair a blocker through an approved transaction | [Workspace Repair Engine](./workspace-repair-engine.md) | Checkpointed execution, validation, canonical verify, and safe rollback |
87
- | 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 |
88
- | Ask an architecture or dependency question | [Workspace Knowledge Graph](./workspace-knowledge-graph.md) | A bounded answer with proof references rather than the whole graph |
89
- | Measure agent token, cost, and outcome efficiency | [Workspace Intelligence Evaluation](./workspace-intelligence-evaluation.md) | A live, provenance-aware report suitable for CLI, IDE, and CI |
90
- | Integrate CI or release gates | [CI workflows](./ci-workflows.md) | Machine-readable exit codes and uploadable evidence |
91
- | Find the writer, schema, or path for an output | [Artifact Catalog](./contracts/ARTIFACT_CATALOG.md) | One canonical source instead of path guessing |
92
- | Understand Workspai terminology | [Glossary](./GLOSSARY.md) | Shared meanings for model, graph, evidence, gate, and artifacts |
93
- | Review or change the main product README | [README content contract](./README_CONTENT_CONTRACT.md) | Stable narrative, claim boundaries, and machine-enforced drift rules |
94
- | Contribute to the CLI | [Development](./DEVELOPMENT.md) | Local build, test, contract, and documentation gates |
80
+ | I want to… | Start here | Expected outcome |
81
+ | -------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
82
+ | Create a workspace or project | [Creating workspaces and projects](./creating-workspaces-and-projects.md) | A registered project with canonical `.workspai` metadata |
83
+ | 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` |
84
+ | Run the complete intelligence loop | [Unified runner](./workspace-intelligence-runner.md) | One ordered run report with durable stage evidence |
85
+ | Turn plain language into governed work | [Goal Packs](./goal-packs.md) | A scope-bound, evidence-pinned plan and portable agent handoff |
86
+ | Ground an agent before broad source discovery | [Canonical-first agent entry](./agent-entry.md) | A portable receipt for host discovery, evidence integrity, and freshness |
87
+ | Repair a blocker through an approved transaction | [Workspace Repair Engine](./workspace-repair-engine.md) | Checkpointed execution, validation, canonical verify, and safe rollback |
88
+ | 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 |
89
+ | Ask an architecture or dependency question | [Workspace Knowledge Graph](./workspace-knowledge-graph.md) | A bounded answer with proof references rather than the whole graph |
90
+ | Measure agent token, cost, and outcome efficiency | [Workspace Intelligence Evaluation](./workspace-intelligence-evaluation.md) | A live, provenance-aware report suitable for CLI, IDE, and CI |
91
+ | Benchmark bounded retrieval across fixed scenarios | [Workspace Intelligence Benchmark](./workspace-intelligence-benchmark.md) | An offline suite with honest estimate/measurement boundaries |
92
+ | Integrate CI or release gates | [CI workflows](./ci-workflows.md) | Machine-readable exit codes and uploadable evidence |
93
+ | Find the writer, schema, or path for an output | [Artifact Catalog](./contracts/ARTIFACT_CATALOG.md) | One canonical source instead of path guessing |
94
+ | Understand Workspai terminology | [Glossary](./GLOSSARY.md) | Shared meanings for model, graph, evidence, gate, and artifacts |
95
+ | Review or change the main product README | [README content contract](./README_CONTENT_CONTRACT.md) | Stable narrative, claim boundaries, and machine-enforced drift rules |
96
+ | Contribute to the CLI | [Development](./DEVELOPMENT.md) | Local build, test, contract, and documentation gates |
95
97
 
96
98
  There are two different AI-facing features. Workspace Intelligence is
97
99
  deterministic, proof-backed, and does not require an AI API key. The optional
@@ -113,6 +115,7 @@ with [AI Quickstart](./AI_QUICKSTART.md) only when that is your goal.
113
115
  | [workspace-knowledge-graph.md](./workspace-knowledge-graph.md) | Two-minute graph quickstart, proof model, AI/MCP consumption, performance, and honest token-efficiency measurement |
114
116
  | [graph-benchmark-methodology.md](./graph-benchmark-methodology.md) | Reproducible payload-reduction benchmark, formulas, claim boundaries, and publication rules |
115
117
  | [workspace-intelligence-evaluation.md](./workspace-intelligence-evaluation.md) | Provider usage, cost provenance, verified outcomes, comparison, and extension consumption |
118
+ | [workspace-intelligence-benchmark.md](./workspace-intelligence-benchmark.md) | Fixed multi-scenario retrieval metrics, measured evaluation attachment, and publication-safe claim boundaries |
116
119
  | [GLOSSARY.md](./GLOSSARY.md) | Plain-language definitions for workspace, model, graph, evidence, gates, and AI integrations |
117
120
  | [README_CONTENT_CONTRACT.md](./README_CONTENT_CONTRACT.md) | Required root README journey, architecture statements, claim policy, and drift guard |
118
121
  | [create-planner-capabilities.md](./create-planner-capabilities.md) | Native create, official, and existing lanes |
package/docs/SETUP.md CHANGED
@@ -83,8 +83,18 @@ Bridge + Core integration:
83
83
  - `RAPIDKIT_CORE_PYTHON_PACKAGE` — override Core install target
84
84
  - `RAPIDKIT_BRIDGE_FORCE_VENV=1` — force cached bridge venv
85
85
  - `RAPIDKIT_BRIDGE_UPGRADE_PIP=1` — upgrade pip in bridge venv
86
+ - `RAPIDKIT_BRIDGE_LOCK_TIMEOUT_MS` — maximum wait for another process that is
87
+ preparing the same cached bridge (default: 10 minutes)
88
+ - `RAPIDKIT_BRIDGE_LOCK_STALE_MS` — stale-owner recovery threshold (default: 15
89
+ minutes and always longer than the configured lock timeout)
86
90
  - `XDG_CACHE_HOME` — bridge cache root
87
91
 
92
+ Bridge creation is serialized across processes. A cached environment is reused
93
+ only after `rapidkit --version --json` satisfies the executable Core contract;
94
+ an incomplete or unhealthy environment is discarded and rebuilt under the
95
+ same lock. This makes concurrent first-use from terminals, IDEs, agents, and CI
96
+ workers safe without requiring a global Python installation.
97
+
88
98
  Scenario toggles: `RAPIDKIT_SCENARIO_FULL_BOOTSTRAP`, `RAPIDKIT_SCENARIO_WORKSPACE_CREATE`
89
99
 
90
100
  General: `DEBUG`, `NODE_ENV`
@@ -45,10 +45,13 @@ chain still preserves portable entry coverage for every supported host.
45
45
 
46
46
  Workspai writes a portable entry contract at
47
47
  `.workspai/agent-entry.v1.json`, a bounded project lens at
48
- `.workspai/reports/project-context-agent.json`, and host adapters when project
49
- grounding is managed.
48
+ `.workspai/reports/project-context-agent.json`, an integrity-bound graph reference,
49
+ project-local `.agents/skills/workspai-*` wrappers, and host adapters when project
50
+ grounding is managed. The wrappers contain no machine-local workspace path and
51
+ resolve their canonical playbook through the project bootstrap contract.
50
52
 
51
- The shared context is intentionally compact. A complete Model or Graph export
53
+ The mandatory project context is intentionally compact. Workspace-wide context,
54
+ the evidence index, and a complete Model or Graph export
52
55
  is validated as canonical evidence but is not injected into first-contact
53
56
  instructions. Agents retrieve task-specific, proof-backed slices through graph
54
57
  search and only open the returned proof paths.
@@ -89,12 +92,22 @@ provider-neutral bootstrap command; each runtime receipt replaces that step in
89
92
  `requiredReadOrder` with the resolved host (or `all` for a complete host audit),
90
93
  so a consumer is never routed back through the wrong adapter.
91
94
 
95
+ The top-level `status` is explicitly scoped by `statusScope: agent-grounding`.
96
+ It must not be interpreted as project setup or release readiness. The
97
+ `readiness` object reports those dimensions separately: agent grounding,
98
+ architecture evidence, project environment, and release. A clean bootstrap can
99
+ therefore be `ready` while release remains `not-verified`, or while previously
100
+ recorded Doctor findings make the project environment `degraded` or `blocked`.
101
+ When live input validation succeeds, the receipt reports Model and Graph
102
+ freshness as `fresh`; fact-level TTL and verify-before-use semantics remain in
103
+ their individual evidence records and do not weaken structural freshness.
104
+
92
105
  The Workspace Model and complete Knowledge Graph are validated by the receipt,
93
106
  but are deliberately **not** part of `requiredReadOrder`. They are on-demand
94
107
  deep-evidence artifacts: load them only for an explicit full export, offline
95
108
  audit, or a task that cannot be answered from the project lens, bounded context,
96
109
  and task-scoped Graph query. This keeps first contact bounded on large workspaces.
97
- The compact Workspace Skills index *is* part of the route: use it to select one
110
+ The compact Workspace Skills index _is_ part of the route: use it to select one
98
111
  relevant playbook, rather than loading every Skill or asking the model to infer
99
112
  an operational procedure from raw source alone.
100
113
 
@@ -154,7 +167,8 @@ stale workspace evidence with an unbounded repository scan.
154
167
  | Host | Project discovery surface |
155
168
  | -------------------------------------------------------- | -------------------------------------------------------- |
156
169
  | Generic and unsupported model-only clients | `.workspai/PROJECT-GROUNDING.md` plus explicit bootstrap |
157
- | Codex, Kimi Code, GitHub Copilot, Cursor, Windsurf, Grok | `AGENTS.md` |
170
+ | Codex, Kimi Code, Grok | `AGENTS.md` plus `.agents/skills/workspai-grounding/SKILL.md` |
171
+ | GitHub Copilot, Cursor, Windsurf | `AGENTS.md` plus their generated host adapter when available |
158
172
  | Claude Code | `CLAUDE.md` adapter |
159
173
  | Gemini CLI | `GEMINI.md` adapter |
160
174
  | Qwen Code | `QWEN.md` adapter |
@@ -190,8 +204,9 @@ coverage. It does not replace the file to make a check pass.
190
204
  Agent-sync derives operational playbooks from the detected workspace: runtime
191
205
  validation is generated per detected runtime, and polyglot, test-evidence, and
192
206
  delivery playbooks appear only when their supporting signals exist. The
193
- canonical inventory remains under `.workspai/skills/`; standard portable
194
- projections use `skills/<skill-name>/SKILL.md` with YAML frontmatter for hosts
207
+ canonical inventory remains under `.workspai/skills/`; the provider-neutral
208
+ projection uses `.agents/skills/<skill-name>/SKILL.md`, while provider mirrors
209
+ use their documented `skills/<skill-name>/SKILL.md` roots with YAML frontmatter for hosts
195
210
  that implement Agent Skills. A host without a documented Skills surface still
196
211
  receives its native adapter and the portable canonical-first entry contract.
197
212
  Agent-sync reconciles only Skill files marked as Workspai-generated, so a
@@ -63,7 +63,7 @@ Validate or preview the current CLI announcement locally:
63
63
  npm --workspace workspai run check:release-announcement
64
64
  npm --workspace workspai run release:announcement -- \
65
65
  --product workspai-cli \
66
- --tag v0.65.0 \
66
+ --tag v0.67.0 \
67
67
  --markdown-output /tmp/workspai-discord-announcement.md
68
68
  ```
69
69
 
@@ -1,5 +1,34 @@
1
1
  # Commands Reference
2
2
 
3
+ ## Live cross-terminal activity
4
+
5
+ ```bash
6
+ workspai live [target]
7
+ workspai live --global [--max-scopes <count>]
8
+ workspai live --run <run-id>
9
+ workspai live --once --json
10
+ workspai live --once --json --projection monitor|board
11
+ workspai live --no-motion --no-color
12
+ workspai live --ascii|--accessible|--classic
13
+ workspai live --capture <file.svg> [--capture-preset github|linkedin|x|square|wide]
14
+ workspai live --replay <run-id> [--replay-speed <0.25..64>]
15
+ ```
16
+
17
+ `workspai live` observes versioned run/block/activity journals emitted by every
18
+ Workspai CLI command in the same project or workspace. It works without
19
+ `adopt`; adoption adds workspace correlation and cross-project intelligence.
20
+ Its default TTY surface is a bounded interactive Flow Board with live block and
21
+ edge state, durable per-block retry attempts, semantic phase rails, an adaptive
22
+ Inspector, a deduplicated multi-workspace Fleet Cockpit, deterministic
23
+ redacted-by-default SVG capture, durable replay, responsive compaction and
24
+ changed-row rendering. Use `--accessible` for stable screen-reader output or
25
+ `--classic` for the compatibility line view.
26
+ `--projection board` exposes the same bounded renderer-neutral run/node/edge
27
+ model used by the terminal and SVG adapters, so IDE and web consumers do not
28
+ need to reconstruct topology from raw events. The default `monitor` projection
29
+ is backward compatible.
30
+ See [Workspai Live Activity](./workspace-live-activity.md).
31
+
3
32
  Human-readable CLI syntax for the Workspai CLI. The machine-complete command,
4
33
  argument, option, alias, ownership, and integrity inventory is available through
5
34
  `workspai commands --json` and
@@ -95,7 +124,7 @@ npx workspai workspace snapshot [--workspace <path>] [--json] [--include-paths]
95
124
  npx workspai workspace diff --from <snapshot-or-model|git[:ref]> [--workspace <path>] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>] [--strict]
96
125
  npx workspai workspace impact --from <workspace-diff-report> [--workspace <path>] [--scope project:<name>] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>] [--strict]
97
126
  npx workspai workspace verify [--from-impact <file>] [--workspace <path>] [--scope project:<name>] [--strict] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
98
- npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid|jsonld|graphml|gexf] [key] [value] [--from <graph.json>] [--output <file>] [--limit <1..100>] [--kind <entity-kind>] [--workspace <path>] [--scope project:<name>] [--refresh-graph] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
127
+ npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid|jsonld|graphml|gexf] [key] [value] [--from <graph.json>] [--output <file>] [--limit <1..100>] [--kind <entity-kind>] [--workspace <path>] [--scope project:<name>] [--refresh-graph] [--graph-inventory-limit <count>] [--graph-semantic-budget <count>] [--graph-deep-budget <count>] [--graph-source-budget <count>] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
99
128
  npx workspai workspace eval [init <task> [strategy]|record|status|report|compare --from <report>] [--workspace <path>] [--output <file>] [--json]
100
129
  npx workspai workspace watch [--workspace <path>] [--json] [--graph-stream] [--once] [--scan-depth <count>]
101
130
  npx workspai workspace explain <target> [--workspace <path>] [--json] [--write]
@@ -194,7 +223,10 @@ the same runtime remains part of baseline and verification identity.
194
223
  `agent bootstrap` is the project-local canonical-first preflight. It validates
195
224
  the host discovery route, project/workspace binding, public artifact schemas,
196
225
  integrity hashes, Model/Graph freshness, live source inputs, and active Goal
197
- handoff before broad repository discovery. `project agent-entry verify` uses
226
+ handoff before broad repository discovery. It also proves that the local
227
+ project graph is the exact current projection of the canonical workspace
228
+ aggregate; a missing, stale, foreign, or tampered shard blocks architecture
229
+ claims. `project agent-entry verify` uses
198
230
  the same receipt and can audit every supported host with `--for-agent all`.
199
231
  Blocked receipts exit `2`; strict mode also maps degraded evidence to exit `2`.
200
232
  See [Canonical-first agent entry](./agent-entry.md).
@@ -218,6 +250,10 @@ and a risk summary. Observation timestamps and freshness alone do not create
218
250
  false change noise. Query indexes are cached
219
251
  per immutable graph object and invalidated automatically when a new graph is
220
252
  built. `dot` and `mermaid` intentionally remain project-topology renderers.
253
+ `workspace graph entities --kind <kind> --scope project:<name> --limit <n>` is
254
+ equivalent to the positional kind form and applies all three bounds before
255
+ serializing JSON; `count`, `totalMatches`, and `truncated` make omissions
256
+ explicit.
221
257
  Without `--output` they emit raw text for direct piping. With `--output` they
222
258
  write a durable file; adding `--json` returns a structured operation receipt
223
259
  with the format, node and edge counts, and resolved output path.
@@ -237,13 +273,24 @@ that retrieval payload with the readable proof-indexed corpus using a labelled
237
273
  `characters / 4` estimate. It measures payload reduction only; it does not
238
274
  assert equivalent answer quality or model-specific billing savings.
239
275
 
276
+ `workspace graph benchmark-suite agent-core.v1 --write --json` runs five fixed,
277
+ repository-neutral scenarios covering architecture, ownership, interfaces,
278
+ change safety, and delivery. It reads the proof corpus once, reports median and
279
+ p95 bounded retrieval sizes, and writes
280
+ `.workspai/reports/workspace-intelligence-benchmark-last-run.json`. If a
281
+ finalized `workspace eval` report exists, its usage and verified outcome are
282
+ attached under a separate provenance classification. Pass `--from
283
+ <baseline-evaluation>` only for a task-aligned comparison. A measured reduction
284
+ is emitted only when both runs use measured token sources and have comparable
285
+ verified outcomes. See [Workspace Intelligence Benchmark](./workspace-intelligence-benchmark.md).
286
+
240
287
  Add `--scope project:<name>` to retrieve project-owned facts plus
241
288
  workspace-level shared entities proven to be connected to that project. The
242
289
  `search` mode also accepts `--kind <entity-kind>` so agents can retrieve a
243
290
  precise semantic surface such as `runtime-unit`, `endpoint`, or `owner`. The
244
291
  agent projection reports explicit omission budgets for relations, related
245
292
  entities, proofs, aliases, attributes, and proof references. Read-oriented
246
- `search`, `entities`, `evidence`, `path`, and `benchmark` modes reuse the
293
+ `search`, `entities`, `evidence`, `path`, `benchmark`, and `benchmark-suite` modes reuse the
247
294
  persisted graph only when its model binding, proofs, project scopes, and live
248
295
  Git/Merkle input fingerprint still match. `--refresh-graph` bypasses that
249
296
  compatible snapshot and rebuilds from current sources.
@@ -260,11 +307,14 @@ are suitable for IDE dashboards and conform to
260
307
  `workspace-intelligence-evaluation.v1`.
261
308
 
262
309
  `workspace model --write` also materializes the derived, contract-validated
263
- knowledge graph at `.workspai/reports/workspace-knowledge-graph.json`. The
264
- unified intelligence runner treats that artifact as a required output of the
265
- Model step, so CI, IDE adapters, agent grounding, and MCP all observe the same
266
- revision. Agent contexts carry its reference, quality counts, and bounded query
267
- commands instead of copying the entire graph into every prompt. MCP exposes
310
+ knowledge graph once at
311
+ `<workspace>/.workspai/reports/workspace-knowledge-graph.json`. Every registered
312
+ project receives a compact, integrity-bound
313
+ `.workspai/reports/project-knowledge-graph-reference.json` that names the exact
314
+ project projection and canonical `workspace:` URI. The unified intelligence
315
+ runner publishes the aggregate and references as one atomic Model-stage
316
+ revision, so CI, IDE adapters, agent grounding, and MCP cannot observe a partial
317
+ set. Bounded graph search remains the default retrieval path. MCP exposes
268
318
  `getWorkspaceKnowledgeGraph`, `searchWorkspaceGraph`, `queryWorkspaceEntities`,
269
319
  `getWorkspaceGraphEvidence`, and `findWorkspaceGraphPath`.
270
320