workspai 0.71.0 → 0.72.1

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 (99) hide show
  1. package/README.md +5 -2
  2. package/contracts/artifact-remediation-plan.v1.json +49 -0
  3. package/contracts/workspace-repair-capabilities.v1.json +7 -1
  4. package/dist/analyze-5ENZTHOT.js +1 -0
  5. package/dist/{artifact-remediation-plan-URQL5MBN.js → artifact-remediation-plan-WDK5ISRU.js} +1 -1
  6. package/dist/autopilot-release-QMZSHOLF.js +1 -0
  7. package/dist/{chunk-YC676TPF.js → chunk-2RF75G5T.js} +1 -1
  8. package/dist/chunk-4AW5QP5J.js +5 -0
  9. package/dist/{chunk-LOXR5QUX.js → chunk-4PDEWMOG.js} +1 -1
  10. package/dist/{chunk-H64KAPJJ.js → chunk-5NL53T5C.js} +1 -1
  11. package/dist/{chunk-IGJA6GBQ.js → chunk-62YBFWHY.js} +1 -1
  12. package/dist/chunk-6WOFOOM7.js +7 -0
  13. package/dist/chunk-7Q7X4X5I.js +1 -0
  14. package/dist/chunk-BVWDG66W.js +1 -0
  15. package/dist/chunk-CQBM6BBP.js +2 -0
  16. package/dist/chunk-CY4QZ3PE.js +3 -0
  17. package/dist/{chunk-IOKEF3DE.js → chunk-FYIPYGMW.js} +1 -1
  18. package/dist/{chunk-K2LKJBQ4.js → chunk-I7P6XQJI.js} +1 -1
  19. package/dist/{chunk-5HURQABR.js → chunk-ISGLADQI.js} +1 -1
  20. package/dist/{chunk-V52R2W2Q.js → chunk-IX5Z6EK6.js} +1 -1
  21. package/dist/{chunk-ACCWXKZW.js → chunk-JPPZDLY3.js} +2 -2
  22. package/dist/{chunk-AUVWD3WV.js → chunk-JQINCVK5.js} +1 -1
  23. package/dist/{chunk-GL3KLNIG.js → chunk-KVPTZMEV.js} +1 -1
  24. package/dist/{chunk-7V3YDKMG.js → chunk-L4WG3NI7.js} +1 -1
  25. package/dist/{chunk-HMKDU7OU.js → chunk-L5ZD2GD3.js} +1 -1
  26. package/dist/{chunk-554W2TXP.js → chunk-LLEKVSMX.js} +1 -1
  27. package/dist/{chunk-L5IV2SI4.js → chunk-LLSY6L7E.js} +1 -1
  28. package/dist/{chunk-QHHSSIMZ.js → chunk-N2PAAQKI.js} +1 -1
  29. package/dist/{chunk-TD5TQZEG.js → chunk-QVUVJU56.js} +1 -1
  30. package/dist/{chunk-FFE2JZZJ.js → chunk-QYXX6G5O.js} +8 -8
  31. package/dist/{chunk-CX6PAQTQ.js → chunk-RQKDJVX3.js} +65 -65
  32. package/dist/{chunk-C563KVBD.js → chunk-S66NO5BX.js} +1 -1
  33. package/dist/{chunk-M2R6UXJB.js → chunk-SATPH22S.js} +1 -1
  34. package/dist/{chunk-2KJNASF3.js → chunk-SS7X2YF5.js} +1 -1
  35. package/dist/{chunk-4CE3GI4Y.js → chunk-T6KHOIEY.js} +1 -1
  36. package/dist/{chunk-AUQLOQ2S.js → chunk-T6LCDLJ7.js} +1 -1
  37. package/dist/{chunk-XY537LCX.js → chunk-TDQ2PRHV.js} +1 -1
  38. package/dist/{chunk-26VNCHVV.js → chunk-U3RX7KDY.js} +1 -1
  39. package/dist/chunk-V4LCPLV6.js +1 -0
  40. package/dist/{chunk-GYN6RPNU.js → chunk-WMC2H7MJ.js} +1 -1
  41. package/dist/{chunk-YS34N35Y.js → chunk-WPZUKU2B.js} +1 -1
  42. package/dist/chunk-X5ZNFXFI.js +1 -0
  43. package/dist/{create-HSHAZYAK.js → create-FOPYAWAR.js} +1 -1
  44. package/dist/{doctor-VZ2MZ7EI.js → doctor-Z3Z5L67W.js} +1 -1
  45. package/dist/{goal-lifecycle-NKSCALES.js → goal-lifecycle-ZH7AQIOX.js} +1 -1
  46. package/dist/{goal-pack-MPKW4K6F.js → goal-pack-OP453Q6U.js} +1 -1
  47. package/dist/index.js +101 -101
  48. package/dist/{pipeline-RIA5UXUC.js → pipeline-LPZHMO7S.js} +1 -1
  49. package/dist/{project-agent-entry-GQAPCSOT.js → project-agent-entry-QGPM7CU7.js} +1 -1
  50. package/dist/{project-intelligence-lens-5I2GQBWC.js → project-intelligence-lens-U7PLWYXX.js} +1 -1
  51. package/dist/{project-test-coverage-4RRCHY5W.js → project-test-coverage-4BGDDBBL.js} +1 -1
  52. package/dist/{proof-carrying-change-T33C2SSD.js → proof-carrying-change-6LQ6JO5J.js} +1 -1
  53. package/dist/{verified-goal-MK5MXGRY.js → verified-goal-JIRVX7KO.js} +1 -1
  54. package/dist/{workspace-AZKZPG45.js → workspace-3K2YGPU7.js} +1 -1
  55. package/dist/{workspace-agent-sync-CGK44F3O.js → workspace-agent-sync-TFQNKRD3.js} +1 -1
  56. package/dist/{workspace-context-S6ZWRUFZ.js → workspace-context-ZDXF6S7S.js} +1 -1
  57. package/dist/{workspace-contract-Y7WRHLYR.js → workspace-contract-E7GVWM7W.js} +1 -1
  58. package/dist/{workspace-explain-CSJL3GJR.js → workspace-explain-YB66UFAS.js} +1 -1
  59. package/dist/{workspace-foundation-LLND2WIF.js → workspace-foundation-J62BMOQS.js} +1 -1
  60. package/dist/{workspace-graph-stream-PHFO2J2E.js → workspace-graph-stream-SJUCBPS4.js} +1 -1
  61. package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +1 -0
  62. package/dist/{workspace-intelligence-ND2N3B2A.js → workspace-intelligence-3IAAM3H3.js} +1 -1
  63. package/dist/{workspace-intelligence-benchmark-S5OXVNLC.js → workspace-intelligence-benchmark-UCGDKMDF.js} +1 -1
  64. package/dist/{workspace-intelligence-runner-LHHJM2AT.js → workspace-intelligence-runner-OELXKX3D.js} +1 -1
  65. package/dist/{workspace-knowledge-graph-NOGGGENE.js → workspace-knowledge-graph-WNQMNAVL.js} +1 -1
  66. package/dist/{workspace-knowledge-graph-query-WHCGPBGS.js → workspace-knowledge-graph-query-3GPXGWYN.js} +1 -1
  67. package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +1 -0
  68. package/dist/{workspace-mcp-serve-6NVF7AS6.js → workspace-mcp-serve-X7ZYJA3X.js} +1 -1
  69. package/dist/{workspace-model-VOQOEDVU.js → workspace-model-5FA2636K.js} +1 -1
  70. package/dist/{workspace-onboarding-ZRLUMBLE.js → workspace-onboarding-CZSQDNKO.js} +1 -1
  71. package/dist/{workspace-registry-summary-NWZK5IKS.js → workspace-registry-summary-WKENOFEA.js} +1 -1
  72. package/dist/workspace-repair-engine-RXHJX4CQ.js +3 -0
  73. package/dist/workspace-run-IDRHBKEB.js +1 -0
  74. package/dist/{workspace-verify-4EQI3MCW.js → workspace-verify-37QL2JYE.js} +1 -1
  75. package/dist/{workspace-watch-BPRU2X7K.js → workspace-watch-P5X6TAFK.js} +1 -1
  76. package/docs/ci-workflows.md +1 -1
  77. package/docs/commands-reference.md +16 -2
  78. package/docs/contracts/ARTIFACT_CATALOG.md +4 -1
  79. package/docs/doctor-command.md +20 -0
  80. package/docs/workspace-knowledge-graph.md +11 -0
  81. package/docs/workspace-repair-engine.md +9 -1
  82. package/docs/workspace-run.md +13 -0
  83. package/package.json +1 -4
  84. package/scripts/enterprise-package-smoke.mjs +14 -2
  85. package/dist/analyze-4YQ67OCK.js +0 -1
  86. package/dist/autopilot-release-V3A3YCDD.js +0 -1
  87. package/dist/chunk-DWL3PPLA.js +0 -1
  88. package/dist/chunk-EZPLMAW2.js +0 -1
  89. package/dist/chunk-IRLKWRLP.js +0 -3
  90. package/dist/chunk-RMGSMDJW.js +0 -5
  91. package/dist/chunk-TKXRP2B4.js +0 -1
  92. package/dist/chunk-U5ENEDJA.js +0 -7
  93. package/dist/chunk-WCJU3CFG.js +0 -1
  94. package/dist/chunk-ZOE43SGQ.js +0 -1
  95. package/dist/workspace-graph-token-efficiency-WNAFAN2F.js +0 -1
  96. package/dist/workspace-knowledge-graph-snapshot-7XHZNRFK.js +0 -1
  97. package/dist/workspace-repair-engine-VUOCH66O.js +0 -3
  98. package/dist/workspace-run-3YZTVOU6.js +0 -1
  99. package/scripts/check-cli-resolution.cjs +0 -72
@@ -0,0 +1,3 @@
1
+ import {a as a$2}from'./chunk-CY4QZ3PE.js';import {a,c,i,b,f as f$1,k as k$1,h,e}from'./chunk-V4LCPLV6.js';import {c as c$2}from'./chunk-I7P6XQJI.js';import {m}from'./chunk-LLSY6L7E.js';import {l,p}from'./chunk-5NL53T5C.js';import {g,l as l$1,m as m$1,n,k as k$2,p as p$3,q,r}from'./chunk-RQKDJVX3.js';import {a as a$5}from'./chunk-7Q7X4X5I.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {a as a$3}from'./chunk-TDQ2PRHV.js';import {p as p$2}from'./chunk-WPZUKU2B.js';import {f}from'./chunk-FE5R6EUV.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$3,d}from'./chunk-EWZZUQBR.js';import {p as p$1}from'./chunk-ODK4LCEL.js';import {c as c$4,b as b$1}from'./chunk-25AWHAB5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import k from'fs-extra';var Le=".workspai/repair",Ma="transaction.json",_a="source-plan.json",wa="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 H(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${$(e).slice(0,16)}`,message:r.message??e}]}}function 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=Ce(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:${$(t).slice(0,16)}`,message:t});}return [...a.values()]}function M(e){return (e?.()??new Date).toISOString()}function $(e){return createHash("sha256").update(e).digest("hex")}function V(e){return Array.isArray(e)?`[${e.map(V).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)}:${V(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function ba(e){return $(V({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=ba(a),t=(await Rt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&ba(o)===r);if(t)return await re(c$1.join(e,b),t),t}var Me="causal-action-integrity:";function Sa(e){return $(V([...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 Wa(e){if(e.length===0)return;let a=Sa(e);return {id:`${Me}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Xa(e){return V({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function va(e){return new Set(e.map(Xa))}function x(e,a){let r=c$1.relative(c$1.resolve(e),c$1.resolve(a));return r===""||!r.startsWith("..")&&!c$1.isAbsolute(r)}async function K(e,a){let r=await k.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await k.pathExists(t);){let i=c$1.dirname(t);if(i===t)return false;t=i;}let o=await k.realpath(t).catch(()=>c$1.resolve(t));return x(r,o)}function Y(e,a,r){let t=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!x(e,t)&&!(r&&x(c$1.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!x(e,t)&&r){let o=c$1.resolve(r),i=c$1.relative(o,t).split(c$1.sep).join("/"),n=`external/${c$1.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return c$1.relative(e,t).split(c$1.sep).join("/")||"."}function z(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(c$1.isAbsolute(e.value))return c$1.resolve(e.value);let a=z(e.value);if(!a)return c$1.resolve(e.workspacePath,e.value);if(e.projectBoundary)return c$1.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$2({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&c$1.basename(c$1.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 c$1.resolve(t.externalPath,a.suffix||".")}function Re(e,a,r,t){let o=Y(e,a,r),i=z(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?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&x(e.workspacePath,a)&&!z(e.proposal.projectPath??""))return a;let{contract:t}=await p$2({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?c$1.resolve(i.externalPath):c$1.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,h=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&h});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?c$1.resolve(o.externalPath):c$1.resolve(e.workspacePath,o.relativePath)}function de(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,Le,"transactions",a)}async function ee(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return c$1.join(de(e,a),Ma)}function Ge(e,a){return c$1.join(de(e,a),_a)}async function re(e,a){await k.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await k.writeJson(r,a,{spaces:2}),await k.move(r,e,{overwrite:true});}function A(e,a,r,t={}){let o={sequence:e.events.length+1,at:M(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 j(e,a,r){a.revision+=1,a.updatedAt=M(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(c$1.join(e,b),a);}async function pe(e){let a$2=await k.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 We(e,a){return await k.readJson(Ge(e,a))}function ce(e$1){return e$1.schemaVersion===e}async function le(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(!x(e,o)&&!z(t)&&!(r&&c$1.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:e.projectReference??Y(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function He(e){return k.readFile(e,"utf8").catch(()=>"")}async function Qa(e){return k.readJson(e).catch(()=>({}))}function Pa(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}async function Ca(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});return e.toolAvailable?e.toolAvailable(e.invocation.executable,a):a$5({executable:e.invocation.executable,cwd:a})}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(c$1.normalize(c$1.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=c$1.isAbsolute(i.executable)?c$1.normalize(i.executable):c$1.normalize(c$1.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 h=await Ca({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:h?"passed":"failed",message:h?`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 se(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function R(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 et(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 at(e){let a=await le(e.workspacePath,e.action,e.authorizedProjectRoot),r=z(e.action.projectPath??"")?.root??Y(e.workspacePath,a,a),t=async f=>k.pathExists(c$1.join(a,f)),o=new Set,i=[],n=[],s=f=>`${r}:${e.adapterId}:${f}`,h$1=f=>f.forEach(m=>o.add(Y(e.workspacePath,c$1.join(a,m),a))),l=f=>{i.push(f),f.required&&f.status==="blocked"&&n.push(f.summary);},d=et(e.workspacePath,a,e.action),g=()=>{let f=h.find(m=>m.id===e.adapterId);if(!f)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:f.id,ecosystem:f.ecosystem,projectPath:r,manifests:f.manifests,support:f.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${f.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let f=await Qa(c$1.join(a,"package.json")),m=f.scripts&&typeof f.scripts=="object"&&!Array.isArray(f.scripts)?f.scripts:{},w=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",D=w==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":w==="pnpm"?"pnpm-lock.yaml":w==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";h$1(["package.json",D]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${w} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:["install"],purpose:"reconcile"})}));let J=v(w==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="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 l(R({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:d??J})),l(typeof m.test=="string"&&m.test.trim()?R({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Pa({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"test",purpose:"test"})}):se(s("test"),"test","No test script is declared.")),l(typeof m.build=="string"&&m.build.trim()?R({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:Pa({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"build",purpose:"build"})}):se(s("build"),"build","No build script is declared.")),g()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){h$1(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let f=e.action.transaction?.ecosystem.toLowerCase(),m=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),w=m==="uv"||f==="uv"||await t("uv.lock"),D=!w&&(m==="poetry"||f==="poetry"||await t("poetry.lock")),J=!w&&!D&&["python","python3","py"].includes(m)&&(e.action.invocation?.args??[]).some(L=>L==="venv")&&(e.action.invocation?.args??[]).some(L=>L===".venv"),W=process.platform==="win32"?"python":"python3",F=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await k.pathExists(F)||J)&&(W=F);let B=w?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):D?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&x(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&x(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:B})),l(R({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:d}));let oe=await He(c$1.join(a,"pyproject.toml")),X=await t("tests")||/\[tool\.pytest/i.test(oe),ue=v(D?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:w?{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"}),Z=v(D?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","build"],purpose:"build"});return l(X?R({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:ue}):se(s("test"),"test","No Python test surface is declared.")),l(/\[build-system\]/i.test(oe)?R({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:Z}):se(s("build"),"build","No Python build contract is declared.")),g()}let b=[{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 f of b){if(f.adapterId!==e.adapterId)continue;let m=await t(f.manifest)?f.manifest:f.alternateManifest&&await t(f.alternateManifest)?f.alternateManifest:void 0;if(!m)continue;h$1(f.files),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${m} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.reconcile[0],args:f.reconcile[1],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:d??(f.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:f.audit[0],args:f.audit[1],purpose:"audit"}):void 0)}));let w=await He(c$1.join(a,m)),D=f.manifest==="composer.json"||f.adapterId==="deno"?/["']test["']\s*:/.test(w):f.manifest==="Gemfile"?await t("Rakefile"):true,J=f.manifest==="composer.json"||f.manifest==="deno.json"?/["']build["']\s*:/.test(w):f.manifest==="Gemfile"?(await k.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return l(D?R({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.test[0],args:f.test[1],purpose:"test"})}):se(s("test"),"test","No test contract is declared.")),l(J?R({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.build[0],args:f.build[1],purpose:"build"})}):se(s("build"),"build","No build contract is declared.")),g()}let y=await k.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&y.some(f=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(f)))return h$1(["Directory.Packages.props","packages.lock.json",...y.filter(f=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(f))]),l(R({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"})})),l(R({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:d??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),l(R({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),l(R({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"})})),g();let P=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return h$1(["pom.xml"]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["dependency:resolve"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["package","-DskipTests"],purpose:"build"})})),g();let E=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&E){let f=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return h$1([E,"gradle.lockfile","gradle/libs.versions.toml"]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["dependencies"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["build","-x","test"],purpose:"build"})})),g()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let f=q==="deps.edn",m=await He(c$1.join(a,q)),w=f?"clojure":"lein";h$1([q]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:f?["-P"]:["deps"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:d}));let D=!f||/:test\b/.test(m);return l(D?R({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:f?["-M:test"]:["test"],purpose:"test"})}):se(s("test"),"test","No Clojure :test alias is declared.")),l(f?se(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):R({id:s("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),g()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(h$1(["build.sbt"]),l(R({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"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),g()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),l(R({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),g())}async function Ta(e){let a=i=>k.pathExists(c$1.join(e,i)),r=await k.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(h.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function tt(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 le(e.workspacePath,e.action,e.authorizedProjectRoot),t=z(e.action.projectPath??"")?.root??Y(e.workspacePath,r,r),o=await Ta(r),i=tt(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let d=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[R({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:d})],checkpointFiles:[],blockers:[d],adapters:[{adapterId:i,ecosystem:h.find(g=>g.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:d}]}}if(n.length===0){let d=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[R({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:d})],checkpointFiles:[],blockers:[d],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:d}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let d of n){let g=await at({...e,adapterId:d});s.stages.push(...g.stages),s.checkpointFiles.push(...g.checkpointFiles),s.blockers.push(...g.blockers),s.adapters.push(...g.adapters);}s.stages=[...new Map(s.stages.map(d=>[d.id,d])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let h$1=Y(e.workspacePath,r,r);if(h$1!==t){let d=g=>g===h$1?t:g.startsWith(`${h$1}/`)?`${t}/${g.slice(h$1.length+1)}`:g;s.stages=s.stages.map(g=>({...g,...g.invocation?{invocation:{...g.invocation,cwd:d(g.invocation.cwd)}}:{}})),s.checkpointFiles=s.checkpointFiles.map(d);}let l=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let d=new Set(e.action.transaction.requiredStages),g=Te(e.action.invocation?.executable??""),b=e.action.invocation?.args??[],y=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(g)&&b.includes("venv")&&b.includes(".venv");y&&l.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(P=>P.kind==="reconcile"?y&&d.has("reconcile"):d.has(P.kind)),s.blockers=s.stages.filter(P=>P.required&&P.status==="blocked").map(P=>P.summary);}for(let d of s.adapters){let g=s.stages.filter(y=>y.id.startsWith(`${d.projectPath}:${d.adapterId}:`)),b=[];d.requiredExecutables=[...new Set(g.filter(y=>y.required&&y.invocation).map(y=>y.invocation.executable))];for(let y of g){if(!y.required||!y.invocation)continue;let P=await T({workspacePath:e.workspacePath,value:y.invocation.cwd,projectBoundary:r}),E=c$1.isAbsolute(y.invocation.executable)?c$1.normalize(y.invocation.executable):c$1.normalize(c$1.resolve(P,y.invocation.executable));l.has(E)||await Ca({workspacePath:e.workspacePath,invocation:y.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||b.push(y.invocation.executable);}d.missingExecutables=[...new Set(b)],d.missingExecutables.length>0&&(d.status="partial",d.message=`Required executable(s) unavailable: ${d.missingExecutables.join(", ")}.`);}if(n.length===1){let d=`:${n[0]}:`;for(let g of s.stages)g.id=g.id.replace(d,":");}return s}async function Yt(e={}){let a=i();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let i=e.project.trim(),n=await m(r),s=i.replace(/\\/g,"/").replace(/^\.\//,""),h=c$1.resolve(r,i),l=n.resolved.filter(d=>{let g=x(r,d.projectPath)?Y(r,d.projectPath):void 0;return d.name===i||g===s||c$1.resolve(d.projectPath)===h});if(l.length===0){let d=n.skipped.find(g=>g.name===i);throw d?new Error(`Registered project is unavailable for repair capability inspection: ${i} (${d.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i}.`)}if(l.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i}.`);t=c$1.resolve(l[0].projectPath),o=l[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!x(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=Y(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ta(t)}}}function Ce(e){if(e.command){let a=g(e.command);if(a)return a}return a$4(e.operation)??void 0}async function rt(e){let a=new Set,r=e.actions[0]?await le(e.workspacePath,e.actions[0]):void 0,t=z(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(Re(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await le(e.workspacePath,o),n=z(o.projectPath??"")?i:e.workspacePath;if(!await K(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 d of s?[]:o.files){let g=await T({workspacePath:e.workspacePath,value:d,projectBoundary:z(d)?i:void 0,projectName:o.projectName});if(!await K(n,g))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${d}`);a.add(Re(e.workspacePath,g,i,z(o.projectPath??"")?o.projectPath:void 0));}let h=Ce(o);if(!h)continue;let l="path"in h?h.path:void 0;if(l){let d=c$1.resolve(i,l);if(!await K(n,d))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${l}`);a.add(Re(e.workspacePath,d,i,z(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function ot(e,a){if(!a.invocation)return;let r=await le(e,a);return v({workspacePath:e,projectPath:r,projectReference:z(a.projectPath??"")?.root,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ke(e){return $(V({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 $(V({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 Xt(e){let a=c$1.resolve(e.workspacePath),r=await pe({workspacePath:a,transactionId:e.transactionId}),t=await We(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||$(V(t))!==r.integrity.sourceEvidenceHash||!ce(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 ee(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(!x(a,n)&&!(o&&x(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await k.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 h=await k.readFile(n);if(i.afterHash!==$(h))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}),h=r&&x(c$1.resolve(r),s)?c$1.resolve(r):e;if(!x(h,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await K(h,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let l=await k.lstat(s).catch(()=>{});if(l?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(l&&!l.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(l&&l.size>Ia){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=l?.size??0,i>Ga){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let d=l?await k.readFile(s):void 0;t.push({path:n,existed:!!l,beforeHash:d?$(d):null,...l?{mode:l.mode}:{}});}return {entries:t,errors:o}}function Da(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 st(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 it(e){let a=await k.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function nt(e){return Va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function ct(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;x(e,t);){if((await k.readdir(t).catch(()=>[])).some(nt))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function dt(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!x(a,o))return false;let i=c$1.basename(o);return Ja.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function lt(e){let a=!x(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:Y(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 pt(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 ut(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let h=c$1.resolve(e.workspacePath,s.cwd),l=Y(e.workspacePath,h,n),d=await k.lstat(h).catch(()=>{});if(!d?.isDirectory()||d.isSymbolicLink()||!await K(n??e.workspacePath,h)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!x(n,h)){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 g=v({workspacePath:e.workspacePath,projectPath:h,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Je(e.workspacePath,g,e.policy,e.projectRoots),pt(s,g);}catch(b){t.push(b instanceof Error?b.message:String(b));continue}a.push(R({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:g})),i.add(`${l}:${s.kind}`);}for(let s of e.projectRoots){let h=lt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),l=await Na({workspacePath:e.workspacePath,action:h,authorizedProjectRoot:s},e.dependencies);o.push(...l.adapters);let d=dt(e.workspacePath,s,e.proposal.changes);if(d){for(let b of l.checkpointFiles)r.add(b);t.push(...l.blockers);}let g=Y(e.workspacePath,s,s);for(let b of l.stages)!d&&!["test","build"].includes(b.kind)||i.has(`${g}:${b.kind}`)||a.push(b);}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 ht(e,a$3={}){let r=c$1.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true,toolAvailable:a$3.toolAvailable}),o=t.actions.filter(u=>u.cardId===e.cardId).filter(u=>!e.projectName||!u.projectName||u.projectName===e.projectName).sort((u,C)=>u.order-C.order||u.id.localeCompare(C.id)),i=e.actionId?o.filter(u=>u.id===e.actionId):o,n=t.actions.filter(u=>!e.projectName||!u.projectName||u.projectName===e.projectName).sort((u,C)=>u.order-C.order||u.id.localeCompare(C.id)),s=new Map(n.map(u=>[u.id,u])),h=u=>{let C=new Set(u.map(ae=>ae.id)),O=[...u];for(;O.length>0;){let ae=O.pop();for(let _ of ae?.dependsOn??[]){let te=s.get(_);!te||C.has(te.id)||(C.add(te.id),O.push(te));}}return n.filter(ae=>C.has(ae.id))},l=i.filter(u=>u.findingStatus==="blocking"||u.notes.includes("Doctor finding status: blocking")),d=l.length>0?l:i.filter(u=>u.findingStatus!=="informational"),g=e.actionId?i.filter(u=>u.id===e.actionId):[],b$1=[...d].sort((u,C)=>{let O=u.status==="ready"||u.status==="review-required"?0:1,ae=C.status==="ready"||C.status==="review-required"?0:1;return O-ae||u.order-C.order||u.id.localeCompare(C.id)})[0],y=b$1?d.filter(u=>u.cardId===b$1.cardId&&u.findingId===b$1.findingId&&u.causalKey===b$1.causalKey&&u.projectName===b$1.projectName&&u.projectPath===b$1.projectPath):[],P=h(e.actionId?g:y),E=e.maxRisk??"guarded",q={maxRisk:E,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},f=[{id:"workspace-root",status:await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:P.length>0?"passed":"failed",message:P.length>0?`${P.length} governed action(s) selected.`:"No governed remediation action matches this target."}],m=Wa(P);m&&f.push(m);let w=[],D=[],J=[],W=[],F=[],B=new Set(["replan","manual-repair","cancel"]);for(let u of P){let C=Ce(u),O=await ot(r,u);if(G[u.risk]<=G[E]||(W.push(`${u.id} exceeds the approved ${E} risk ceiling.`),B.add(u.risk==="invasive"?"approve-invasive":"approve-guarded")),(u.status==="blocked"||u.status==="guidance-only")&&W.push(`${u.id} is ${u.status}: ${u.blocker}`),!C&&!O&&(u.mode==="run-command"||u.mode==="edit-file")&&(W.push(`${u.id} has no typed operation or structured invocation.`),F.push(u.id)),O)try{Je(r,O,q);}catch(_){let te=_ instanceof Error?_.message:String(_);W.push(te),/Force-based/.test(te)&&B.add("allow-force"),/Breaking dependency/.test(te)&&B.add("allow-breaking");}if(w.push({id:`action:${u.id}`,kind:"repair",status:C||O?"pending":"blocked",required:true,risk:u.risk,summary:u.summary,...O?{invocation:O}:{}}),u.transaction){let _=await Na({workspacePath:r,action:u},a$3);w.push(..._.stages),D.push(..._.checkpointFiles),W.push(..._.blockers),J.push(..._.adapters);}}let oe=[...new Map(w.map(u=>[u.id,u])).values()];w.splice(0,w.length,...oe),w.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."}),w.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),w.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),f.push(...await ze({workspacePath:r,stages:w,toolAvailable:a$3.toolAvailable}));let X=await rt({workspacePath:r,actions:P,dependencyFiles:D}),ue=P[0]?await le(r,P[0]):void 0,Z=await $e(r,X,ue);f.push({id:"rollback-coverage",status:P.some(u=>u.mode==="edit-file"||u.mode==="run-command")&&X.length===0?"failed":"passed",message:X.length>0?`${X.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),f.push({id:"structured-execution",status:F.length>0?"failed":"passed",message:F.length>0?`Executable actions without typed execution: ${F.join(", ")}.`:"Every executable action uses a typed operation or structured invocation."}),f.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 L=$(V(t)),je=[...new Set(P.map(u=>u.projectPath).filter(Boolean))],ie=[...new Set(P.map(u=>u.projectName).filter(Boolean))],ke=ie.length===1?ie[0]:void 0,he=je.length===1&&ie.length<=1,we={cardId:e.cardId,scope:he?"project":"workspace",...ke?{projectName:ke}:{},...je.length===1?{projectPath:je[0]}:{},actionIds:P.map(u=>u.id)},xe=M(a$3.now),U=`repair_${randomUUID().replaceAll("-","")}`,ge=f.some(u=>u.status==="failed")||W.length>0,Ie=[...W,...f.filter(u=>u.status==="failed").map(u=>u.message)],p=[...new Map(J.map(u=>[`${u.projectPath}:${u.adapterId}`,u])).values()],N=Ea({actions:P,adapters:p,preconditions:f,stages:w,decisionOptions:B,maxRisk:E,fallbackReasons:Ie}),S={schemaVersion:a,transactionId:U,revision:1,createdAt:xe,updatedAt:xe,workspace:{name:t.workspace.name,rootRef:"."},target:we,state:ge?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:f,adapterEvaluations:p,checkpoint:{status:X.length>0?"pending":"unavailable",files:Z.entries},stages:w,...ge?{decision:{reason:[...new Set(Ie)].join(" "),options:[...B],causes:N}}:{},events:[],integrity:{sourceEvidenceHash:L,planHash:Ke({sourceEvidenceHash:L,target:we,policy:q,preconditions:f,adapterEvaluations:p,stages:w,checkpointFiles:Z.entries})}};A(S,"planned",ge?"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 ne=await $a(r,S);if(ne)return ne;let Ne=de(r,U);return await k.ensureDir(Ne),await re(Ge(r,U),t),await re(Se(r,U),S),await re(c$1.join(r,b),S),S}async function gt(e,a={}){let r=e.proposal.goalId;if(!r)return ya(e,a);let t=c$1.resolve(e.workspacePath);return f(t,`.workspai/goals/${r}/repair-proposal`,()=>ya({...e,workspacePath:t},a))}async function ya(e,a$3={}){a$1(e.proposal,f$1,"Workspace repair proposal");let r=c$1.resolve(e.workspacePath),t=JSON.parse(JSON.stringify(e.proposal));if(t.goalId){let p=await l({workspacePath:r,goalId:t.goalId});if(!p.active||p.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(p.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${p.goalPack?.state??"missing"}`);if((p.active.repairTransactionIds??(p.active.repairTransactionId?[p.active.repairTransactionId]:[])).length>=p.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${p.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(p.goalPack.scope.kind==="project"||p.goalPack.scope.kind==="project-set"){let S=p.goalPack.scope.projects;if(!t.projectName||!S.includes(t.projectName))throw new Error(p.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${S[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${S.join(", ")}).`)}}let o=e.maxRisk??"guarded",i={maxRisk:o,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},n=[],s=[],h=new Set(["replan","manual-repair","cancel"]),l$1=await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"));n.push({id:"workspace-root",status:l$1?"passed":"failed",message:l$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let d;try{d=await Za({workspacePath:r,proposal:t});}catch(p){s.push(p instanceof Error?p.message:String(p));}let g=d&&!x(r,d)&&t.projectName?`external/${t.projectName}`:void 0;if(d&&(t.projectName||t.projectPath)&&(t.projectPath=g??c$1.relative(r,d).split(c$1.sep).join("/")),t.projectPath){let p=d??c$1.resolve(r,t.projectPath),N=await k.lstat(p).catch(()=>{});(!N?.isDirectory()||N.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(p=>({...p,cwd:Re(r,p.cwd,d,g)}));let b$1=new Set,y=new Set,P=0;for(let p of t.changes){p.path=Re(r,p.path,d,g),p.path==="."&&s.push(`${p.id} cannot replace the workspace root.`),b$1.has(p.id)&&s.push(`Duplicate proposal change id: ${p.id}.`),y.has(p.path)&&s.push(`Multiple proposal changes target ${p.path}.`),b$1.add(p.id),y.add(p.path),P+=Buffer.byteLength(p.content??"","utf8"),P>za&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let N=Da(p.path);if(N&&s.push(`${p.path}: ${N}`),p.operation==="write"){let S=st(p.path,p.content);S&&s.push(S);}if(G[p.risk]>G[o]&&(s.push(`${p.id} exceeds the approved ${o} risk ceiling.`),h.add(p.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let S=d??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ne=await T({workspacePath:r,value:p.path,projectBoundary:S,projectName:t.projectName});x(S,ne)||s.push(`${p.path} escapes the declared project scope.`);}}let E=[...y].sort(),q=await $e(r,E,d);s.push(...q.errors);let f=new Map(q.entries.map(p=>[p.path,p]));for(let p of t.changes){let N=f.get(p.path);if(!N||N.beforeHash!==p.expectedBeforeHash){s.push(`${p.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}p.operation==="delete"&&!N.existed&&s.push(`${p.path} cannot be deleted because it does not exist.`),p.operation==="write"&&N.beforeHash!==null&&$(p.content??"")===N.beforeHash&&s.push(`${p.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 m=new Set;if(t.projectPath)m.add(d??c$1.resolve(r,t.projectPath));else for(let p of t.changes)m.add(await ct(r,p.path));let w=await ut({workspacePath:r,proposal:t,projectRoots:[...m].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...w.blockers);let D=w.stages,J=D.some(p=>p.status!=="skipped"&&["audit","test","build"].includes(p.kind));n.push({id:"validation-coverage",status:J?"passed":"unknown",message:J?"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([...E,...w.checkpointFiles])].sort(),F=await $e(r,W,d);s.push(...F.errors),n.push({id:"checkpoint-boundary",status:F.errors.length===0?"passed":"failed",message:F.errors.length===0?`${F.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:F.errors.join(" ")});let B=[{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(p=>({id:`proposal:${p.id}`,kind:"repair",status:G[p.risk]<=G[o]?"pending":"blocked",required:true,risk:p.risk,summary:p.summary,changedPaths:[p.path]})),...D,{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:B,toolAvailable:a$3.toolAvailable}));let oe=new Set(B.map(p=>p.id));oe.size!==B.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:oe.size===B.length?"passed":"failed",message:oe.size===B.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let p=false,N=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),S=N.actions.filter(I=>I.cardId===t.cardId&&(!t.projectName||I.projectName===t.projectName)&&(!t.projectPath||I.projectPath===t.projectPath));if(!t.targetActionIds?.length){let I=va(S);I.size===1?t.targetActionIds=S.map(Oa=>Oa.id).sort():I.size>1&&(p=true,s.push(`Repair proposal target is ambiguous: ${I.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ne=[...new Set(t.targetActionIds??[])],Ne=new Set(ne),u=N.actions.filter(I=>Ne.has(I.id)),C=new Set(u.map(I=>I.id)),O=ne.filter(I=>!C.has(I));O.length>0&&(p=true,s.push(`Repair proposal references stale or unknown causal action ids: ${O.join(", ")}.`)),u.filter(I=>I.cardId!==t.cardId||t.projectName!==void 0&&I.projectName!==t.projectName||t.projectPath!==void 0&&I.projectPath!==t.projectPath).length>0&&(p=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let _=va(u);_.size>1&&(p=true,s.push(`Repair proposal combines ${_.size} independent causal finding families. Create one transaction per finding family.`)),u.length>0&&!t.blockerSignature&&(p=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(u.map(I=>I.projectName??I.projectPath).filter(I=>!!I)).size>0&&!t.projectName&&!t.projectPath&&(p=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),u.length>0&&u.every(I=>I.mode==="run-command"&&I.transaction?.kind==="dependency-materialization"&&I.transaction.sourceMutationRequired===false)&&(p=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:!p&&(u.length>0||S.length===0)?"passed":"failed",message:u.length>0?`${u.length} action(s) bind this proposal to one canonical causal target.`:S.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=Wa(u);Ue&&n.push(Ue);}catch{}let X=$(V(t)),ue={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(p=>`proposal:${p.id}`)},Z=M(a$3.now),L=`repair_${randomUUID().replaceAll("-","")}`,ie=n.some(p=>p.status==="failed")||s.length>0,ke=[...s,...n.filter(p=>p.status==="failed"&&p.id!=="proposal-boundary").map(p=>p.message)],he=Ea({adapters:w.adapters,preconditions:n,stages:B,decisionOptions:h,maxRisk:o,fallbackReasons:ke});for(let p of t.changes)G[p.risk]<=G[o]||he.push({kind:"risk-approval",id:`risk:${p.id}`,message:`${p.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let we=he.length>0&&he.every(p=>p.kind==="failed-precondition")&&n.some(p=>p.id==="proposal-boundary"&&p.status==="failed"),xe=we?["replan","cancel"]:[...h],U={schemaVersion:a,transactionId:L,revision:1,createdAt:Z,updatedAt:Z,workspace:{name:await it(r),rootRef:"."},target:ue,state:ie?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:w.adapters,checkpoint:{status:"pending",files:F.entries},stages:B,...ie?{decision:{reason:[...new Set(ke)].join(" "),options:xe,causes:he}}:{},events:[],integrity:{sourceEvidenceHash:X,planHash:Ke({sourceEvidenceHash:X,target:ue,policy:i,preconditions:n,adapterEvaluations:w.adapters,stages:B,checkpointFiles:F.entries})}};A(U,"planned",ie?we?"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(U,c,"Workspace repair transaction");let ge=await $a(r,U);if(ge)return ge;let Ie=de(r,L);return await k.ensureDir(Ie),await re(Ge(r,L),t),await re(Se(r,L),U),await re(c$1.join(r,b),U),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:L}),U}async function Zt(e,a={}){let r=await pe(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=H("The compiled repair plan changed after planning.",["cancel"]),await j(e.workspacePath,r,a.now),r;let t=await We(e.workspacePath,e.transactionId);return $(V(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=H("The persisted source plan changed after planning.",["cancel"]),await j(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:M(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",A(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await j(e.workspacePath,r,a.now),r)}async function Ba(e,a){let r=c$1.join(e,Le,La);await k.ensureDir(c$1.dirname(r));try{let t=await k.stat(r),o=await k.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(l){s=l!==null&&typeof l=="object"&&"code"in l&&l.code==="EPERM";}let h=!!(i&&i!==hostname());!s&&!h&&Date.now()-t.mtimeMs>Ka&&await k.remove(r);}catch{}try{await k.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 k.readJson(r).catch(async()=>{let o=await k.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await k.remove(r);}}async function Fa(e){let a=await ee(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 ft(e){if(e.transaction.checkpoint.status==="captured")return;await Fa(e);let a=c$1.join(de(e.workspacePath,e.transaction.transactionId),wa);await k.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=await ee(e.workspacePath,e.transaction),i=await T({workspacePath:e.workspacePath,value:t.path,projectBoundary:o,projectName:e.transaction.target.projectName}),n=t.existed?await k.readFile(i):void 0;if(n&&$(n)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let s=`${wa}/${String(r).padStart(4,"0")}.bin`;if(n){let h=c$1.join(de(e.workspacePath,e.transaction.transactionId),s),l=`${h}.${process.pid}.${randomUUID()}.tmp`;await k.writeFile(l,n,{flag:"wx"});let d=await k.readFile(l);if($(d)!==t.beforeHash)throw await k.remove(l),new Error(`Checkpoint backup verification failed for ${t.path}.`);await k.move(l,h,{overwrite:true}),t.backupRef=s;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=M(e.now),e.transaction.state="checkpointed",A(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function Ra(e,a){let r=await ee(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 k.readFile(o).catch(()=>{});t.afterHash=i?$(i):null;}}function Te(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Je(e,a,r,t=[]){let o=c$1.resolve(e,a.cwd);if(!(x(e,o)||t.some(l=>x(l,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(l=>!l||/[\0\r\n]/.test(l)))throw new Error("Invocation contains invalid arguments.");let n=Te(a.executable),s=c$1.isAbsolute(a.executable),h=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!x(e,a.executable)&&!t.some(l=>x(l,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!s&&!h&&!Ua.has(n))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(l=>/^(?:--force|-f)$/i.test(l)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(l=>/(?:breaking|legacy-peer-deps)/i.test(l)))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 _e(e){let a=e.projectBoundary?[c$1.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 k.lstat(t.cwd).catch(()=>{});if(!o?.isDirectory()||o.isSymbolicLink()||!await K(e.projectBoundary??e.workspacePath,t.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(t.executable)||/^\.{1,2}[\\/]/.test(t.executable)){let s=c$1.isAbsolute(t.executable)?t.executable:c$1.resolve(t.cwd,t.executable);if(!await K(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 mt(e){let a=k$1.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function kt(e){let a=k$1.find(d=>d.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await k.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}):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);let o=a.scope==="project"?t:e.workspacePath;if(!await K(o,t))throw new Error("The target producer working directory escapes the workspace boundary.");let i=c$1.resolve(t,a.producerArtifact);if(!x(t,i)||!await K(t,c$1.dirname(i)))throw new Error("The target producer artifact escapes its canonical scope.");let n=await k.stat(i).catch(()=>{}),s=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),h=await execa(process.execPath,[r,...mt(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"}}),l=await k.stat(i).catch(()=>{});return {exitCode:h.exitCode??null,stdout:h.stdout??"",stderr:h.stderr??"",evidenceProduced:!!(l?.isFile()&&(!n||l.mtimeMs!==n.mtimeMs||l.ctimeMs!==n.ctimeMs||l.size!==n.size))}}async function wt(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=ce(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=ce(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 bt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(h=>!h.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(h=>h.id)),o=a.filter(h=>!t.has(h)),i=e.transaction.preconditions.map(h=>h.id).find(h=>h.startsWith(Me))?.slice(Me.length),n=r.actions.filter(h=>t.has(h.id)&&a.includes(h.id)),s=o.length===0&&!!i&&Sa(n)!==i;return {current:o.length===0&&!s,missingActionIds:o,semanticDrift:s}}function Q(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function vt(e,a){if(a.type==="file-create")return l$1({projectPath:e,operation:a});if(a.type==="file-append")return m$1({projectPath:e,operation:a});if(a.type==="file-copy")return n({projectPath:e,operation:a});if(a.type==="package-json-script")return k$2({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return p$3({projectPath:e,operation:a});if(a.type==="env-key-add")return q({projectPath:e,operation:a});if(a.type==="makefile-target")return r({projectPath:e,operation:a})}async function Pt(e){let a=await ee(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!x(a,r)||!await K(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Da(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(g=>g.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await k.readFile(r).catch(()=>{}),n=i?$(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await k.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 k.remove(r);return}let h=e.change.content??"";if(Buffer.byteLength(h,"utf8")>Ia)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await k.ensureDir(c$1.dirname(r));let l=c$1.join(c$1.dirname(r),`.${c$1.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await k.writeFile(l,h,{encoding:"utf8",flag:"wx"}),await k.move(l,r,{overwrite:true});let d=await k.readFile(r);if($(d)!==$(h))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function ja(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=M(e.dependencies.now),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await j(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:""}):kt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=Q(r.stdout),e.stage.stderrTail=Q(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=Q(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 bt({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 Pt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=Ce(a.action);if(r){let t=await le(e.workspacePath,a.action),o=await ee(e.workspacePath,e.transaction)??e.workspacePath;if(!await K(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await vt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??_e)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=Q(t.stdout),e.stage.stderrTail=Q(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??_e)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=Q(a.stdout),e.stage.stderrTail=Q(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=M(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 Ra(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=M(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await Ra(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ye(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",A(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=H(n,["manual-repair","cancel"]),A(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ee(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(!x(o,s)||!await K(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let h=await k.lstat(s).catch(()=>{});if(h?.isSymbolicLink()||h&&!h.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let l=h?await k.readFile(s):void 0,d=l?$(l):null,g=n.afterHash!==void 0&&d===n.afterHash,b=a&&d===n.beforeHash;if(!g&&!b)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 y=c$1.join(de(e.workspacePath,e.transaction.transactionId),n.backupRef),P=await k.lstat(y).catch(()=>{});if(!P?.isFile()||P.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let E=await k.readFile(y);if($(E)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:E});}for(let n of t){if(!n.entry.existed){await k.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let h=c$1.join(c$1.dirname(n.absolute),`.${c$1.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await k.ensureDir(c$1.dirname(n.absolute)),await k.writeFile(h,s,{flag:"wx"}),n.entry.mode!==void 0&&await k.chmod(h,n.entry.mode),await k.move(h,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=M(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 h=`rollback:${n.id}`,l=e.transaction.stages.find(b=>b.id===h&&b.kind==="rollback"),d=l??{id:h,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};l||e.transaction.stages.push(d),d.status="running",d.startedAt=M(e.dependencies.now),delete d.completedAt,delete d.exitCode,delete d.stdoutTail,delete d.stderrTail,A(e.transaction,"rollback",d.summary,{stageId:d.id,status:"running",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now);let g;try{g=await(e.dependencies.runInvocation??_e)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});}catch(b){g={exitCode:null,stdout:"",stderr:b instanceof Error?b.message:String(b)};}if(d.exitCode=g.exitCode,d.stdoutTail=Q(g.stdout),d.stderrTail=Q(g.stderr),d.completedAt=M(e.dependencies.now),g.exitCode!==0)return d.status="failed",d.summary=g.stderr||g.stdout||`Rollback reconciliation exited with ${g.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=H(`Source files were restored, but the installed dependency tree could not be reconciled: ${d.summary}`,["manual-repair","cancel"]),A(e.transaction,"decision",e.transaction.decision.reason,{stageId:d.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false;d.status="passed",d.summary="Installed dependency tree reconciled with the restored source state.",A(e.transaction,"rollback",d.summary,{stageId:d.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,A(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),true}async function Qt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Ba(r,e.transactionId);try{let o=await pe({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=H("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await j(r,o,a.now),o;let i=await We(r,e.transactionId);if($(V(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=H("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await j(r,o,a.now),o;if(o.state==="approved"&&ce(i)&&i.goalId){let m=await l({workspacePath:r,goalId:i.goalId}),w=m.active?.repairTransactionIds??(m.active?.repairTransactionId?[m.active.repairTransactionId]:[]);if(m.index.activeGoalId!==i.goalId||!w.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(m=>m.status==="failed");if(s){let m=o.stages.find(w=>w.invocation&&`tool:${w.invocation.cwd}:${w.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=H(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...m?{executable:m}:{}}),A(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await j(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 ye({workspacePath:r,transaction:o,dependencies:a}),o}let h=new Map(ce(i)?i.changes.map(m=>[`proposal:${m.id}`,{kind:"proposal",change:m}]):i.actions.map(m=>[`action:${m.id}`,{kind:"canonical",action:m}]));try{await Fa({workspacePath:r,transaction:o});}catch(m){return o.approval.status="expired",o.state="decision-required",o.decision=H(m instanceof Error?m.message:String(m),["cancel"]),A(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await j(r,o,a.now),o}let l$1=o.stages.find(m=>m.id==="target-precondition");if(!l$1)return o.approval.status="expired",o.state="decision-required",o.decision=H("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await j(r,o,a.now),o;if(!await ja({workspacePath:r,transaction:o,stage:l$1,actions:h,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=H(`Target precondition failed before checkpoint: ${l$1.summary}`,["cancel"]),A(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await j(r,o,a.now),o;try{await ft({workspacePath:r,transaction:o,now:a.now});}catch(m){return o.approval.status="expired",o.state="decision-required",o.decision=H(m instanceof Error?m.message:String(m),["cancel"]),A(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await j(r,o,a.now),o}o.state="executing",await j(r,o,a.now);for(let m of o.stages.filter(w=>w.id!=="target-precondition"&&w.id!=="canonical-verify"&&w.kind!=="rollback"))if(!await ja({workspacePath:r,transaction:o,stage:m,actions:h,dependencies:a})&&m.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H(`Required stage ${m.id} failed: ${m.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let g=o.stages.find(m=>m.id==="canonical-verify");if(!g)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o;g.status="running",g.startedAt=M(a.now),A(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:g.id,status:"running",now:a.now}),await j(r,o,a.now);let b;try{b=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(m){b={status:"failed",exitCode:1,artifactPath:p$1.intelligenceRun},g.stderrTail=Q(m instanceof Error?m.message:String(m));}let y=b.status==="passed"&&b.exitCode===0?"passed":b.status==="failed"||b.exitCode===1?"failed":"blocked",P=await wt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:y}),E=P.status==="passed"&&y!=="failed",q,f;if(E&&ce(i)&&i.goalId){let m=await a$3(r);if(m.status==="miss")E=false,f=`Goal-bound repair could not seal its post-repair Model/Graph source state (${m.reason}).`;else {let w=m.graph.source.inputs?.hash;w?q={modelHash:d(m.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$3(m.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:w}:(E=false,f="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return g.status=E?"passed":"failed",g.completedAt=M(a.now),g.exitCode=b.exitCode,g.summary=E&&y==="passed"?"Selected repair target and canonical workspace verification passed.":E?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":f||(P.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${y}.`),o.verification={status:E?"passed":"failed",targetStatus:P.status,workspaceStatus:y,remainingActionIds:P.remainingActionIds,artifact:p$1.intelligenceRun,exitCode:b.exitCode,summary:g.summary,...q?{sourceBinding:q}:{}},A(o,"verification",g.summary,{stageId:g.id,status:g.status,now:a.now}),E?(o.state="closed",delete o.decision,A(o,"closed",g.summary,{status:"passed",now:a.now}),o.integrity.closureHash=qa(o),await j(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H(g.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function yt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Ba(r,e.transactionId);try{let o=await pe({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 ye({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function er(e,a={}){let r=await pe(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,A(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await j(e.workspacePath,r,a.now),r}async function ar(e,a={}){let r=c$1.resolve(e.workspacePath),t=await pe({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 yt({workspacePath:r,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(t.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,A(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await j(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 We(r,e.transactionId),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},n=async()=>{if(ce(o))return gt({workspacePath:r,proposal:o,...i},a);let l=t.target.actionIds.map(d=>d.startsWith("action:")?d.slice(7):d);return ht({workspacePath:r,cardId:t.target.cardId,...l.length===1?{actionId:l[0]}:{},projectName:t.target.projectName,...i},a)},s=t.decision.causes?.some(l=>l.kind==="missing-executable"),h=e.decision==="replan"&&s?await n():void 0;return h?.transactionId===t.transactionId?t:(t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,A(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await j(r,t,a.now),h??n())}async function Rt(e){let a=c$1.join(e,Le,"transactions"),r=await k.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>pe({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Zt as approveWorkspaceRepair,Xt as assertClosedGoalRepairTransactionCurrent,er as cancelWorkspaceRepair,ar as decideWorkspaceRepair,mt as exactCardProducerArgs,Qt as executeWorkspaceRepair,Yt as inspectWorkspaceRepairCapabilities,Rt as listWorkspaceRepairTransactions,ht as planWorkspaceRepair,gt as planWorkspaceRepairProposal,pe as readWorkspaceRepairTransaction,yt as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as resolveWorkspaceRunStageTimeoutMs,b as runWorkspaceStage}from'./chunk-4AW5QP5J.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-37SWTS2B.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-C563KVBD.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-S66NO5BX.js';
@@ -1 +1 @@
1
- import {a}from'./chunk-2KJNASF3.js';import {d,s,m as m$1}from'./chunk-ZOE43SGQ.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};
1
+ import {a}from'./chunk-SS7X2YF5.js';import {d,s,m as m$1}from'./chunk-BVWDG66W.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};
@@ -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.71.0 \
66
+ --tag v0.72.1 \
67
67
  --markdown-output /tmp/workspai-discord-announcement.md
68
68
  ```
69
69
 
@@ -301,7 +301,9 @@ complete graph. New responses also expose `graphSourceHash`, allowing IDE and
301
301
  agent activity consumers to correlate returned entity/proof IDs only with the
302
302
  exact Graph revision that authored them. Ranking is deterministic and offline: it removes natural-language
303
303
  stopwords, weights rarer graph terms more strongly, and prefers exact labels and
304
- identities. `workspace graph benchmark <query> --limit <n> --json` compares
304
+ identities. Authored source ranks ahead of compiled, generated, vendored,
305
+ fixture, and test-data matches unless the query explicitly names one of those
306
+ surfaces. `workspace graph benchmark <query> --limit <n> --json` compares
305
307
  that retrieval payload with the readable proof-indexed corpus using a labelled
306
308
  `characters / 4` estimate. It measures payload reduction only; it does not
307
309
  assert equivalent answer quality or model-specific billing savings.
@@ -319,6 +321,9 @@ verified outcomes. See [Workspace Intelligence Benchmark](./workspace-intelligen
319
321
 
320
322
  Add `--scope project:<name>` to retrieve project-owned facts plus
321
323
  workspace-level shared entities proven to be connected to that project. The
324
+ same scope constrains exact entity aliases used by `graph evidence` and `graph
325
+ path`; a matching alias in another project cannot make a scoped target
326
+ ambiguous. The
322
327
  `search` mode also accepts `--kind <entity-kind>` so agents can retrieve a
323
328
  precise semantic surface such as `runtime-unit`, `endpoint`, or `owner`. The
324
329
  agent projection reports explicit omission budgets for relations, related
@@ -384,6 +389,12 @@ lifecycle units to `workspace run`; inspect them without execution using
384
389
  `workspace run <stage> --plan`, and select one runtime family with
385
390
  `--runtime <runtime>`.
386
391
 
392
+ For npm, pnpm, and Cargo monorepos, the owning workspace manifest represents its
393
+ matching members as one dependency-materialization boundary. Explicitly
394
+ registered nested projects remain independent, while aggregate parents do not
395
+ execute them a second time. Embedded eval, benchmark, integration, test-data,
396
+ and fixture manifests are excluded unless they expose real lifecycle evidence.
397
+
387
398
  Core module/template commands are intentionally narrower than runtime detection.
388
399
  RapidKit Core modules are guaranteed only for RapidKit Core module-enabled kits:
389
400
  `fastapi.standard`, `fastapi.ddd`, and `nestjs.standard`. They are not enabled
@@ -480,7 +491,10 @@ Supported keys: `mode`, `dependency_sharing_mode`, `rules.enforce_workspace_mark
480
491
 
481
492
  ## Setup and warm dependencies
482
493
 
483
- `setup <runtime>` validates toolchain and updates `.workspai/toolchain.lock`.
494
+ `setup <runtime>` validates an already installed host runtime and updates
495
+ `.workspai/toolchain.lock`. It does not install system runtimes. When the executable is missing,
496
+ the remediation plan emits an external prerequisite and blocks setup/bootstrap until fresh
497
+ environment evidence is available.
484
498
 
485
499
  `--warm-deps` adds optional dependency warm-up (Node lock/deps, Go modules). Warm-deps is non-fatal and reports `completed` / `failed` / `skipped`.
486
500
 
@@ -132,7 +132,10 @@ handoff for governance artifacts outside Doctor: Bootstrap compliance, Analyze,
132
132
  Pipeline, Workspace Run, Workspace Verify, and Doctor plan bridging. Consumers should ask npm for
133
133
  this plan before inventing per-card repair logic. The plan carries ordered actions, safe file
134
134
  operations where deterministic, refresh/verify commands, risk, approval state, and rollback
135
- strategy.
135
+ strategy. Each action can also declare typed executable/action requirements and a retry boundary.
136
+ The root `execution` projection identifies actions eligible in the current environment and one
137
+ canonical next action, so IDEs do not infer readiness from array order. Missing host tools produce
138
+ guidance plus blocked downstream actions; they are never advertised as executable.
136
139
 
137
140
  When `doctor project` runs inside a workspace, the project-local report is written beside the
138
141
  project and the workspace receives both a latest alias and a collision-safe project copy under
@@ -21,6 +21,13 @@ Checks host prerequisites:
21
21
  - pipx (optional)
22
22
  - RapidKit Core availability
23
23
  - Go (optional)
24
+ - Windows `workspai` PATH resolution and npm-shim precedence
25
+
26
+ The PATH check is reported as typed Doctor evidence instead of running during
27
+ package installation. A normal `npm install -g workspai` therefore requires no
28
+ install-script authorization. On Windows, a shadowed npm shim is an advisory:
29
+ Doctor reports the active executable, the ordered matches, and the bounded
30
+ `npx --yes workspai <command>` fallback without mutating PATH.
24
31
 
25
32
  ### 2) Workspace Check
26
33
 
@@ -179,6 +186,12 @@ runtime health endpoint, database migrations, or an executable boot entrypoint
179
186
  are retained as explicit `not-applicable` evidence for non-deployable
180
187
  archetypes instead of becoming false warnings.
181
188
 
189
+ Frontend application-only probes follow the same rule. Framework config,
190
+ application source-tree, and application script checks are `not-applicable` for
191
+ libraries, SDKs, platforms, plugins, and monorepo roots. Tooling dependencies at
192
+ a private workspace root therefore do not create a false frontend application
193
+ or an irrelevant repair such as adding an application test script.
194
+
182
195
  The default terminal view is summary-first and uses portable boundaries such
183
196
  as `$WORKSPACE`, `$PROJECT`, and `external/<project>`. `--verbose` expands all
184
197
  probes and lifecycle capabilities. JSON continues to retain canonical absolute
@@ -575,6 +588,13 @@ These probes are intentionally evidence-first. Missing optional surfaces are sur
575
588
  or manual repair capabilities, while deterministic repairs are promoted into `--fix` only when the
576
589
  change is safe enough for Doctor to apply with approval and post-fix verification.
577
590
 
591
+ Runtime-dependent repairs are executable only when the required host tool can
592
+ actually launch from the governed working directory. Doctor and the Repair
593
+ executor use the same probe for Node, Python, Go, JVM, Rust, .NET, PHP, Ruby,
594
+ and other supported runtimes. An unavailable executable is represented as a
595
+ typed prerequisite with a blocking reason and retry policy; dependent setup or
596
+ dependency steps remain blocked until fresh evidence proves the prerequisite.
597
+
578
598
  Workspace scans are bounded and cache-safe. Doctor fingerprints manifests plus relevant source,
579
599
  test, and module trees, includes content hashes for small files, writes cache artifacts atomically,
580
600
  and limits project concurrency (four workers by default; configurable with
@@ -538,6 +538,17 @@ Use full graph export for interchange or offline analysis. Use bounded search
538
538
  for interactive agents. The latter keeps response size proportional to the
539
539
  question instead of workspace size.
540
540
 
541
+ Interactive ranking preserves source intent. When otherwise relevant matches
542
+ compete, authored source is preferred over compiled output, generated code,
543
+ vendored dependencies, fixtures, and test-data. Those surfaces remain
544
+ retrievable when the query explicitly asks for them; they are not silently
545
+ removed from the canonical Graph.
546
+
547
+ Project scope also applies while resolving exact evidence and path endpoints.
548
+ Aliases from another project cannot make a scoped target ambiguous, and shared
549
+ workspace entities are admitted only when the Graph proves their connection to
550
+ the selected project.
551
+
541
552
  ### Runtime-generated API topology
542
553
 
543
554
  When an authored API contract is wired through framework registration or
@@ -160,7 +160,10 @@ tool before the environment-creation stage runs.
160
160
  next repair target and never trigger rollback of a valid bounded repair.
161
161
  - Required executables are resolved before approval and again immediately before execution. A
162
162
  missing, broken-shebang, or changed toolchain expires approval instead of starting a partial
163
- transaction. Filesystem presence alone is not launchability proof.
163
+ transaction. Filesystem presence alone is not launchability proof. Planning and execution use
164
+ the same launchability probe across every runtime adapter. A missing executable forbids retry of
165
+ the unchanged plan generation; install or configure it externally, refresh evidence, and create
166
+ a fresh plan.
164
167
  - The exact card producer is run twice: first as a no-mutation causal precondition, then after
165
168
  repair as card-local evidence. An aggregate workspace gate cannot substitute for either run.
166
169
  - A Goal-bound proposal is linked to the active Goal before execution. Closure seals the fresh
@@ -184,6 +187,11 @@ transaction. If a manifest, required executable, isolated environment, project-d
184
187
  validation, or audit surface is unavailable, the engine returns `decision-required`; it never
185
188
  hides the gap behind a model fallback.
186
189
 
190
+ Runtime prerequisites form an explicit dependency graph: host executable, canonical toolchain
191
+ pin, workspace bootstrap, dependency materialization, declared test/build stages, and canonical
192
+ verification. `workspai setup <runtime>` validates and pins an already installed host runtime; it
193
+ does not silently install system software.
194
+
187
195
  The same capability contract publishes an executable qualification matrix over
188
196
  adapter, scope, failure family, and recovery path. Every failure family has one
189
197
  bounded terminal policy: refresh stale/missing evidence, replan no-op/source
@@ -35,6 +35,19 @@ family. Vendored trees, build outputs, fixtures, and nested test fixture package
35
35
  manifests are excluded from lifecycle discovery so orchestration does not turn
36
36
  sample inputs into install targets.
37
37
 
38
+ Workspace ownership is resolved before commands are selected. An npm
39
+ `workspaces` declaration, `pnpm-workspace.yaml`, or Cargo `[workspace]` owns
40
+ matching member manifests and their explicit exclusions. Workspai therefore
41
+ runs the owning install or fetch command once instead of scheduling the same
42
+ dependency materialization for every member. Metadata-only packages and nested
43
+ eval, benchmark, integration, test-data, and fixture inputs are not promoted to
44
+ standalone lifecycle units without executable lifecycle evidence.
45
+
46
+ Registered project boundaries take precedence over aggregate discovery. When a
47
+ nested directory is already an explicit workspace project, an aggregate parent
48
+ does not execute that child's runtime unit again. `--plan --json` exposes the
49
+ resulting ownership so operators can review the exact units before execution.
50
+
38
51
  Planning and `init` do not require Doctor or release-readiness evidence. Real
39
52
  `test`, `build`, and `start` runs enforce the `doctor-workspace` and `readiness`
40
53
  gates by default. A failed gate prevents project commands from starting and is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workspai",
3
- "version": "0.71.0",
3
+ "version": "0.72.1",
4
4
  "type": "module",
5
5
  "description": "Open-source workspace intelligence CLI for software systems: create, adopt, govern, verify, and align polyglot workspaces for humans, CI, IDEs, and AI agents.",
6
6
  "keywords": [
@@ -60,7 +60,6 @@
60
60
  "rapidkit.config.example.cjs",
61
61
  "data/modules-embeddings.json",
62
62
  "scripts/enforce-package-manager.cjs",
63
- "scripts/check-cli-resolution.cjs",
64
63
  "scripts/check-agent-customization-drift.mjs",
65
64
  "scripts/enterprise-package-smoke.mjs",
66
65
  "scripts/prepack-enterprise.mjs"
@@ -70,7 +69,6 @@
70
69
  "access": "public"
71
70
  },
72
71
  "scripts": {
73
- "postinstall": "node scripts/check-cli-resolution.cjs",
74
72
  "check:package-manager": "node scripts/enforce-package-manager.cjs",
75
73
  "sync-kits": "bash scripts/sync-kits.sh",
76
74
  "sync:kits": "corepack npm run sync-kits",
@@ -80,7 +78,6 @@
80
78
  "dev:local": "corepack npm run build && corepack npm link",
81
79
  "install:local": "corepack npm unlink -g workspai || true && corepack npm run build && corepack npm link",
82
80
  "uninstall:local": "corepack npm unlink -g workspai || true",
83
- "prepare": "node scripts/prepare-husky.mjs",
84
81
  "test:e2e:first-install": "bash scripts/e2e-first-install.sh",
85
82
  "test:e2e:user-first-install": "bash scripts/e2e-user-first-install.sh",
86
83
  "test:prebuild": "tsup",
@@ -214,11 +214,15 @@ const REQUIRED_PACKAGE_FILES = [
214
214
  'templates/kits/nestjs-standard/package.json.j2',
215
215
  'workspai.config.example.cjs',
216
216
  'rapidkit.config.example.cjs',
217
- 'scripts/check-cli-resolution.cjs',
218
217
  'scripts/enforce-package-manager.cjs',
219
218
  ];
220
219
 
221
- const FORBIDDEN_PACKAGE_FILES = ['workspai.config.example.js', 'rapidkit.config.example.js'];
220
+ const FORBIDDEN_PACKAGE_FILES = [
221
+ 'workspai.config.example.js',
222
+ 'rapidkit.config.example.js',
223
+ 'scripts/check-cli-resolution.cjs',
224
+ 'scripts/prepare-husky.mjs',
225
+ ];
222
226
 
223
227
  function isPublishedByFilesPolicy(packageJson, assetPath) {
224
228
  const files = packageJson.files ?? [];
@@ -238,6 +242,14 @@ function assertPackageFilesPolicy(requiredFiles) {
238
242
  if ('rapidkit' in (packageJson.bin ?? {})) {
239
243
  fail('package.json#bin.rapidkit must stay in the legacy rapidkit package, not workspai');
240
244
  }
245
+ const consumerLifecycleScripts = ['preinstall', 'install', 'postinstall', 'prepare'].filter(
246
+ (scriptName) => typeof packageJson.scripts?.[scriptName] === 'string'
247
+ );
248
+ if (consumerLifecycleScripts.length > 0) {
249
+ fail(
250
+ `package.json must not require consumer install-script authorization: ${consumerLifecycleScripts.join(', ')}`
251
+ );
252
+ }
241
253
  for (const required of requiredFiles) {
242
254
  if (!isPublishedByFilesPolicy(packageJson, required)) {
243
255
  fail(`package.json#files does not publish ${required}`);
@@ -1 +0,0 @@
1
- export{b as printAnalyzeReport,a as runAnalyze}from'./chunk-554W2TXP.js';
@@ -1 +0,0 @@
1
- export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-26VNCHVV.js';
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-LPCWROQ3.js';import {q,p,r as r$1,t}from'./chunk-ODK4LCEL.js';var R=q.repairTransaction,C=p.repairTransaction,E=r$1.repairTransaction;var y="workspai.workspace-repair-proposal.v1",j="contracts/workspace-intelligence/workspace-repair-proposal.v1.json";var A="workspai.workspace-repair-capabilities.v1",b="workspai.workspace-repair-consumer-protocol.v1",v=["project","workspace","linked-project","polyglot-project"],d=["missing-tool","stale-evidence","missing-artifact","no-op-proposal","source-drift","validation-failure","producer-failure","provider-outage","interrupted-rollback","unsupported-runtime"],u=["automatic-refresh","bounded-replan","decision-required","checkpoint-rollback","durable-resume","manual-repair"],w={"missing-tool":"decision-required","stale-evidence":"automatic-refresh","missing-artifact":"automatic-refresh","no-op-proposal":"bounded-replan","source-drift":"bounded-replan","validation-failure":"checkpoint-rollback","producer-failure":"bounded-replan","provider-outage":"durable-resume","interrupted-rollback":"durable-resume","unsupported-runtime":"manual-repair"};function P(){let i=[],s=c.map(o=>o.id);new Set(s).size!==s.length&&i.push("adapter ids are not unique"),v.length<4&&i.push("scope matrix is incomplete"),d.length<10&&i.push("failure-family matrix is incomplete"),u.length<6&&i.push("recovery-path matrix is incomplete");for(let o of d){let t=w[o];u.includes(t)||i.push(`${o} has no bounded recovery policy`);}for(let o of c)for(let t of ["reconcile","audit","test","build"])o.stages[t]||i.push(`${o.id}.${t} is undeclared`);return i}var c=[{id:"node",ecosystem:"JavaScript / TypeScript",manifests:["package.json"],lockfiles:["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],packageManagers:["npm","pnpm","yarn","bun"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["selected package manager"]},{id:"python",ecosystem:"Python",manifests:["pyproject.toml","requirements.txt"],lockfiles:["uv.lock","poetry.lock","requirements.txt"],packageManagers:["uv","poetry","pip"],support:"conditional",stages:{reconcile:"conditional",audit:"conditional",test:"conditional",build:"declared"},requiredToolFamilies:["isolated Python","selected environment manager","pip-audit or governed Doctor audit"],limitation:"A bounded isolated environment and an installed audit surface are required."},{id:"go",ecosystem:"Go",manifests:["go.mod"],lockfiles:["go.sum"],packageManagers:["go modules"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["go","govulncheck"],limitation:"govulncheck must be installed; the engine never fetches an unreviewed tool."},{id:"rust",ecosystem:"Rust",manifests:["Cargo.toml"],lockfiles:["Cargo.lock"],packageManagers:["cargo"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["cargo","cargo-audit"],limitation:"The cargo-audit subcommand must already be installed."},{id:"php-composer",ecosystem:"PHP",manifests:["composer.json"],lockfiles:["composer.lock"],packageManagers:["composer"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["composer"]},{id:"ruby-bundler",ecosystem:"Ruby",manifests:["Gemfile"],lockfiles:["Gemfile.lock"],packageManagers:["bundler"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"declared",build:"declared"},requiredToolFamilies:["bundle","bundle-audit"],limitation:"bundle-audit and the declared Rake tasks must already exist."},{id:"elixir-mix",ecosystem:"Elixir",manifests:["mix.exs"],lockfiles:["mix.lock"],packageManagers:["mix"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mix","Hex audit task"],limitation:"The project must expose the Hex audit task used by its dependency policy."},{id:"deno",ecosystem:"Deno",manifests:["deno.json","deno.jsonc"],lockfiles:["deno.lock"],packageManagers:["deno"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["deno"]},{id:"dotnet",ecosystem:".NET",manifests:["*.sln","*.csproj","*.fsproj","*.vbproj"],lockfiles:["Directory.Packages.props","packages.lock.json"],packageManagers:["NuGet / dotnet"],support:"full",stages:{reconcile:"native",audit:"native",test:"native",build:"native"},requiredToolFamilies:["dotnet"]},{id:"jvm-maven",ecosystem:"JVM / Maven",manifests:["pom.xml"],lockfiles:[],packageManagers:["Maven Wrapper","Maven"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mvnw or mvn","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"jvm-gradle",ecosystem:"JVM / Gradle",manifests:["build.gradle.kts","build.gradle"],lockfiles:["gradle.lockfile","gradle/libs.versions.toml"],packageManagers:["Gradle Wrapper","Gradle"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["gradlew or gradle","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"clojure",ecosystem:"Clojure",manifests:["deps.edn","project.clj"],lockfiles:[],packageManagers:["Clojure CLI","Leiningen"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"conditional",build:"conditional"},requiredToolFamilies:["clojure or lein","governed project audit"],limitation:"Tests and builds run only when the selected Clojure project surface declares a deterministic entrypoint."},{id:"scala-sbt",ecosystem:"Scala / sbt",manifests:["build.sbt"],lockfiles:[],packageManagers:["sbt"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["sbt","governed project audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."}];function M(){let i=P();if(i.length>0)throw new Error(`Workspace Repair qualification matrix is incomplete: ${i.join("; ")}`);return {schemaVersion:A,owner:"Workspai CLI",workflow:["plan","preconditions","approval","target-precondition","checkpoint","execute","reconcile","audit","test","build","target-producer-verify","canonical-verify","close-or-rollback-or-decision"],invariants:{multiAdapterProjects:true,missingTools:"decision-required",unsupportedEcosystems:"decision-required",silentFallbackToModelExecution:false,mutationAuthority:"cli-only",targetClosure:"selected-causal-action-set",changeReceipt:"checkpoint-hash-delta",consumerTimeline:"durable-transaction-events",typedDecisionCauses:true,registeredLinkedProjectMutationBoundary:true,sourceProposalIntegrity:"project-bound-hash-pinned",completionAuthority:"cli-verification-receipt",goalSourceTransition:"closed-integrity-bound-v1",goalAttemptBudget:"durable-serialized-v1",consumerHandshakeRequired:true,ephemeralProposalsAreEvidence:false,approvalBoundToPlanHash:true,canonicalVerificationRequired:true,rollbackConflictDetection:true},consumerProtocol:{protocolVersion:b,versionProbe:{args:["--version","--json"],schemaVersion:"rapidkit-version-v1"},capabilityProbe:{args:["workspace","repair","capabilities","--json"],schemaVersion:A},invocation:{command:"workspace repair",workspaceResolution:["process-cwd","--workspace"],actions:["capabilities","plan","propose","approve","decide","execute","resume","status","list","rollback","cancel"]},contracts:{operationResult:a$1,proposal:y,transaction:R},transientPaths:[".workspai/repair/inbox/*.json",".workspai/repair/engine.lock"]},qualificationMatrix:{schemaVersion:"workspai.workspace-repair-qualification-matrix.v1",status:"contract-enforced",dimensions:{adapters:c.map(s=>s.id),scopes:v,failureFamilies:d,recoveryPaths:u,failureRecoveryPolicy:w},invariants:{everyAdapterDeclaresClosureStages:true,everyFailureTerminates:true,everyMutationIsCheckpointed:true,workspaceAndProjectScopesUseTheSameEngine:true,linkedProjectsRemainBoundaryChecked:true}},adapters:c}}var V="workspai.studio-card-repair-capabilities.v1",h="npx workspai workspace verify --json",r=p,a=t;function e(i,s,o,t={}){return {cardId:i,scope:t.scope??"workspace",producerCommand:s,producerArtifact:o,verifyCommand:s,verifyArtifact:o,aggregateVerifyCommand:h,targetClosure:"exact-producer-and-causal-action-set",aggregateRepair:"sequential-causal-queue",transactionScope:"one-causal-finding-family",workspacePosture:"reported-separately",repairPolicy:t.repairPolicy??"refresh-producer",remediationArtifacts:t.remediationArtifacts??[]}}var H=[e("doctor","npx workspai doctor workspace --json",r.doctor,{repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.doctorRemediationPlan,a.artifactRemediationPlan]}),e("projectDoctor","npx workspai doctor project --json",a.doctorProject,{scope:"project",repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.doctorRemediationPlan,a.artifactRemediationPlan]}),e("pipeline","npx workspai pipeline --json --strict",a.pipelineLastRun,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("analyze","npx workspai analyze --json",r.analyze,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("readiness","npx workspai readiness --json",r.readiness,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("bootstrap","npx workspai bootstrap --ci --json",a.bootstrapCompliance,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("workspaceSync","npx workspai workspace sync --json",a.workspaceRegistry),e("foundation","npx workspai workspace foundation ensure --json",".workspai/workspace.json"),e("contract","npx workspai workspace contract verify --strict --json",r.contractVerify,{repairPolicy:"source-repair-then-produce"}),e("autopilot","npx workspai autopilot release --json",a.autopilotReleaseLastRun,{repairPolicy:"source-repair-then-produce"}),e("workspaceRun","npx workspai workspace run test --json",a.workspaceRunLast,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("setup","npx workspai setup --json",".workspai/toolchain.lock",{repairPolicy:"source-repair-then-produce"}),e("importReadiness","npx workspai doctor project --json",a.doctorProject,{scope:"project",repairPolicy:"diagnose-and-repair",remediationArtifacts:[a.artifactRemediationPlan]}),e("snapshot","npx workspai snapshot create --json",".workspai/reports/snapshot-last-run.json"),e("workspaceModel","npx workspai workspace model --json --write",r.model),e("intelligenceSnapshot","npx workspai workspace snapshot --json",r.snapshot),e("workspaceDiff",`npx workspai workspace diff --from ${r.snapshot} --json`,r.diff),e("workspaceImpact",`npx workspai workspace impact --from ${r.diff} --json`,r.impact),e("workspaceIntelligenceRun","npx workspai workspace intelligence run --for-agent generic --strict --json",r.intelligenceRun,{repairPolicy:"source-repair-then-produce"}),e("workspaceVerify",h,r.verify,{repairPolicy:"source-repair-then-produce",remediationArtifacts:[a.artifactRemediationPlan]}),e("workspaceExplain","npx workspai workspace explain release-blocked --json --write",r.explain),e("workspaceWhy","npx workspai workspace why release-blocked --json --write",a.workspaceWhy),e("workspaceTrace",`npx workspai workspace trace --from ${r.diff} --json --write`,a.workspaceTrace),e("workspaceWatch","npx workspai workspace watch --once --json",r.model),e("workspaceContextAgent","npx workspai workspace context --for-agent --json --write",r.agentContext),e("agentGrounding","npx workspai workspace agent-sync --write --refresh-context --json --preset enterprise --target vscode",r.agentCustomizationPack),e("share",`npx workspai workspace share --output ${a.workspaceShareBundle} --json`,a.workspaceShareBundle),e("archive","npx workspai workspace export --output team-workspace.workspai-archive.zip --json",".workspai/archive-manifest.json"),e("mirror","npx workspai mirror status --json",a.mirrorOps),e("cache","npx workspai cache status --json",".workspai/cache-config.yml"),e("policy","npx workspai workspace policy show --json",".workspai/policies.yml",{repairPolicy:"source-repair-then-produce"}),e("infra","npx workspai infra plan --json",a.infraPlan,{repairPolicy:"source-repair-then-produce"})];export{R as a,C as b,E as c,y as d,j as e,A as f,c as g,M as h,V as i,H as j};