workspai 0.73.0 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/contracts/runtime-command-surface.v1.json +7 -3
  2. package/dist/analyze-IA33T6MY.js +1 -0
  3. package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-OVTQM7HN.js} +1 -1
  4. package/dist/autopilot-release-T327V7QK.js +1 -0
  5. package/dist/chunk-252EKOR6.js +2 -0
  6. package/dist/{chunk-3GO7BJ5J.js → chunk-4JJDDL3X.js} +1 -1
  7. package/dist/chunk-5EVBOUYW.js +3 -0
  8. package/dist/chunk-5Y4YRYZI.js +12 -0
  9. package/dist/{chunk-J44PN2FX.js → chunk-773WUMFU.js} +15 -15
  10. package/dist/{chunk-FRH7AIGY.js → chunk-BTJPTJLT.js} +2 -2
  11. package/dist/{chunk-OIGI7MP6.js → chunk-C43NXRRE.js} +1 -1
  12. package/dist/chunk-D6BL7ARI.js +2 -0
  13. package/dist/chunk-DLLHUG2Q.js +9 -0
  14. package/dist/chunk-DPC5DKH6.js +2 -0
  15. package/dist/{chunk-R5OJD5K2.js → chunk-DTLLIA2C.js} +1 -1
  16. package/dist/{chunk-LDJAUIAG.js → chunk-FYR4FD7K.js} +1 -1
  17. package/dist/chunk-G6ADWA2B.js +2 -0
  18. package/dist/chunk-H333GKL4.js +3 -0
  19. package/dist/{chunk-EDDGQ6LM.js → chunk-H5DRKXXC.js} +1 -1
  20. package/dist/{chunk-DNKELRK6.js → chunk-IQFXLJIM.js} +1 -1
  21. package/dist/{chunk-UCNIXOTL.js → chunk-IUOMBLRR.js} +1 -1
  22. package/dist/chunk-K3FXRBER.js +4 -0
  23. package/dist/{chunk-TIZCESKY.js → chunk-KCIET26G.js} +1 -1
  24. package/dist/chunk-LEEOZRWR.js +7 -0
  25. package/dist/{chunk-T5NBSCVX.js → chunk-NCZJUPG5.js} +49 -49
  26. package/dist/{chunk-TSYDTKXO.js → chunk-RPM67N7A.js} +1 -1
  27. package/dist/{chunk-NSMRQOWP.js → chunk-SAZXL36B.js} +1 -1
  28. package/dist/chunk-SVGUAVMG.js +1 -0
  29. package/dist/chunk-TBOIXIQA.js +1 -0
  30. package/dist/chunk-TGDXD4CD.js +1 -0
  31. package/dist/{chunk-IPZT6WKM.js → chunk-TVSMNF5G.js} +1 -1
  32. package/dist/{chunk-D3N2WFDV.js → chunk-UHT2SW7O.js} +1 -1
  33. package/dist/chunk-VLKX5U4H.js +13 -0
  34. package/dist/chunk-XF65LQ6M.js +1 -0
  35. package/dist/chunk-ZKYH44ER.js +1 -0
  36. package/dist/{chunk-TZK2R6RD.js → chunk-ZNKZ2KXR.js} +1 -1
  37. package/dist/chunk-ZS7JHATN.js +1 -0
  38. package/dist/{create-XYKXS3JB.js → create-EKA2QG5R.js} +1 -1
  39. package/dist/doctor-BXSNADVR.js +1 -0
  40. package/dist/{goal-lifecycle-BIX2JVNO.js → goal-lifecycle-XXWNMIAD.js} +1 -1
  41. package/dist/{goal-pack-SUWH6K7U.js → goal-pack-NTHYLISY.js} +1 -1
  42. package/dist/index.js +158 -158
  43. package/dist/pipeline-JLOC2SUT.js +5 -0
  44. package/dist/{project-agent-entry-Y3NEHZED.js → project-agent-entry-ZNUHGCVC.js} +1 -1
  45. package/dist/{project-intelligence-lens-6Q6XSUDJ.js → project-intelligence-lens-W72OUEDW.js} +1 -1
  46. package/dist/{proof-carrying-change-456TYEDW.js → proof-carrying-change-WLUPMUO7.js} +1 -1
  47. package/dist/verified-goal-6O2JZOOR.js +1 -0
  48. package/dist/{workspace-ROUEA3RT.js → workspace-XTIGVLGH.js} +1 -1
  49. package/dist/{workspace-agent-sync-6UYG33EQ.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
  50. package/dist/{workspace-context-H7ZXR6VI.js → workspace-context-Y3TNY2XZ.js} +1 -1
  51. package/dist/{workspace-contract-2V2BI6A3.js → workspace-contract-GRZY7WRD.js} +1 -1
  52. package/dist/{workspace-explain-IBMTRUSF.js → workspace-explain-KUYHJFLY.js} +1 -1
  53. package/dist/{workspace-foundation-H5B3TTZD.js → workspace-foundation-ZBUJTR56.js} +1 -1
  54. package/dist/{workspace-graph-stream-YDEET5LK.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
  55. package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
  56. package/dist/{workspace-intelligence-DXKQXTTM.js → workspace-intelligence-26YT6KMN.js} +1 -1
  57. package/dist/{workspace-intelligence-benchmark-L46EGZZM.js → workspace-intelligence-benchmark-QFVTUBDO.js} +1 -1
  58. package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
  59. package/dist/{workspace-intelligence-runner-SCB44IXU.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
  60. package/dist/{workspace-knowledge-graph-BNEVFEOW.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
  61. package/dist/{workspace-knowledge-graph-query-GOC365ZR.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
  62. package/dist/workspace-knowledge-graph-snapshot-JEJMRQZL.js +1 -0
  63. package/dist/workspace-marker-7U3NYRPJ.js +1 -0
  64. package/dist/{workspace-mcp-serve-JLZTTEVG.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
  65. package/dist/{workspace-model-XSNLDUI2.js → workspace-model-2ODVOWDQ.js} +1 -1
  66. package/dist/{workspace-onboarding-IRBVZTT4.js → workspace-onboarding-BY6RUBBH.js} +1 -1
  67. package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
  68. package/dist/{workspace-registry-summary-CBZDSG6I.js → workspace-registry-summary-VKTJ7PHV.js} +1 -1
  69. package/dist/workspace-repair-engine-RBM7NCGI.js +3 -0
  70. package/dist/workspace-run-JCA5WPCR.js +1 -0
  71. package/dist/{workspace-verify-QTRY7WW3.js → workspace-verify-NFJ7RKKT.js} +1 -1
  72. package/dist/{workspace-watch-PDQKYBYQ.js → workspace-watch-3DBBB6IP.js} +1 -1
  73. package/docs/ci-workflows.md +1 -1
  74. package/package.json +1 -1
  75. package/dist/analyze-WC2TY5AT.js +0 -1
  76. package/dist/autopilot-release-LJDRECFW.js +0 -1
  77. package/dist/chunk-2BCECNIW.js +0 -1
  78. package/dist/chunk-2LIVMG5C.js +0 -2
  79. package/dist/chunk-3SNP6M4M.js +0 -2
  80. package/dist/chunk-4HQU2GQM.js +0 -1
  81. package/dist/chunk-4JAURS76.js +0 -13
  82. package/dist/chunk-7O7P4MRD.js +0 -1
  83. package/dist/chunk-AQNU5RXV.js +0 -2
  84. package/dist/chunk-CQBM6BBP.js +0 -2
  85. package/dist/chunk-CY4QZ3PE.js +0 -3
  86. package/dist/chunk-F6CTGVJA.js +0 -9
  87. package/dist/chunk-K3O3HENC.js +0 -5
  88. package/dist/chunk-LGC4CRUF.js +0 -3
  89. package/dist/chunk-NNQE4DS2.js +0 -2
  90. package/dist/chunk-NSH7TTSV.js +0 -1
  91. package/dist/chunk-SO4CGS35.js +0 -4
  92. package/dist/chunk-UNXG3ZFV.js +0 -1
  93. package/dist/chunk-VBMWFT7Q.js +0 -1
  94. package/dist/chunk-ZZWGD3X3.js +0 -12
  95. package/dist/doctor-LQ7FT6AZ.js +0 -1
  96. package/dist/pipeline-NSPPWD7U.js +0 -5
  97. package/dist/verified-goal-GRH5UOJR.js +0 -1
  98. package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +0 -1
  99. package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +0 -1
  100. package/dist/workspace-marker-XGAWZZDX.js +0 -1
  101. package/dist/workspace-repair-engine-TDUNQSFJ.js +0 -3
  102. package/dist/workspace-run-I2W5PIPK.js +0 -1
@@ -1,3 +0,0 @@
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-2BCECNIW.js';import {m}from'./chunk-NSMRQOWP.js';import {l,p}from'./chunk-VBMWFT7Q.js';import {g,l as l$1,m as m$1,n,k as k$2,p as p$3,q,r}from'./chunk-T5NBSCVX.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-D3N2WFDV.js';import {p as p$2}from'./chunk-NNQE4DS2.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};
@@ -1 +0,0 @@
1
- export{a as resolveWorkspaceRunStageTimeoutMs,b as runWorkspaceStage}from'./chunk-K3O3HENC.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-37SWTS2B.js';