workspai 0.68.0 → 0.69.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.
- package/README.md +38 -18
- package/contracts/cli-runtime-command-inventory.v1.snapshot.json +459 -0
- package/contracts/extension-cli-compatibility.v1.json +11 -0
- package/contracts/published-contract-catalog.v1.json +55 -0
- package/contracts/runtime-command-surface.v1.json +282 -0
- package/contracts/workspace-intelligence/architecture-change-lease.v1.json +50 -0
- package/contracts/workspace-intelligence/architecture-surprise-report.v1.json +46 -0
- package/contracts/workspace-intelligence/change-operation-result.v1.json +43 -0
- package/contracts/workspace-intelligence/decision-checkpoint.v1.json +18 -0
- package/contracts/workspace-intelligence/decision-event.v1.json +134 -0
- package/contracts/workspace-intelligence/decision-transaction.v1.json +29 -0
- package/contracts/workspace-intelligence/goal-index.v1.json +13 -0
- package/contracts/workspace-intelligence/goal-pack.v1.json +2 -1
- package/contracts/workspace-intelligence/predicted-architecture-change.v1.json +34 -0
- package/contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json +14 -0
- package/contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json +16 -0
- package/contracts/workspace-intelligence/proof-carrying-change-capsule.v1.json +62 -0
- package/contracts/workspace-intelligence/proof-carrying-change-list.v1.json +80 -0
- package/contracts/workspace-intelligence/workspace-knowledge-graph-change-overlay.v1.json +9 -1
- package/dist/analyze-GPYPXXRT.js +1 -0
- package/dist/{artifact-remediation-plan-I7IKC5MR.js → artifact-remediation-plan-JHHZ4L24.js} +1 -1
- package/dist/autopilot-release-FL47VMF7.js +1 -0
- package/dist/capabilities-command-MYSLJIYS.js +1 -0
- package/dist/chunk-2LZWBUJD.js +1 -0
- package/dist/{chunk-7DDEMDG2.js → chunk-37ZLNFV5.js} +2 -2
- package/dist/{chunk-OFYY4725.js → chunk-3G5FF2JZ.js} +1 -1
- package/dist/chunk-3HFFKW4Q.js +2 -0
- package/dist/{chunk-BHM6RHTA.js → chunk-3WHE7V4M.js} +1 -1
- package/dist/chunk-A3MYO55A.js +3 -0
- package/dist/chunk-ABMB6MJT.js +1 -0
- package/dist/chunk-AD4ZY3RF.js +12 -0
- package/dist/chunk-BM2F5C4J.js +1 -0
- package/dist/chunk-COICGD62.js +1 -0
- package/dist/{chunk-4WVOAX2V.js → chunk-DWL3PPLA.js} +1 -1
- package/dist/{chunk-3Z4SVBMR.js → chunk-EBEAJIBI.js} +1 -1
- package/dist/chunk-EBQS5T7Q.js +7 -0
- package/dist/{chunk-5OV2WXAR.js → chunk-EG6EZ7HW.js} +1 -1
- package/dist/chunk-ERVWW5HX.js +1 -0
- package/dist/chunk-EZPLMAW2.js +1 -0
- package/dist/chunk-FIK343LI.js +1 -0
- package/dist/chunk-GSSJJS5M.js +6 -0
- package/dist/{chunk-TMRCPT7S.js → chunk-GYN6RPNU.js} +1 -1
- package/dist/{chunk-6E2Y3XGT.js → chunk-HCFOVANQ.js} +1 -1
- package/dist/chunk-I3UCODXU.js +1 -0
- package/dist/{chunk-3BMYMZQB.js → chunk-IGJA6GBQ.js} +1 -1
- package/dist/{chunk-FX5J6JCK.js → chunk-IVYPC36J.js} +1 -1
- package/dist/chunk-K33JJVQZ.js +2 -0
- package/dist/{chunk-KDY4X7SQ.js → chunk-M37ALD4V.js} +1 -1
- package/dist/{chunk-3XF7O66C.js → chunk-MAWHHHU3.js} +5 -5
- package/dist/chunk-MBICKDYP.js +1 -0
- package/dist/{chunk-QMQBX3RV.js → chunk-MGL6DBOR.js} +1 -1
- package/dist/chunk-MHQHRMKU.js +5 -0
- package/dist/{chunk-2C5XJBYI.js → chunk-N2Q4MSSP.js} +64 -64
- package/dist/chunk-N4B2M44I.js +1 -0
- package/dist/chunk-NSH7TTSV.js +1 -0
- package/dist/chunk-O5XQP5E7.js +1 -0
- package/dist/chunk-ODK4LCEL.js +1 -0
- package/dist/chunk-OU3BBWH5.js +49 -0
- package/dist/chunk-OZXCNVGW.js +2 -0
- package/dist/{chunk-SLFOUSRW.js → chunk-QYEQVNBF.js} +1 -1
- package/dist/chunk-RVOW3BHQ.js +2 -0
- package/dist/chunk-TKXRP2B4.js +1 -0
- package/dist/chunk-UNXG3ZFV.js +1 -0
- package/dist/chunk-UW4SESKD.js +2 -0
- package/dist/{chunk-2MTJWPQ4.js → chunk-V52R2W2Q.js} +1 -1
- package/dist/chunk-V6TIT6M3.js +157 -0
- package/dist/chunk-VNKAISFE.js +8 -0
- package/dist/chunk-W6WRT77T.js +1 -0
- package/dist/chunk-WHR5SL33.js +4 -0
- package/dist/{chunk-IXXQMD34.js → chunk-WZ5V5U2K.js} +1 -1
- package/dist/chunk-XPGCFVGC.js +4 -0
- package/dist/chunk-YKY4JFCF.js +1 -0
- package/dist/{chunk-VIN7NJW3.js → chunk-YWZBGSFE.js} +3 -3
- package/dist/chunk-YZL7ZY7J.js +2 -0
- package/dist/{create-U5PQHOZ4.js → create-GWBQ74ZI.js} +1 -1
- package/dist/doctor-OQAXSMEM.js +1 -0
- package/dist/goal-lifecycle-YWBVQ2DF.js +1 -0
- package/dist/goal-pack-KUXPZVNO.js +1 -0
- package/dist/index.d.ts +35 -2
- package/dist/index.js +239 -239
- package/dist/pipeline-PGB5TEV3.js +5 -0
- package/dist/{project-agent-entry-MH7364BE.js → project-agent-entry-H3JAGNLS.js} +1 -1
- package/dist/{project-intelligence-lens-ZCCHUKVI.js → project-intelligence-lens-7NMKHV5N.js} +1 -1
- package/dist/{project-test-coverage-JPWTBSSJ.js → project-test-coverage-3DKZKLWY.js} +1 -1
- package/dist/proof-carrying-change-QFH7WI2E.js +1 -0
- package/dist/verified-goal-7XHRWYSE.js +1 -0
- package/dist/{workspace-B33BFZZ3.js → workspace-TJHCETBV.js} +1 -1
- package/dist/{workspace-agent-sync-T3MJO2MX.js → workspace-agent-sync-Z35NTXCB.js} +1 -1
- package/dist/{workspace-archive-NOSGRKRZ.js → workspace-archive-OSMU3CK6.js} +1 -1
- package/dist/{workspace-context-KOCEP4MJ.js → workspace-context-KNJQUJWC.js} +1 -1
- package/dist/{workspace-contract-MQ3QE52V.js → workspace-contract-VIUQT5SZ.js} +1 -1
- package/dist/workspace-explain-HM6GMK26.js +1 -0
- package/dist/workspace-explain-contract-KV7RTEJU.js +1 -0
- package/dist/{workspace-feedback-3YLIUFQ7.js → workspace-feedback-YSPEGCON.js} +1 -1
- package/dist/{workspace-foundation-O7O3QIS4.js → workspace-foundation-PLXFPI3J.js} +1 -1
- package/dist/{workspace-graph-stream-XTGGBD7D.js → workspace-graph-stream-FNRQ2FTB.js} +1 -1
- package/dist/workspace-graph-token-efficiency-WNAFAN2F.js +1 -0
- package/dist/{workspace-history-7HDZZ4G5.js → workspace-history-HDDFG6LH.js} +1 -1
- package/dist/{workspace-intelligence-TFEQBPUP.js → workspace-intelligence-QLSD5EEV.js} +1 -1
- package/dist/{workspace-intelligence-benchmark-PLVUBGWO.js → workspace-intelligence-benchmark-S5OXVNLC.js} +1 -1
- package/dist/{workspace-intelligence-evaluation-OJIQS5SN.js → workspace-intelligence-evaluation-QDSOOUHH.js} +1 -1
- package/dist/{workspace-intelligence-runner-6ZAV6RO4.js → workspace-intelligence-runner-4EW4T2OW.js} +1 -1
- package/dist/workspace-intelligence-runtime-registry-ZLPF7BAY.js +1 -0
- package/dist/{workspace-knowledge-graph-AUXYL3L6.js → workspace-knowledge-graph-EEOW5VAJ.js} +1 -1
- package/dist/workspace-knowledge-graph-change-overlay-FIIAFLO6.js +1 -0
- package/dist/{workspace-knowledge-graph-contract-X52KXBXJ.js → workspace-knowledge-graph-contract-FVX5T7SU.js} +1 -1
- package/dist/{workspace-knowledge-graph-query-A7TKONWY.js → workspace-knowledge-graph-query-WHCGPBGS.js} +1 -1
- package/dist/workspace-knowledge-graph-snapshot-X347REDB.js +1 -0
- package/dist/workspace-mcp-serve-NQ42PE2I.js +3 -0
- package/dist/{workspace-model-GVXNLSQM.js → workspace-model-NCOOY5LC.js} +1 -1
- package/dist/{workspace-onboarding-ECZ2KJ2A.js → workspace-onboarding-JNC7ZFMR.js} +1 -1
- package/dist/{workspace-readme-6N5Y2ZSJ.js → workspace-readme-OV2ADTLW.js} +2 -2
- package/dist/{workspace-registry-summary-5SFBTRGQ.js → workspace-registry-summary-ONT4VOJX.js} +1 -1
- package/dist/{workspace-repair-engine-CKJCTWKX.js → workspace-repair-engine-WMJCYWO4.js} +2 -2
- package/dist/workspace-run-3S35MDX6.js +1 -0
- package/dist/{workspace-verify-D3QTMAUI.js → workspace-verify-MLABQUWK.js} +1 -1
- package/dist/{workspace-watch-XYJEW2Z2.js → workspace-watch-MJOG5AZ3.js} +1 -1
- package/docs/README.md +2 -0
- package/docs/ci-workflows.md +1 -1
- package/docs/commands-reference.md +23 -0
- package/docs/contracts/ARTIFACT_CATALOG.md +37 -18
- package/docs/contracts/COMMAND_OWNERSHIP_MATRIX.md +17 -0
- package/docs/contracts/PROOF_CARRYING_CHANGE_CONTRACT_PLAN.md +65 -0
- package/docs/proof-carrying-change.implementation.v1.json +118 -0
- package/docs/proof-carrying-change.md +202 -0
- package/package.json +1 -1
- package/dist/analyze-JDEWUBC6.js +0 -1
- package/dist/autopilot-release-OELUFNLL.js +0 -1
- package/dist/capabilities-command-RAAYENQ6.js +0 -1
- package/dist/chunk-2KX6KHEC.js +0 -1
- package/dist/chunk-3KU3YUWD.js +0 -2
- package/dist/chunk-3NF3M3RE.js +0 -1
- package/dist/chunk-3OGPTLI2.js +0 -1
- package/dist/chunk-5ME4W4LN.js +0 -1
- package/dist/chunk-5XUAAQSV.js +0 -5
- package/dist/chunk-5YZ2W57R.js +0 -8
- package/dist/chunk-7DZNZ3GM.js +0 -3
- package/dist/chunk-BG6IX6HA.js +0 -1
- package/dist/chunk-BMAFHX6A.js +0 -1
- package/dist/chunk-BUYLM6QV.js +0 -1
- package/dist/chunk-C2VTO5WT.js +0 -2
- package/dist/chunk-CPR2CMOY.js +0 -1
- package/dist/chunk-CSZPE637.js +0 -2
- package/dist/chunk-DFVG4DDZ.js +0 -6
- package/dist/chunk-EHLGPLIU.js +0 -1
- package/dist/chunk-FPDH3N3A.js +0 -7
- package/dist/chunk-GVQKAINC.js +0 -49
- package/dist/chunk-IKUFNK46.js +0 -2
- package/dist/chunk-JYMO7QXQ.js +0 -1
- package/dist/chunk-KY2GOSO5.js +0 -1
- package/dist/chunk-LEOFD3W5.js +0 -12
- package/dist/chunk-LPCZHKD5.js +0 -1
- package/dist/chunk-N5HPMATQ.js +0 -1
- package/dist/chunk-P3622IM5.js +0 -4
- package/dist/chunk-Q7UGDNSM.js +0 -1
- package/dist/chunk-RVAOJOXA.js +0 -2
- package/dist/chunk-TCLKGPXF.js +0 -2
- package/dist/chunk-W5VKBDSD.js +0 -157
- package/dist/chunk-WRZSQDZV.js +0 -1
- package/dist/chunk-Y4Z6CEII.js +0 -1
- package/dist/chunk-ZEEV5J4I.js +0 -1
- package/dist/chunk-ZGHJIQXL.js +0 -1
- package/dist/doctor-D7YI7LSA.js +0 -1
- package/dist/goal-lifecycle-BMS6GSIU.js +0 -1
- package/dist/goal-pack-RBSVQMMX.js +0 -1
- package/dist/pipeline-QOMXH2EK.js +0 -5
- package/dist/verified-goal-XUXU2X5H.js +0 -1
- package/dist/workspace-explain-DTFCKYXK.js +0 -1
- package/dist/workspace-explain-contract-WMREJWHF.js +0 -1
- package/dist/workspace-graph-token-efficiency-5LJKQU2J.js +0 -1
- package/dist/workspace-intelligence-runtime-registry-UKFB3BI7.js +0 -1
- package/dist/workspace-knowledge-graph-change-overlay-XG6FC4IX.js +0 -1
- package/dist/workspace-knowledge-graph-snapshot-GPBDAKAU.js +0 -1
- package/dist/workspace-mcp-serve-TDUXJUAA.js +0 -3
- package/dist/workspace-run-ZZ5WHL7W.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {c as c$2}from'./chunk-BG6IX6HA.js';import {d as d$3,i,j as j$1,k,h as h$1,m as m$2,n,o}from'./chunk-2C5XJBYI.js';import {a as a$2}from'./chunk-7DZNZ3GM.js';import {a,c,h,b,e,j,g,d as d$2}from'./chunk-4WVOAX2V.js';import {m as m$1}from'./chunk-W5VKBDSD.js';import {l,p}from'./chunk-JYMO7QXQ.js';import {a as a$3}from'./chunk-3NF3M3RE.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {p as p$1}from'./chunk-TCLKGPXF.js';import {c as c$1}from'./chunk-C2VTO5WT.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$3,d as d$1}from'./chunk-EWZZUQBR.js';import {e as e$1}from'./chunk-ZGHJIQXL.js';import {c as c$4,b as b$1}from'./chunk-25AWHAB5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import d from'path';import {execa}from'execa';import m from'fs-extra';var Le=".workspai/repair",Ma="transaction.json",_a="source-plan.json",ka="checkpoint",La="engine.lock",Ia=5*1024*1024,Ga=25*1024*1024,za=25*1024*1024,Aa=4*1024*1024,Ka=900*1e3,Va=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),Ja=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),G={safe:0,guarded:1,invasive:2},Ua=new Set(["node","npm","npx","pnpm","yarn","bun","deno","python","python3","py","pip","pip3","poetry","uv","pytest","pip-audit","govulncheck","go","cargo","composer","bundle","bundle-audit","dotnet","mvn","mvnw","gradle","gradlew","mix","clojure","lein","sbt","make"]);function Ya(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function O(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${C(e).slice(0,16)}`,message:r.message??e}]}}function Ea(e){let a=new Map,r=t=>a.set(Ya(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=We(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),G[t.risk]>G[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(i=>i.invocation&&`tool:${i.invocation.cwd}:${i.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${C(t).slice(0,16)}`,message:t});}return [...a.values()]}function H(e){return (e?.()??new Date).toISOString()}function C(e){return createHash("sha256").update(e).digest("hex")}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${K(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function wa(e){return C(K({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function $a(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=wa(a),t=(await jt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&wa(o)===r);if(t)return await re(d.join(e,b),t),t}var He="causal-action-integrity:";function Sa(e){return C(K([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function Ca(e){if(e.length===0)return;let a=Sa(e);return {id:`${He}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Xa(e){return K({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function ba(e){return new Set(e.map(Xa))}function I(e,a){let r=d.relative(d.resolve(e),d.resolve(a));return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}async function z(e,a){let r=await m.realpath(e).catch(()=>d.resolve(e)),t=d.resolve(a);for(;!await m.pathExists(t);){let i=d.dirname(t);if(i===t)return false;t=i;}let o=await m.realpath(t).catch(()=>d.resolve(t));return I(r,o)}function te(e,a,r){let t=d.isAbsolute(a)?d.resolve(a):d.resolve(e,a);if(!I(e,t)&&!(r&&I(d.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!I(e,t)&&r){let o=d.resolve(r),i=d.relative(o,t).split(d.sep).join("/"),n=`external/${d.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return d.relative(e,t).split(d.sep).join("/")||"."}function X(e){let a=e.replaceAll("\\","/").replace(/^\.\//,""),r=/^external\/([^/]+)(?:\/(.*))?$/.exec(a);if(!r)return;let t=r[2]??"";if(!t.split("/").some(o=>o===".."))return {root:`external/${r[1]}`,suffix:t}}async function T(e){if(d.isAbsolute(e.value))return d.resolve(e.value);let a=X(e.value);if(!a)return d.resolve(e.workspacePath,e.value);if(e.projectBoundary)return d.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$1({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&d.basename(d.resolve(o.externalPath))===a.root.slice(9)||e.projectName!==void 0&&o.slug===e.projectName);if(!t?.externalPath)throw new Error(`Portable external project reference is not canonically registered: ${a.root}`);return d.resolve(t.externalPath,a.suffix||".")}function je(e,a,r,t){let o=te(e,a,r),i=X(o);return !i||!t?o:i.suffix?`${t}/${i.suffix}`:t}async function Za(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&I(e.workspacePath,a)&&!X(e.proposal.projectPath??""))return a;let{contract:t}=await p$1({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?d.resolve(i.externalPath):d.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,u=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&u});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?d.resolve(o.externalPath):d.resolve(e.workspacePath,o.relativePath)}function ce(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return d.join(e,Le,"transactions",a)}async function ae(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return d.join(ce(e,a),Ma)}function Ge(e,a){return d.join(ce(e,a),_a)}async function re(e,a){await m.ensureDir(d.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await m.writeJson(r,a,{spaces:2}),await m.move(r,e,{overwrite:true});}function E(e,a,r,t={}){let o={sequence:e.events.length+1,at:H(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r};e.events.push(o);let i=t.status??a,n=a==="failed"||i==="failed"?"failed":a==="cancelled"?"cancelled":a==="closed"||i==="passed"||i==="completed"?"succeeded":a==="rollback"?"rolled-back":i==="blocked"?"blocked":"running";t.stageId?c$4({blockId:`repair.${t.stageId}`,status:n,message:r,component:"workspace-repair",attributes:{transactionId:e.transactionId,repairEventType:a}}):b$1({kind:n==="failed"?"operation.failed":n==="succeeded"||n==="rolled-back"?"operation.completed":"operation.started",status:n,component:"workspace-repair",message:r,correlationId:e.transactionId,attributes:{repairEventType:a}});}async function x(e,a,r){a.revision+=1,a.updatedAt=H(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(d.join(e,b),a);}async function le(e){let a$2=await m.readJson(Se(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function Ce(e,a){return await m.readJson(Ge(e,a))}function ne(e){return e.schemaVersion===d$2}async function de(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=await T({workspacePath:e,value:t,projectBoundary:r,projectName:a.projectName});if(!I(e,o)&&!X(t)&&!(r&&d.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:te(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Oe(e){return m.readFile(e,"utf8").catch(()=>"")}async function Qa(e){return m.readJson(e).catch(()=>({}))}function va(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function et(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=d.extname(e).length>0;return (process.env.PATH??"").split(d.delimiter).filter(Boolean).flatMap(t=>r?[d.join(t,e)]:a.map(o=>d.join(t,`${e}${o}`)))}function Pa(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ya(e,a){try{let r=await execa(e,["--version"],{cwd:a,shell:false,reject:false,timeout:5e3,maxBuffer:65536,stdin:"ignore"});return r.exitCode!==void 0&&r.exitCode!==null}catch{return false}}async function Wa(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(d.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=d.isAbsolute(r)?r:d.resolve(a,r),o=await m.stat(t).catch(()=>{});return Pa(o)&&ya(t,a)}for(let t of et(r)){let o=await m.stat(t).catch(()=>{});if(Pa(o)&&await ya(t,a))return true}return false}async function ze(e){let a=new Set;for(let i of e.stages){if(i.kind!=="repair"||!i.invocation)continue;let n=Te(i.invocation.executable);if(!["python","python3","py"].includes(n)||!i.invocation.args.includes("venv")||!i.invocation.args.includes(".venv"))continue;let s=await T({workspacePath:e.workspacePath,value:i.invocation.cwd});a.add(d.normalize(d.join(s,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(i=>i.required&&i.status!=="skipped"&&i.invocation).map(i=>i.invocation),t=new Map;for(let i of r)t.set(`${i.cwd}\0${i.executable}`,i);let o=[];for(let i of t.values()){let n=await T({workspacePath:e.workspacePath,value:i.cwd}),s=d.isAbsolute(i.executable)?d.normalize(i.executable):d.normalize(d.resolve(n,i.executable));if(a.has(s)){o.push({id:`tool:${i.cwd}:${i.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${i.executable} (${i.cwd}).`});continue}let u=await Wa({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:u?"passed":"failed",message:u?`Required repair executable is available: ${i.executable} (${i.cwd}).`:`Required repair executable is unavailable: ${i.executable} (${i.cwd}). Install or configure it, then create a fresh plan.`});}return o}function oe(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function P(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function at(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return v({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function tt(e){let a=await de(e.workspacePath,e.action,e.authorizedProjectRoot),r=X(e.action.projectPath??"")?.root??te(e.workspacePath,a,a),t=async g=>m.pathExists(d.join(a,g)),o=new Set,i=[],n=[],s=g=>`${r}:${e.adapterId}:${g}`,u=g=>g.forEach(f=>o.add(te(e.workspacePath,d.join(a,f),a))),c=g=>{i.push(g),g.required&&g.status==="blocked"&&n.push(g.summary);},p=at(e.workspacePath,a,e.action),k=()=>{let g$1=g.find(f=>f.id===e.adapterId);if(!g$1)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:g$1.id,ecosystem:g$1.ecosystem,projectPath:r,manifests:g$1.manifests,support:g$1.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(f=>f.required&&f.invocation).map(f=>f.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${g$1.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let g=await Qa(d.join(a,"package.json")),f=g.scripts&&typeof g.scripts=="object"&&!Array.isArray(g.scripts)?g.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",B=b==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":b==="pnpm"?"pnpm-lock.yaml":b==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";u(["package.json",B]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${b} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:["install"],purpose:"reconcile"})}));let V=v(b==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return c(P({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:p??V})),c(typeof f.test=="string"&&f.test.trim()?P({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):oe(s("test"),"test","No test script is declared.")),c(typeof f.build=="string"&&f.build.trim()?P({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):oe(s("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){u(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let g=e.action.transaction?.ecosystem.toLowerCase(),f=d.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=f==="uv"||g==="uv"||await t("uv.lock"),B=!b&&(f==="poetry"||g==="poetry"||await t("poetry.lock")),V=!b&&!B&&["python","python3","py"].includes(f)&&(e.action.invocation?.args??[]).some(M=>M==="venv")&&(e.action.invocation?.args??[]).some(M=>M===".venv"),W=process.platform==="win32"?"python":"python3",D=d.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await m.pathExists(D)||V)&&(W=D);let _=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):B?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:_})),c(P({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:p}));let L=await Oe(d.join(a,"pyproject.toml")),pe=await t("tests")||/\[tool\.pytest/i.test(L),Z=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pytest"],purpose:"test"}),se=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","build"],purpose:"build"});return c(pe?P({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:Z}):oe(s("test"),"test","No Python test surface is declared.")),c(/\[build-system\]/i.test(L)?P({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:se}):oe(s("build"),"build","No Python build contract is declared.")),k()}let w=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let g of w){if(g.adapterId!==e.adapterId)continue;let f=await t(g.manifest)?g.manifest:g.alternateManifest&&await t(g.alternateManifest)?g.alternateManifest:void 0;if(!f)continue;u(g.files),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${f} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.reconcile[0],args:g.reconcile[1],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:p??(g.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:g.audit[0],args:g.audit[1],purpose:"audit"}):void 0)}));let b=await Oe(d.join(a,f)),B=g.manifest==="composer.json"||g.adapterId==="deno"?/["']test["']\s*:/.test(b):g.manifest==="Gemfile"?await t("Rakefile"):true,V=g.manifest==="composer.json"||g.manifest==="deno.json"?/["']build["']\s*:/.test(b):g.manifest==="Gemfile"?(await m.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return c(B?P({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.test[0],args:g.test[1],purpose:"test"})}):oe(s("test"),"test","No test contract is declared.")),c(V?P({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.build[0],args:g.build[1],purpose:"build"})}):oe(s("build"),"build","No build contract is declared.")),k()}let j=await m.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&j.some(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g)))return u(["Directory.Packages.props","packages.lock.json",...j.filter(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g))]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:p??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),c(P({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),k();let y=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return u(["pom.xml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["dependency:resolve"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["package","-DskipTests"],purpose:"build"})})),k();let $=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&$){let g=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return u([$,"gradle.lockfile","gradle/libs.versions.toml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["dependencies"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["build","-x","test"],purpose:"build"})})),k()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let g=q==="deps.edn",f=await Oe(d.join(a,q)),b=g?"clojure":"lein";u([q]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-P"]:["deps"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:p}));let B=!g||/:test\b/.test(f);return c(B?P({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-M:test"]:["test"],purpose:"test"})}):oe(s("test"),"test","No Clojure :test alias is declared.")),c(g?oe(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):P({id:s("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),k()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(u(["build.sbt"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),c(P({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),k())}async function Ta(e){let a=i=>m.pathExists(d.join(e,i)),r=await m.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(i=>/\.(?:cs|fs|vb)proj$|\.slnx?$/i.test(i))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(g.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function rt(e){let a=e?.trim().toLowerCase();if(a){if(["npm","pnpm","yarn","bun","node","javascript","typescript"].includes(a))return "node";if(["python","pip","poetry","uv"].includes(a))return "python";if(["go","gomod","go-modules"].includes(a))return "go";if(["rust","cargo"].includes(a))return "rust";if(["php","composer"].includes(a))return "php-composer";if(["ruby","bundler","bundle"].includes(a))return "ruby-bundler";if(["elixir","mix"].includes(a))return "elixir-mix";if(a==="deno")return "deno";if(["dotnet",".net","nuget"].includes(a))return "dotnet";if(["maven","jvm-maven"].includes(a))return "jvm-maven";if(["gradle","jvm-gradle"].includes(a))return "jvm-gradle";if(["clojure","lein","leiningen"].includes(a))return "clojure";if(["scala","sbt","scala-sbt"].includes(a))return "scala-sbt"}}async function Na(e,a={}){let r=await de(e.workspacePath,e.action,e.authorizedProjectRoot),t=X(e.action.projectPath??"")?.root??te(e.workspacePath,r,r),o=await Ta(r),i=rt(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let c=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[P({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:i,ecosystem:g.find(p=>p.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:c}]}}if(n.length===0){let c=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[P({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:c}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let c of n){let p=await tt({...e,adapterId:c});s.stages.push(...p.stages),s.checkpointFiles.push(...p.checkpointFiles),s.blockers.push(...p.blockers),s.adapters.push(...p.adapters);}s.stages=[...new Map(s.stages.map(c=>[c.id,c])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let u=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let c=new Set(e.action.transaction.requiredStages),p=Te(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],w=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(p)&&k.includes("venv")&&k.includes(".venv");w&&u.add(d.normalize(d.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(j=>j.kind==="reconcile"?w&&c.has("reconcile"):c.has(j.kind)),s.blockers=s.stages.filter(j=>j.required&&j.status==="blocked").map(j=>j.summary);}for(let c of s.adapters){let p=s.stages.filter(w=>w.id.startsWith(`${c.projectPath}:${c.adapterId}:`)),k=[];c.requiredExecutables=[...new Set(p.filter(w=>w.required&&w.invocation).map(w=>w.invocation.executable))];for(let w of p){if(!w.required||!w.invocation)continue;let j=await T({workspacePath:e.workspacePath,value:w.invocation.cwd,projectBoundary:r}),y=d.isAbsolute(w.invocation.executable)?d.normalize(w.invocation.executable):d.normalize(d.resolve(j,w.invocation.executable));u.has(y)||await Wa({workspacePath:e.workspacePath,invocation:w.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||k.push(w.invocation.executable);}c.missingExecutables=[...new Set(k)],c.missingExecutables.length>0&&(c.status="partial",c.message=`Required executable(s) unavailable: ${c.missingExecutables.join(", ")}.`);}if(n.length===1){let c=`:${n[0]}:`;for(let p of s.stages)p.id=p.id.replace(c,":");}return s}async function Xt(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=d.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let i=e.project.trim(),n=await m$1(r),s=i.replace(/\\/g,"/").replace(/^\.\//,""),u=d.resolve(r,i),c=n.resolved.filter(p=>{let k=I(r,p.projectPath)?te(r,p.projectPath):void 0;return p.name===i||k===s||d.resolve(p.projectPath)===u});if(c.length===0){let p=n.skipped.find(k=>k.name===i);throw p?new Error(`Registered project is unavailable for repair capability inspection: ${i} (${p.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i}.`)}if(c.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i}.`);t=d.resolve(c[0].projectPath),o=c[0].name;}else {if(t=d.resolve(r,e.projectPath??"."),!I(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=te(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ta(t)}}}function We(e){if(e.command){let a=d$3(e.command);if(a)return a}return a$4(e.operation)??void 0}async function ot(e){let a=new Set,r=e.actions[0]?await de(e.workspacePath,e.actions[0]):void 0,t=X(e.actions[0]?.projectPath??"")?e.actions[0]?.projectPath:void 0;for(let o of e.dependencyFiles){let i=await T({workspacePath:e.workspacePath,value:o,projectBoundary:r,projectName:e.actions[0]?.projectName});a.add(je(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await de(e.workspacePath,o),n=X(o.projectPath??"")?i:e.workspacePath;if(!await z(n,i))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${i}`);let s=o.transaction?.kind==="dependency-materialization"&&o.transaction.sourceMutationRequired===false;for(let p of s?[]:o.files){let k=await T({workspacePath:e.workspacePath,value:p,projectBoundary:X(p)?i:void 0,projectName:o.projectName});if(!await z(n,k))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${p}`);a.add(je(e.workspacePath,k,i,X(o.projectPath??"")?o.projectPath:void 0));}let u=We(o);if(!u)continue;let c="path"in u?u.path:void 0;if(c){let p=d.resolve(i,c);if(!await z(n,p))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${c}`);a.add(je(e.workspacePath,p,i,X(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function st(e,a){if(!a.invocation)return;let r=await de(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ke(e){return C(K({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function Ve(e){return Ke({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function qa(e){return C(K({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Zt(e){let a=d.resolve(e.workspacePath),r=await le({workspacePath:a,transactionId:e.transactionId}),t=await Ce(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Ve(r)!==r.integrity.planHash||!r.integrity.closureHash||qa(r)!==r.integrity.closureHash||C(K(t))!==r.integrity.sourceEvidenceHash||!ne(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=await ae(a,r);for(let i of r.checkpoint.files){let n=await T({workspacePath:a,value:i.path,projectBoundary:o,projectName:r.target.projectName});if(!I(a,n)&&!(o&&I(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await m.lstat(n).catch(()=>{});if(!s){if(i.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${i.path}`);continue}if(!s.isFile()||s.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${i.path}`);let u=await m.readFile(n);if(i.afterHash!==C(u))throw new Error(`Goal repair output changed after transaction closure: ${i.path}`);if(i.mode!==void 0&&s.mode!==i.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${i.path}`)}return r.verification.sourceBinding}async function $e(e,a,r){let t=[],o=[],i=0;for(let n of a){let s=await T({workspacePath:e,value:n,projectBoundary:r}),u=r&&I(d.resolve(r),s)?d.resolve(r):e;if(!I(u,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await z(u,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let c=await m.lstat(s).catch(()=>{});if(c?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(c&&!c.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(c&&c.size>Ia){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=c?.size??0,i>Ga){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=c?await m.readFile(s):void 0;t.push({path:n,existed:!!c,beforeHash:p?C(p):null,...c?{mode:c.mode}:{}});}return {entries:t,errors:o}}function Ba(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}function it(e,a){if(!(!/\.json$/i.test(e)||a===void 0))try{JSON.parse(a);return}catch{return `${e} must contain valid JSON; comments and trailing syntax are not allowed.`}}async function nt(e){let a=await m.readJson(d.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():d.basename(e)}function ct(e){return Va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function dt(e,a){let r=d.resolve(e,a),t=d.dirname(r);for(;I(e,t);){if((await m.readdir(t).catch(()=>[])).some(ct))return t;if(d.resolve(t)===d.resolve(e))break;t=d.dirname(t);}return e}function lt(e,a,r){return r.some(t=>{let o=d.resolve(e,t.path);if(!I(a,o))return false;let i=d.basename(o);return Ja.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function pt(e){let a=!I(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:te(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function ut(e,a){let r=Te(a.executable),[t="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(r);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(s=>/^(?:test|build|check|verify|package)$/i.test(s))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function ht(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let u=d.resolve(e.workspacePath,s.cwd),c=te(e.workspacePath,u,n),p=await m.lstat(u).catch(()=>{});if(!p?.isDirectory()||p.isSymbolicLink()||!await z(n??e.workspacePath,u)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!I(n,u)){t.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(G[s.risk]>G[e.maxRisk]){t.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:u,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Je(e.workspacePath,k,e.policy,e.projectRoots),ut(s,k);}catch(w){t.push(w instanceof Error?w.message:String(w));continue}a.push(P({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:k})),i.add(`${c}:${s.kind}`);}for(let s of e.projectRoots){let u=pt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),c=await Na({workspacePath:e.workspacePath,action:u,authorizedProjectRoot:s},e.dependencies);o.push(...c.adapters);let p=lt(e.workspacePath,s,e.proposal.changes);if(p){for(let w of c.checkpointFiles)r.add(w);t.push(...c.blockers);}let k=te(e.workspacePath,s,s);for(let w of c.stages)!p&&!["test","build"].includes(w.kind)||i.has(`${k}:${w.kind}`)||a.push(w);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function gt(e,a$3={}){let r=d.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(h=>h.cardId===e.cardId).filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),i=e.actionId?o.filter(h=>h.id===e.actionId):o,n=t.actions.filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),s=new Map(n.map(h=>[h.id,h])),u=h=>{let R=new Set(h.map(J=>J.id)),F=[...h];for(;F.length>0;){let J=F.pop();for(let U of J?.dependsOn??[]){let Y=s.get(U);!Y||R.has(Y.id)||(R.add(Y.id),F.push(Y));}}return n.filter(J=>R.has(J.id))},c$1=i.filter(h=>h.findingStatus==="blocking"||h.notes.includes("Doctor finding status: blocking")),p=c$1.length>0?c$1:i.filter(h=>h.findingStatus!=="informational"),k=e.actionId?i.filter(h=>h.id===e.actionId):[],w=[...p].sort((h,R)=>{let F=h.status==="ready"||h.status==="review-required"?0:1,J=R.status==="ready"||R.status==="review-required"?0:1;return F-J||h.order-R.order||h.id.localeCompare(R.id)})[0],j=w?p.filter(h=>h.cardId===w.cardId&&h.findingId===w.findingId&&h.causalKey===w.causalKey&&h.projectName===w.projectName&&h.projectPath===w.projectPath):[],y=u(e.actionId?k:j),$=e.maxRisk??"guarded",q={maxRisk:$,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},g=[{id:"workspace-root",status:await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:y.length>0?"passed":"failed",message:y.length>0?`${y.length} governed action(s) selected.`:"No governed remediation action matches this target."}],f=Ca(y);f&&g.push(f);let b$1=[],B=[],V=[],W=[],D=new Set(["replan","manual-repair","cancel"]);for(let h of y){let R=We(h),F=await st(r,h);if(G[h.risk]<=G[$]||(W.push(`${h.id} exceeds the approved ${$} risk ceiling.`),D.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),(h.status==="blocked"||h.status==="guidance-only")&&W.push(`${h.id} is ${h.status}: ${h.blocker}`),!R&&!F&&W.push(`${h.id} has no typed operation or structured invocation.`),F)try{Je(r,F,q);}catch(U){let Y=U instanceof Error?U.message:String(U);W.push(Y),/Force-based/.test(Y)&&D.add("allow-force"),/Breaking dependency/.test(Y)&&D.add("allow-breaking");}if(b$1.push({id:`action:${h.id}`,kind:"repair",status:R||F?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,...F?{invocation:F}:{}}),h.transaction){let U=await Na({workspacePath:r,action:h},a$3);b$1.push(...U.stages),B.push(...U.checkpointFiles),W.push(...U.blockers),V.push(...U.adapters);}}let _=[...new Map(b$1.map(h=>[h.id,h])).values()];b$1.splice(0,b$1.length,..._),b$1.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),b$1.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),b$1.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),g.push(...await ze({workspacePath:r,stages:b$1,toolAvailable:a$3.toolAvailable}));let L=await ot({workspacePath:r,actions:y,dependencyFiles:B}),pe=y[0]?await de(r,y[0]):void 0,Z=await $e(r,L,pe);g.push({id:"rollback-coverage",status:y.some(h=>h.mode==="edit-file"||h.mode==="run-command")&&L.length===0?"failed":"passed",message:L.length>0?`${L.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),g.push({id:"structured-execution",status:b$1.some(h=>h.required&&h.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),g.push({id:"checkpoint-boundary",status:Z.errors.length===0?"passed":"failed",message:Z.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":Z.errors.join(" ")});let se=C(K(t)),M=[...new Set(y.map(h=>h.projectPath).filter(Boolean))],xe=[...new Set(y.map(h=>h.projectName).filter(Boolean))],ue=xe.length===1?xe[0]:void 0,Ie=M.length===1&&xe.length<=1,ie={cardId:e.cardId,scope:Ie?"project":"workspace",...ue?{projectName:ue}:{},...M.length===1?{projectPath:M[0]}:{},actionIds:y.map(h=>h.id)},ke=H(a$3.now),he=`repair_${randomUUID().replaceAll("-","")}`,Q=g.some(h=>h.status==="failed")||W.length>0,we=[...W,...g.filter(h=>h.status==="failed").map(h=>h.message)],be=[...new Map(V.map(h=>[`${h.projectPath}:${h.adapterId}`,h])).values()],l=Ea({actions:y,adapters:be,preconditions:g,stages:b$1,decisionOptions:D,maxRisk:$,fallbackReasons:we}),S={schemaVersion:a,transactionId:he,revision:1,createdAt:ke,updatedAt:ke,workspace:{name:t.workspace.name,rootRef:"."},target:ie,state:Q?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:g,adapterEvaluations:be,checkpoint:{status:L.length>0?"pending":"unavailable",files:Z.entries},stages:b$1,...Q?{decision:{reason:[...new Set(we)].join(" "),options:[...D],causes:l}}:{},events:[],integrity:{sourceEvidenceHash:se,planHash:Ke({sourceEvidenceHash:se,target:ie,policy:q,preconditions:g,adapterEvaluations:be,stages:b$1,checkpointFiles:Z.entries})}};E(S,"planned",Q?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let N=await $a(r,S);if(N)return N;let ge=ce(r,he);return await m.ensureDir(ge),await re(Ge(r,he),t),await re(Se(r,he),S),await re(d.join(r,b),S),S}async function ft(e,a={}){let r=e.proposal.goalId;if(!r)return Ra(e,a);let t=d.resolve(e.workspacePath);return c$1(t,`.workspai/goals/${r}/repair-proposal`,()=>Ra({...e,workspacePath:t},a))}async function Ra(e$1,a$3={}){a$1(e$1.proposal,e,"Workspace repair proposal");let r=d.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal));if(t.goalId){let l$1=await l({workspacePath:r,goalId:t.goalId});if(!l$1.active||l$1.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(l$1.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${l$1.goalPack?.state??"missing"}`);if((l$1.active.repairTransactionIds??(l$1.active.repairTransactionId?[l$1.active.repairTransactionId]:[])).length>=l$1.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${l$1.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(l$1.goalPack.scope.kind==="project"||l$1.goalPack.scope.kind==="project-set"){let N=l$1.goalPack.scope.projects;if(!t.projectName||!N.includes(t.projectName))throw new Error(l$1.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${N[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${N.join(", ")}).`)}}let o=e$1.maxRisk??"guarded",i={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},n=[],s=[],u=new Set(["replan","manual-repair","cancel"]),c$1=await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"));n.push({id:"workspace-root",status:c$1?"passed":"failed",message:c$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let p$1;try{p$1=await Za({workspacePath:r,proposal:t});}catch(l){s.push(l instanceof Error?l.message:String(l));}let k=p$1&&!I(r,p$1)&&t.projectName?`external/${t.projectName}`:void 0;if(p$1&&(t.projectName||t.projectPath)&&(t.projectPath=k??d.relative(r,p$1).split(d.sep).join("/")),t.projectPath){let l=p$1??d.resolve(r,t.projectPath),S=await m.lstat(l).catch(()=>{});(!S?.isDirectory()||S.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(l=>({...l,cwd:je(r,l.cwd,p$1,k)}));let w=new Set,j=new Set,y=0;for(let l of t.changes){l.path=je(r,l.path,p$1,k),l.path==="."&&s.push(`${l.id} cannot replace the workspace root.`),w.has(l.id)&&s.push(`Duplicate proposal change id: ${l.id}.`),j.has(l.path)&&s.push(`Multiple proposal changes target ${l.path}.`),w.add(l.id),j.add(l.path),y+=Buffer.byteLength(l.content??"","utf8"),y>za&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let S=Ba(l.path);if(S&&s.push(`${l.path}: ${S}`),l.operation==="write"){let N=it(l.path,l.content);N&&s.push(N);}if(G[l.risk]>G[o]&&(s.push(`${l.id} exceeds the approved ${o} risk ceiling.`),u.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let N=p$1??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ge=await T({workspacePath:r,value:l.path,projectBoundary:N,projectName:t.projectName});I(N,ge)||s.push(`${l.path} escapes the declared project scope.`);}}let $=[...j].sort(),q=await $e(r,$,p$1);s.push(...q.errors);let g=new Map(q.entries.map(l=>[l.path,l]));for(let l of t.changes){let S=g.get(l.path);if(!S||S.beforeHash!==l.expectedBeforeHash){s.push(`${l.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}l.operation==="delete"&&!S.existed&&s.push(`${l.path} cannot be deleted because it does not exist.`),l.operation==="write"&&S.beforeHash!==null&&C(l.content??"")===S.beforeHash&&s.push(`${l.path} is a no-op and cannot prove source progress.`);}n.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let f=new Set;if(t.projectPath)f.add(p$1??d.resolve(r,t.projectPath));else for(let l of t.changes)f.add(await dt(r,l.path));let b$1=await ht({workspacePath:r,proposal:t,projectRoots:[...f].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...b$1.blockers);let B=b$1.stages,V=B.some(l=>l.status!=="skipped"&&["audit","test","build"].includes(l.kind));n.push({id:"validation-coverage",status:V?"passed":"unknown",message:V?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let W=[...new Set([...$,...b$1.checkpointFiles])].sort(),D=await $e(r,W,p$1);s.push(...D.errors),n.push({id:"checkpoint-boundary",status:D.errors.length===0?"passed":"failed",message:D.errors.length===0?`${D.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:D.errors.join(" ")});let _=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(l=>({id:`proposal:${l.id}`,kind:"repair",status:G[l.risk]<=G[o]?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,changedPaths:[l.path]})),...B,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];n.push(...await ze({workspacePath:r,stages:_,toolAvailable:a$3.toolAvailable}));let L=new Set(_.map(l=>l.id));L.size!==_.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:L.size===_.length?"passed":"failed",message:L.size===_.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let l=false,S=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),N=S.actions.filter(A=>A.cardId===t.cardId&&(!t.projectName||A.projectName===t.projectName)&&(!t.projectPath||A.projectPath===t.projectPath));if(!t.targetActionIds?.length){let A=ba(N);A.size===1?t.targetActionIds=N.map(Oa=>Oa.id).sort():A.size>1&&(l=true,s.push(`Repair proposal target is ambiguous: ${A.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ge=[...new Set(t.targetActionIds??[])],h=new Set(ge),R=S.actions.filter(A=>h.has(A.id)),F=new Set(R.map(A=>A.id)),J=ge.filter(A=>!F.has(A));J.length>0&&(l=true,s.push(`Repair proposal references stale or unknown causal action ids: ${J.join(", ")}.`)),R.filter(A=>A.cardId!==t.cardId||t.projectName!==void 0&&A.projectName!==t.projectName||t.projectPath!==void 0&&A.projectPath!==t.projectPath).length>0&&(l=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let Y=ba(R);Y.size>1&&(l=true,s.push(`Repair proposal combines ${Y.size} independent causal finding families. Create one transaction per finding family.`)),R.length>0&&!t.blockerSignature&&(l=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(R.map(A=>A.projectName??A.projectPath).filter(A=>!!A)).size>0&&!t.projectName&&!t.projectPath&&(l=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),R.length>0&&R.every(A=>A.mode==="run-command"&&A.transaction?.kind==="dependency-materialization"&&A.transaction.sourceMutationRequired===false)&&(l=true,s.push("The selected causal action is command-owned and declares that source mutation is not required. Execute the canonical action instead of submitting a model source proposal.")),n.push({id:"causal-target-binding",status:!l&&(R.length>0||N.length===0)?"passed":"failed",message:R.length>0?`${R.length} action(s) bind this proposal to one canonical causal target.`:N.length===0?"No canonical remediation action exists; the bounded source proposal remains the explicit target.":"A single canonical causal target is required before source mutation."});let Ue=Ca(R);Ue&&n.push(Ue);}catch{}let pe=C(K(t)),Z={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(l=>`proposal:${l.id}`)},se=H(a$3.now),M=`repair_${randomUUID().replaceAll("-","")}`,ue=n.some(l=>l.status==="failed")||s.length>0,Ie=[...s,...n.filter(l=>l.status==="failed"&&l.id!=="proposal-boundary").map(l=>l.message)],ie=Ea({adapters:b$1.adapters,preconditions:n,stages:_,decisionOptions:u,maxRisk:o,fallbackReasons:Ie});for(let l of t.changes)G[l.risk]<=G[o]||ie.push({kind:"risk-approval",id:`risk:${l.id}`,message:`${l.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let ke=ie.length>0&&ie.every(l=>l.kind==="failed-precondition")&&n.some(l=>l.id==="proposal-boundary"&&l.status==="failed"),he=ke?["replan","cancel"]:[...u],Q={schemaVersion:a,transactionId:M,revision:1,createdAt:se,updatedAt:se,workspace:{name:await nt(r),rootRef:"."},target:Z,state:ue?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:b$1.adapters,checkpoint:{status:"pending",files:D.entries},stages:_,...ue?{decision:{reason:[...new Set(Ie)].join(" "),options:he,causes:ie}}:{},events:[],integrity:{sourceEvidenceHash:pe,planHash:Ke({sourceEvidenceHash:pe,target:Z,policy:i,preconditions:n,adapterEvaluations:b$1.adapters,stages:_,checkpointFiles:D.entries})}};E(Q,"planned",ue?ke?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(Q,c,"Workspace repair transaction");let we=await $a(r,Q);if(we)return we;let be=ce(r,M);return await m.ensureDir(be),await re(Ge(r,M),t),await re(Se(r,M),Q),await re(d.join(r,b),Q),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:M}),Q}async function Qt(e,a={}){let r=await le(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Ve(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=O("The compiled repair plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return C(K(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=O("The persisted source plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:H(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",E(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await x(e.workspacePath,r,a.now),r)}async function Da(e,a){let r=d.join(e,Le,La);await m.ensureDir(d.dirname(r));try{let t=await m.stat(r),o=await m.readJson(r).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,n=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&n)try{process.kill(n,0),s=true;}catch(c){s=c!==null&&typeof c=="object"&&"code"in c&&c.code==="EPERM";}let u=!!(i&&i!==hostname());!s&&!u&&Date.now()-t.mtimeMs>Ka&&await m.remove(r);}catch{}try{await m.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
|
|
1
|
+
import {a as a$2}from'./chunk-A3MYO55A.js';import {a,c,h,b,e as e$1,j,g,d as d$2}from'./chunk-DWL3PPLA.js';import {c as c$1}from'./chunk-ABMB6MJT.js';import {m as m$1}from'./chunk-V6TIT6M3.js';import {l,p}from'./chunk-BM2F5C4J.js';import {g as g$1,l as l$1,m as m$2,n,k,p as p$3,q,r}from'./chunk-N2Q4MSSP.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {a as a$3}from'./chunk-MBICKDYP.js';import {p as p$2}from'./chunk-UW4SESKD.js';import {e}from'./chunk-OZXCNVGW.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$2,d as d$1}from'./chunk-EWZZUQBR.js';import {p as p$1}from'./chunk-ODK4LCEL.js';import {c as c$3,b as b$1}from'./chunk-25AWHAB5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import d from'path';import {execa}from'execa';import m from'fs-extra';var Le=".workspai/repair",Ma="transaction.json",_a="source-plan.json",ka="checkpoint",La="engine.lock",Ia=5*1024*1024,Ga=25*1024*1024,za=25*1024*1024,Aa=4*1024*1024,Ka=900*1e3,Va=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),Ja=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),G={safe:0,guarded:1,invasive:2},Ua=new Set(["node","npm","npx","pnpm","yarn","bun","deno","python","python3","py","pip","pip3","poetry","uv","pytest","pip-audit","govulncheck","go","cargo","composer","bundle","bundle-audit","dotnet","mvn","mvnw","gradle","gradlew","mix","clojure","lein","sbt","make"]);function Ya(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function O(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${C(e).slice(0,16)}`,message:r.message??e}]}}function Ea(e){let a=new Map,r=t=>a.set(Ya(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=We(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),G[t.risk]>G[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(i=>i.invocation&&`tool:${i.invocation.cwd}:${i.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${C(t).slice(0,16)}`,message:t});}return [...a.values()]}function H(e){return (e?.()??new Date).toISOString()}function C(e){return createHash("sha256").update(e).digest("hex")}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${K(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function wa(e){return C(K({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function $a(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=wa(a),t=(await jt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&wa(o)===r);if(t)return await re(d.join(e,b),t),t}var He="causal-action-integrity:";function Sa(e){return C(K([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function Ca(e){if(e.length===0)return;let a=Sa(e);return {id:`${He}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Xa(e){return K({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function ba(e){return new Set(e.map(Xa))}function I(e,a){let r=d.relative(d.resolve(e),d.resolve(a));return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}async function z(e,a){let r=await m.realpath(e).catch(()=>d.resolve(e)),t=d.resolve(a);for(;!await m.pathExists(t);){let i=d.dirname(t);if(i===t)return false;t=i;}let o=await m.realpath(t).catch(()=>d.resolve(t));return I(r,o)}function te(e,a,r){let t=d.isAbsolute(a)?d.resolve(a):d.resolve(e,a);if(!I(e,t)&&!(r&&I(d.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!I(e,t)&&r){let o=d.resolve(r),i=d.relative(o,t).split(d.sep).join("/"),n=`external/${d.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return d.relative(e,t).split(d.sep).join("/")||"."}function X(e){let a=e.replaceAll("\\","/").replace(/^\.\//,""),r=/^external\/([^/]+)(?:\/(.*))?$/.exec(a);if(!r)return;let t=r[2]??"";if(!t.split("/").some(o=>o===".."))return {root:`external/${r[1]}`,suffix:t}}async function T(e){if(d.isAbsolute(e.value))return d.resolve(e.value);let a=X(e.value);if(!a)return d.resolve(e.workspacePath,e.value);if(e.projectBoundary)return d.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$2({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&d.basename(d.resolve(o.externalPath))===a.root.slice(9)||e.projectName!==void 0&&o.slug===e.projectName);if(!t?.externalPath)throw new Error(`Portable external project reference is not canonically registered: ${a.root}`);return d.resolve(t.externalPath,a.suffix||".")}function je(e,a,r,t){let o=te(e,a,r),i=X(o);return !i||!t?o:i.suffix?`${t}/${i.suffix}`:t}async function Za(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&I(e.workspacePath,a)&&!X(e.proposal.projectPath??""))return a;let{contract:t}=await p$2({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?d.resolve(i.externalPath):d.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,u=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&u});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?d.resolve(o.externalPath):d.resolve(e.workspacePath,o.relativePath)}function ce(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return d.join(e,Le,"transactions",a)}async function ae(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return d.join(ce(e,a),Ma)}function Ge(e,a){return d.join(ce(e,a),_a)}async function re(e,a){await m.ensureDir(d.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await m.writeJson(r,a,{spaces:2}),await m.move(r,e,{overwrite:true});}function E(e,a,r,t={}){let o={sequence:e.events.length+1,at:H(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r};e.events.push(o);let i=t.status??a,n=a==="failed"||i==="failed"?"failed":a==="cancelled"?"cancelled":a==="closed"||i==="passed"||i==="completed"?"succeeded":a==="rollback"?"rolled-back":i==="blocked"?"blocked":"running";t.stageId?c$3({blockId:`repair.${t.stageId}`,status:n,message:r,component:"workspace-repair",attributes:{transactionId:e.transactionId,repairEventType:a}}):b$1({kind:n==="failed"?"operation.failed":n==="succeeded"||n==="rolled-back"?"operation.completed":"operation.started",status:n,component:"workspace-repair",message:r,correlationId:e.transactionId,attributes:{repairEventType:a}});}async function x(e,a,r){a.revision+=1,a.updatedAt=H(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(d.join(e,b),a);}async function le(e){let a$2=await m.readJson(Se(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function Ce(e,a){return await m.readJson(Ge(e,a))}function ne(e){return e.schemaVersion===d$2}async function de(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=await T({workspacePath:e,value:t,projectBoundary:r,projectName:a.projectName});if(!I(e,o)&&!X(t)&&!(r&&d.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:te(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Oe(e){return m.readFile(e,"utf8").catch(()=>"")}async function Qa(e){return m.readJson(e).catch(()=>({}))}function va(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function et(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=d.extname(e).length>0;return (process.env.PATH??"").split(d.delimiter).filter(Boolean).flatMap(t=>r?[d.join(t,e)]:a.map(o=>d.join(t,`${e}${o}`)))}function Pa(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ya(e,a){try{let r=await execa(e,["--version"],{cwd:a,shell:false,reject:false,timeout:5e3,maxBuffer:65536,stdin:"ignore"});return r.exitCode!==void 0&&r.exitCode!==null}catch{return false}}async function Wa(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(d.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=d.isAbsolute(r)?r:d.resolve(a,r),o=await m.stat(t).catch(()=>{});return Pa(o)&&ya(t,a)}for(let t of et(r)){let o=await m.stat(t).catch(()=>{});if(Pa(o)&&await ya(t,a))return true}return false}async function ze(e){let a=new Set;for(let i of e.stages){if(i.kind!=="repair"||!i.invocation)continue;let n=Te(i.invocation.executable);if(!["python","python3","py"].includes(n)||!i.invocation.args.includes("venv")||!i.invocation.args.includes(".venv"))continue;let s=await T({workspacePath:e.workspacePath,value:i.invocation.cwd});a.add(d.normalize(d.join(s,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(i=>i.required&&i.status!=="skipped"&&i.invocation).map(i=>i.invocation),t=new Map;for(let i of r)t.set(`${i.cwd}\0${i.executable}`,i);let o=[];for(let i of t.values()){let n=await T({workspacePath:e.workspacePath,value:i.cwd}),s=d.isAbsolute(i.executable)?d.normalize(i.executable):d.normalize(d.resolve(n,i.executable));if(a.has(s)){o.push({id:`tool:${i.cwd}:${i.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${i.executable} (${i.cwd}).`});continue}let u=await Wa({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:u?"passed":"failed",message:u?`Required repair executable is available: ${i.executable} (${i.cwd}).`:`Required repair executable is unavailable: ${i.executable} (${i.cwd}). Install or configure it, then create a fresh plan.`});}return o}function oe(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function P(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function at(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return v({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function tt(e){let a=await de(e.workspacePath,e.action,e.authorizedProjectRoot),r=X(e.action.projectPath??"")?.root??te(e.workspacePath,a,a),t=async g=>m.pathExists(d.join(a,g)),o=new Set,i=[],n=[],s=g=>`${r}:${e.adapterId}:${g}`,u=g=>g.forEach(f=>o.add(te(e.workspacePath,d.join(a,f),a))),c=g=>{i.push(g),g.required&&g.status==="blocked"&&n.push(g.summary);},p=at(e.workspacePath,a,e.action),k=()=>{let g$1=g.find(f=>f.id===e.adapterId);if(!g$1)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:g$1.id,ecosystem:g$1.ecosystem,projectPath:r,manifests:g$1.manifests,support:g$1.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(f=>f.required&&f.invocation).map(f=>f.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${g$1.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let g=await Qa(d.join(a,"package.json")),f=g.scripts&&typeof g.scripts=="object"&&!Array.isArray(g.scripts)?g.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",B=b==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":b==="pnpm"?"pnpm-lock.yaml":b==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";u(["package.json",B]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${b} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:["install"],purpose:"reconcile"})}));let V=v(b==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return c(P({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:p??V})),c(typeof f.test=="string"&&f.test.trim()?P({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):oe(s("test"),"test","No test script is declared.")),c(typeof f.build=="string"&&f.build.trim()?P({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:va({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):oe(s("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){u(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let g=e.action.transaction?.ecosystem.toLowerCase(),f=d.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=f==="uv"||g==="uv"||await t("uv.lock"),B=!b&&(f==="poetry"||g==="poetry"||await t("poetry.lock")),V=!b&&!B&&["python","python3","py"].includes(f)&&(e.action.invocation?.args??[]).some(M=>M==="venv")&&(e.action.invocation?.args??[]).some(M=>M===".venv"),W=process.platform==="win32"?"python":"python3",D=d.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await m.pathExists(D)||V)&&(W=D);let _=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):B?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:_})),c(P({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:p}));let L=await Oe(d.join(a,"pyproject.toml")),pe=await t("tests")||/\[tool\.pytest/i.test(L),Z=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pytest"],purpose:"test"}),se=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","build"],purpose:"build"});return c(pe?P({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:Z}):oe(s("test"),"test","No Python test surface is declared.")),c(/\[build-system\]/i.test(L)?P({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:se}):oe(s("build"),"build","No Python build contract is declared.")),k()}let w=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let g of w){if(g.adapterId!==e.adapterId)continue;let f=await t(g.manifest)?g.manifest:g.alternateManifest&&await t(g.alternateManifest)?g.alternateManifest:void 0;if(!f)continue;u(g.files),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${f} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.reconcile[0],args:g.reconcile[1],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:p??(g.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:g.audit[0],args:g.audit[1],purpose:"audit"}):void 0)}));let b=await Oe(d.join(a,f)),B=g.manifest==="composer.json"||g.adapterId==="deno"?/["']test["']\s*:/.test(b):g.manifest==="Gemfile"?await t("Rakefile"):true,V=g.manifest==="composer.json"||g.manifest==="deno.json"?/["']build["']\s*:/.test(b):g.manifest==="Gemfile"?(await m.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return c(B?P({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.test[0],args:g.test[1],purpose:"test"})}):oe(s("test"),"test","No test contract is declared.")),c(V?P({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.build[0],args:g.build[1],purpose:"build"})}):oe(s("build"),"build","No build contract is declared.")),k()}let j=await m.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&j.some(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g)))return u(["Directory.Packages.props","packages.lock.json",...j.filter(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g))]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:p??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),c(P({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),k();let y=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return u(["pom.xml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["dependency:resolve"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["package","-DskipTests"],purpose:"build"})})),k();let $=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&$){let g=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return u([$,"gradle.lockfile","gradle/libs.versions.toml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["dependencies"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["build","-x","test"],purpose:"build"})})),k()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let g=q==="deps.edn",f=await Oe(d.join(a,q)),b=g?"clojure":"lein";u([q]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-P"]:["deps"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:p}));let B=!g||/:test\b/.test(f);return c(B?P({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-M:test"]:["test"],purpose:"test"})}):oe(s("test"),"test","No Clojure :test alias is declared.")),c(g?oe(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):P({id:s("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),k()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(u(["build.sbt"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),c(P({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),k())}async function Ta(e){let a=i=>m.pathExists(d.join(e,i)),r=await m.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(i=>/\.(?:cs|fs|vb)proj$|\.slnx?$/i.test(i))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(g.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function rt(e){let a=e?.trim().toLowerCase();if(a){if(["npm","pnpm","yarn","bun","node","javascript","typescript"].includes(a))return "node";if(["python","pip","poetry","uv"].includes(a))return "python";if(["go","gomod","go-modules"].includes(a))return "go";if(["rust","cargo"].includes(a))return "rust";if(["php","composer"].includes(a))return "php-composer";if(["ruby","bundler","bundle"].includes(a))return "ruby-bundler";if(["elixir","mix"].includes(a))return "elixir-mix";if(a==="deno")return "deno";if(["dotnet",".net","nuget"].includes(a))return "dotnet";if(["maven","jvm-maven"].includes(a))return "jvm-maven";if(["gradle","jvm-gradle"].includes(a))return "jvm-gradle";if(["clojure","lein","leiningen"].includes(a))return "clojure";if(["scala","sbt","scala-sbt"].includes(a))return "scala-sbt"}}async function Na(e,a={}){let r=await de(e.workspacePath,e.action,e.authorizedProjectRoot),t=X(e.action.projectPath??"")?.root??te(e.workspacePath,r,r),o=await Ta(r),i=rt(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let c=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[P({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:i,ecosystem:g.find(p=>p.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:c}]}}if(n.length===0){let c=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[P({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:c}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let c of n){let p=await tt({...e,adapterId:c});s.stages.push(...p.stages),s.checkpointFiles.push(...p.checkpointFiles),s.blockers.push(...p.blockers),s.adapters.push(...p.adapters);}s.stages=[...new Map(s.stages.map(c=>[c.id,c])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let u=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let c=new Set(e.action.transaction.requiredStages),p=Te(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],w=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(p)&&k.includes("venv")&&k.includes(".venv");w&&u.add(d.normalize(d.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(j=>j.kind==="reconcile"?w&&c.has("reconcile"):c.has(j.kind)),s.blockers=s.stages.filter(j=>j.required&&j.status==="blocked").map(j=>j.summary);}for(let c of s.adapters){let p=s.stages.filter(w=>w.id.startsWith(`${c.projectPath}:${c.adapterId}:`)),k=[];c.requiredExecutables=[...new Set(p.filter(w=>w.required&&w.invocation).map(w=>w.invocation.executable))];for(let w of p){if(!w.required||!w.invocation)continue;let j=await T({workspacePath:e.workspacePath,value:w.invocation.cwd,projectBoundary:r}),y=d.isAbsolute(w.invocation.executable)?d.normalize(w.invocation.executable):d.normalize(d.resolve(j,w.invocation.executable));u.has(y)||await Wa({workspacePath:e.workspacePath,invocation:w.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||k.push(w.invocation.executable);}c.missingExecutables=[...new Set(k)],c.missingExecutables.length>0&&(c.status="partial",c.message=`Required executable(s) unavailable: ${c.missingExecutables.join(", ")}.`);}if(n.length===1){let c=`:${n[0]}:`;for(let p of s.stages)p.id=p.id.replace(c,":");}return s}async function Xt(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=d.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let i=e.project.trim(),n=await m$1(r),s=i.replace(/\\/g,"/").replace(/^\.\//,""),u=d.resolve(r,i),c=n.resolved.filter(p=>{let k=I(r,p.projectPath)?te(r,p.projectPath):void 0;return p.name===i||k===s||d.resolve(p.projectPath)===u});if(c.length===0){let p=n.skipped.find(k=>k.name===i);throw p?new Error(`Registered project is unavailable for repair capability inspection: ${i} (${p.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i}.`)}if(c.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i}.`);t=d.resolve(c[0].projectPath),o=c[0].name;}else {if(t=d.resolve(r,e.projectPath??"."),!I(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=te(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ta(t)}}}function We(e){if(e.command){let a=g$1(e.command);if(a)return a}return a$4(e.operation)??void 0}async function ot(e){let a=new Set,r=e.actions[0]?await de(e.workspacePath,e.actions[0]):void 0,t=X(e.actions[0]?.projectPath??"")?e.actions[0]?.projectPath:void 0;for(let o of e.dependencyFiles){let i=await T({workspacePath:e.workspacePath,value:o,projectBoundary:r,projectName:e.actions[0]?.projectName});a.add(je(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await de(e.workspacePath,o),n=X(o.projectPath??"")?i:e.workspacePath;if(!await z(n,i))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${i}`);let s=o.transaction?.kind==="dependency-materialization"&&o.transaction.sourceMutationRequired===false;for(let p of s?[]:o.files){let k=await T({workspacePath:e.workspacePath,value:p,projectBoundary:X(p)?i:void 0,projectName:o.projectName});if(!await z(n,k))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${p}`);a.add(je(e.workspacePath,k,i,X(o.projectPath??"")?o.projectPath:void 0));}let u=We(o);if(!u)continue;let c="path"in u?u.path:void 0;if(c){let p=d.resolve(i,c);if(!await z(n,p))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${c}`);a.add(je(e.workspacePath,p,i,X(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function st(e,a){if(!a.invocation)return;let r=await de(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ke(e){return C(K({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function Ve(e){return Ke({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function qa(e){return C(K({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Zt(e){let a=d.resolve(e.workspacePath),r=await le({workspacePath:a,transactionId:e.transactionId}),t=await Ce(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Ve(r)!==r.integrity.planHash||!r.integrity.closureHash||qa(r)!==r.integrity.closureHash||C(K(t))!==r.integrity.sourceEvidenceHash||!ne(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=await ae(a,r);for(let i of r.checkpoint.files){let n=await T({workspacePath:a,value:i.path,projectBoundary:o,projectName:r.target.projectName});if(!I(a,n)&&!(o&&I(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await m.lstat(n).catch(()=>{});if(!s){if(i.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${i.path}`);continue}if(!s.isFile()||s.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${i.path}`);let u=await m.readFile(n);if(i.afterHash!==C(u))throw new Error(`Goal repair output changed after transaction closure: ${i.path}`);if(i.mode!==void 0&&s.mode!==i.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${i.path}`)}return r.verification.sourceBinding}async function $e(e,a,r){let t=[],o=[],i=0;for(let n of a){let s=await T({workspacePath:e,value:n,projectBoundary:r}),u=r&&I(d.resolve(r),s)?d.resolve(r):e;if(!I(u,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await z(u,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let c=await m.lstat(s).catch(()=>{});if(c?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(c&&!c.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(c&&c.size>Ia){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=c?.size??0,i>Ga){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=c?await m.readFile(s):void 0;t.push({path:n,existed:!!c,beforeHash:p?C(p):null,...c?{mode:c.mode}:{}});}return {entries:t,errors:o}}function Ba(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}function it(e,a){if(!(!/\.json$/i.test(e)||a===void 0))try{JSON.parse(a);return}catch{return `${e} must contain valid JSON; comments and trailing syntax are not allowed.`}}async function nt(e){let a=await m.readJson(d.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():d.basename(e)}function ct(e){return Va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function dt(e,a){let r=d.resolve(e,a),t=d.dirname(r);for(;I(e,t);){if((await m.readdir(t).catch(()=>[])).some(ct))return t;if(d.resolve(t)===d.resolve(e))break;t=d.dirname(t);}return e}function lt(e,a,r){return r.some(t=>{let o=d.resolve(e,t.path);if(!I(a,o))return false;let i=d.basename(o);return Ja.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function pt(e){let a=!I(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:te(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function ut(e,a){let r=Te(a.executable),[t="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(r);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(s=>/^(?:test|build|check|verify|package)$/i.test(s))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function ht(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let u=d.resolve(e.workspacePath,s.cwd),c=te(e.workspacePath,u,n),p=await m.lstat(u).catch(()=>{});if(!p?.isDirectory()||p.isSymbolicLink()||!await z(n??e.workspacePath,u)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!I(n,u)){t.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(G[s.risk]>G[e.maxRisk]){t.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:u,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Je(e.workspacePath,k,e.policy,e.projectRoots),ut(s,k);}catch(w){t.push(w instanceof Error?w.message:String(w));continue}a.push(P({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:k})),i.add(`${c}:${s.kind}`);}for(let s of e.projectRoots){let u=pt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),c=await Na({workspacePath:e.workspacePath,action:u,authorizedProjectRoot:s},e.dependencies);o.push(...c.adapters);let p=lt(e.workspacePath,s,e.proposal.changes);if(p){for(let w of c.checkpointFiles)r.add(w);t.push(...c.blockers);}let k=te(e.workspacePath,s,s);for(let w of c.stages)!p&&!["test","build"].includes(w.kind)||i.has(`${k}:${w.kind}`)||a.push(w);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function gt(e,a$3={}){let r=d.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(h=>h.cardId===e.cardId).filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),i=e.actionId?o.filter(h=>h.id===e.actionId):o,n=t.actions.filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),s=new Map(n.map(h=>[h.id,h])),u=h=>{let R=new Set(h.map(J=>J.id)),F=[...h];for(;F.length>0;){let J=F.pop();for(let U of J?.dependsOn??[]){let Y=s.get(U);!Y||R.has(Y.id)||(R.add(Y.id),F.push(Y));}}return n.filter(J=>R.has(J.id))},c$1=i.filter(h=>h.findingStatus==="blocking"||h.notes.includes("Doctor finding status: blocking")),p=c$1.length>0?c$1:i.filter(h=>h.findingStatus!=="informational"),k=e.actionId?i.filter(h=>h.id===e.actionId):[],w=[...p].sort((h,R)=>{let F=h.status==="ready"||h.status==="review-required"?0:1,J=R.status==="ready"||R.status==="review-required"?0:1;return F-J||h.order-R.order||h.id.localeCompare(R.id)})[0],j=w?p.filter(h=>h.cardId===w.cardId&&h.findingId===w.findingId&&h.causalKey===w.causalKey&&h.projectName===w.projectName&&h.projectPath===w.projectPath):[],y=u(e.actionId?k:j),$=e.maxRisk??"guarded",q={maxRisk:$,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},g=[{id:"workspace-root",status:await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:y.length>0?"passed":"failed",message:y.length>0?`${y.length} governed action(s) selected.`:"No governed remediation action matches this target."}],f=Ca(y);f&&g.push(f);let b$1=[],B=[],V=[],W=[],D=new Set(["replan","manual-repair","cancel"]);for(let h of y){let R=We(h),F=await st(r,h);if(G[h.risk]<=G[$]||(W.push(`${h.id} exceeds the approved ${$} risk ceiling.`),D.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),(h.status==="blocked"||h.status==="guidance-only")&&W.push(`${h.id} is ${h.status}: ${h.blocker}`),!R&&!F&&W.push(`${h.id} has no typed operation or structured invocation.`),F)try{Je(r,F,q);}catch(U){let Y=U instanceof Error?U.message:String(U);W.push(Y),/Force-based/.test(Y)&&D.add("allow-force"),/Breaking dependency/.test(Y)&&D.add("allow-breaking");}if(b$1.push({id:`action:${h.id}`,kind:"repair",status:R||F?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,...F?{invocation:F}:{}}),h.transaction){let U=await Na({workspacePath:r,action:h},a$3);b$1.push(...U.stages),B.push(...U.checkpointFiles),W.push(...U.blockers),V.push(...U.adapters);}}let _=[...new Map(b$1.map(h=>[h.id,h])).values()];b$1.splice(0,b$1.length,..._),b$1.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),b$1.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),b$1.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),g.push(...await ze({workspacePath:r,stages:b$1,toolAvailable:a$3.toolAvailable}));let L=await ot({workspacePath:r,actions:y,dependencyFiles:B}),pe=y[0]?await de(r,y[0]):void 0,Z=await $e(r,L,pe);g.push({id:"rollback-coverage",status:y.some(h=>h.mode==="edit-file"||h.mode==="run-command")&&L.length===0?"failed":"passed",message:L.length>0?`${L.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),g.push({id:"structured-execution",status:b$1.some(h=>h.required&&h.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),g.push({id:"checkpoint-boundary",status:Z.errors.length===0?"passed":"failed",message:Z.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":Z.errors.join(" ")});let se=C(K(t)),M=[...new Set(y.map(h=>h.projectPath).filter(Boolean))],xe=[...new Set(y.map(h=>h.projectName).filter(Boolean))],ue=xe.length===1?xe[0]:void 0,Ie=M.length===1&&xe.length<=1,ie={cardId:e.cardId,scope:Ie?"project":"workspace",...ue?{projectName:ue}:{},...M.length===1?{projectPath:M[0]}:{},actionIds:y.map(h=>h.id)},ke=H(a$3.now),he=`repair_${randomUUID().replaceAll("-","")}`,Q=g.some(h=>h.status==="failed")||W.length>0,we=[...W,...g.filter(h=>h.status==="failed").map(h=>h.message)],be=[...new Map(V.map(h=>[`${h.projectPath}:${h.adapterId}`,h])).values()],l=Ea({actions:y,adapters:be,preconditions:g,stages:b$1,decisionOptions:D,maxRisk:$,fallbackReasons:we}),S={schemaVersion:a,transactionId:he,revision:1,createdAt:ke,updatedAt:ke,workspace:{name:t.workspace.name,rootRef:"."},target:ie,state:Q?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:g,adapterEvaluations:be,checkpoint:{status:L.length>0?"pending":"unavailable",files:Z.entries},stages:b$1,...Q?{decision:{reason:[...new Set(we)].join(" "),options:[...D],causes:l}}:{},events:[],integrity:{sourceEvidenceHash:se,planHash:Ke({sourceEvidenceHash:se,target:ie,policy:q,preconditions:g,adapterEvaluations:be,stages:b$1,checkpointFiles:Z.entries})}};E(S,"planned",Q?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let N=await $a(r,S);if(N)return N;let ge=ce(r,he);return await m.ensureDir(ge),await re(Ge(r,he),t),await re(Se(r,he),S),await re(d.join(r,b),S),S}async function ft(e$1,a={}){let r=e$1.proposal.goalId;if(!r)return Ra(e$1,a);let t=d.resolve(e$1.workspacePath);return e(t,`.workspai/goals/${r}/repair-proposal`,()=>Ra({...e$1,workspacePath:t},a))}async function Ra(e,a$3={}){a$1(e.proposal,e$1,"Workspace repair proposal");let r=d.resolve(e.workspacePath),t=JSON.parse(JSON.stringify(e.proposal));if(t.goalId){let l$1=await l({workspacePath:r,goalId:t.goalId});if(!l$1.active||l$1.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(l$1.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${l$1.goalPack?.state??"missing"}`);if((l$1.active.repairTransactionIds??(l$1.active.repairTransactionId?[l$1.active.repairTransactionId]:[])).length>=l$1.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${l$1.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(l$1.goalPack.scope.kind==="project"||l$1.goalPack.scope.kind==="project-set"){let N=l$1.goalPack.scope.projects;if(!t.projectName||!N.includes(t.projectName))throw new Error(l$1.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${N[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${N.join(", ")}).`)}}let o=e.maxRisk??"guarded",i={maxRisk:o,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},n=[],s=[],u=new Set(["replan","manual-repair","cancel"]),c$1=await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"));n.push({id:"workspace-root",status:c$1?"passed":"failed",message:c$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let p$1;try{p$1=await Za({workspacePath:r,proposal:t});}catch(l){s.push(l instanceof Error?l.message:String(l));}let k=p$1&&!I(r,p$1)&&t.projectName?`external/${t.projectName}`:void 0;if(p$1&&(t.projectName||t.projectPath)&&(t.projectPath=k??d.relative(r,p$1).split(d.sep).join("/")),t.projectPath){let l=p$1??d.resolve(r,t.projectPath),S=await m.lstat(l).catch(()=>{});(!S?.isDirectory()||S.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(l=>({...l,cwd:je(r,l.cwd,p$1,k)}));let w=new Set,j=new Set,y=0;for(let l of t.changes){l.path=je(r,l.path,p$1,k),l.path==="."&&s.push(`${l.id} cannot replace the workspace root.`),w.has(l.id)&&s.push(`Duplicate proposal change id: ${l.id}.`),j.has(l.path)&&s.push(`Multiple proposal changes target ${l.path}.`),w.add(l.id),j.add(l.path),y+=Buffer.byteLength(l.content??"","utf8"),y>za&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let S=Ba(l.path);if(S&&s.push(`${l.path}: ${S}`),l.operation==="write"){let N=it(l.path,l.content);N&&s.push(N);}if(G[l.risk]>G[o]&&(s.push(`${l.id} exceeds the approved ${o} risk ceiling.`),u.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let N=p$1??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ge=await T({workspacePath:r,value:l.path,projectBoundary:N,projectName:t.projectName});I(N,ge)||s.push(`${l.path} escapes the declared project scope.`);}}let $=[...j].sort(),q=await $e(r,$,p$1);s.push(...q.errors);let g=new Map(q.entries.map(l=>[l.path,l]));for(let l of t.changes){let S=g.get(l.path);if(!S||S.beforeHash!==l.expectedBeforeHash){s.push(`${l.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}l.operation==="delete"&&!S.existed&&s.push(`${l.path} cannot be deleted because it does not exist.`),l.operation==="write"&&S.beforeHash!==null&&C(l.content??"")===S.beforeHash&&s.push(`${l.path} is a no-op and cannot prove source progress.`);}n.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let f=new Set;if(t.projectPath)f.add(p$1??d.resolve(r,t.projectPath));else for(let l of t.changes)f.add(await dt(r,l.path));let b$1=await ht({workspacePath:r,proposal:t,projectRoots:[...f].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...b$1.blockers);let B=b$1.stages,V=B.some(l=>l.status!=="skipped"&&["audit","test","build"].includes(l.kind));n.push({id:"validation-coverage",status:V?"passed":"unknown",message:V?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let W=[...new Set([...$,...b$1.checkpointFiles])].sort(),D=await $e(r,W,p$1);s.push(...D.errors),n.push({id:"checkpoint-boundary",status:D.errors.length===0?"passed":"failed",message:D.errors.length===0?`${D.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:D.errors.join(" ")});let _=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(l=>({id:`proposal:${l.id}`,kind:"repair",status:G[l.risk]<=G[o]?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,changedPaths:[l.path]})),...B,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];n.push(...await ze({workspacePath:r,stages:_,toolAvailable:a$3.toolAvailable}));let L=new Set(_.map(l=>l.id));L.size!==_.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:L.size===_.length?"passed":"failed",message:L.size===_.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let l=false,S=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),N=S.actions.filter(A=>A.cardId===t.cardId&&(!t.projectName||A.projectName===t.projectName)&&(!t.projectPath||A.projectPath===t.projectPath));if(!t.targetActionIds?.length){let A=ba(N);A.size===1?t.targetActionIds=N.map(Oa=>Oa.id).sort():A.size>1&&(l=true,s.push(`Repair proposal target is ambiguous: ${A.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ge=[...new Set(t.targetActionIds??[])],h=new Set(ge),R=S.actions.filter(A=>h.has(A.id)),F=new Set(R.map(A=>A.id)),J=ge.filter(A=>!F.has(A));J.length>0&&(l=true,s.push(`Repair proposal references stale or unknown causal action ids: ${J.join(", ")}.`)),R.filter(A=>A.cardId!==t.cardId||t.projectName!==void 0&&A.projectName!==t.projectName||t.projectPath!==void 0&&A.projectPath!==t.projectPath).length>0&&(l=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let Y=ba(R);Y.size>1&&(l=true,s.push(`Repair proposal combines ${Y.size} independent causal finding families. Create one transaction per finding family.`)),R.length>0&&!t.blockerSignature&&(l=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(R.map(A=>A.projectName??A.projectPath).filter(A=>!!A)).size>0&&!t.projectName&&!t.projectPath&&(l=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),R.length>0&&R.every(A=>A.mode==="run-command"&&A.transaction?.kind==="dependency-materialization"&&A.transaction.sourceMutationRequired===false)&&(l=true,s.push("The selected causal action is command-owned and declares that source mutation is not required. Execute the canonical action instead of submitting a model source proposal.")),n.push({id:"causal-target-binding",status:!l&&(R.length>0||N.length===0)?"passed":"failed",message:R.length>0?`${R.length} action(s) bind this proposal to one canonical causal target.`:N.length===0?"No canonical remediation action exists; the bounded source proposal remains the explicit target.":"A single canonical causal target is required before source mutation."});let Ue=Ca(R);Ue&&n.push(Ue);}catch{}let pe=C(K(t)),Z={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(l=>`proposal:${l.id}`)},se=H(a$3.now),M=`repair_${randomUUID().replaceAll("-","")}`,ue=n.some(l=>l.status==="failed")||s.length>0,Ie=[...s,...n.filter(l=>l.status==="failed"&&l.id!=="proposal-boundary").map(l=>l.message)],ie=Ea({adapters:b$1.adapters,preconditions:n,stages:_,decisionOptions:u,maxRisk:o,fallbackReasons:Ie});for(let l of t.changes)G[l.risk]<=G[o]||ie.push({kind:"risk-approval",id:`risk:${l.id}`,message:`${l.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let ke=ie.length>0&&ie.every(l=>l.kind==="failed-precondition")&&n.some(l=>l.id==="proposal-boundary"&&l.status==="failed"),he=ke?["replan","cancel"]:[...u],Q={schemaVersion:a,transactionId:M,revision:1,createdAt:se,updatedAt:se,workspace:{name:await nt(r),rootRef:"."},target:Z,state:ue?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:b$1.adapters,checkpoint:{status:"pending",files:D.entries},stages:_,...ue?{decision:{reason:[...new Set(Ie)].join(" "),options:he,causes:ie}}:{},events:[],integrity:{sourceEvidenceHash:pe,planHash:Ke({sourceEvidenceHash:pe,target:Z,policy:i,preconditions:n,adapterEvaluations:b$1.adapters,stages:_,checkpointFiles:D.entries})}};E(Q,"planned",ue?ke?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(Q,c,"Workspace repair transaction");let we=await $a(r,Q);if(we)return we;let be=ce(r,M);return await m.ensureDir(be),await re(Ge(r,M),t),await re(Se(r,M),Q),await re(d.join(r,b),Q),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:M}),Q}async function Qt(e,a={}){let r=await le(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Ve(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=O("The compiled repair plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return C(K(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=O("The persisted source plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:H(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",E(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await x(e.workspacePath,r,a.now),r)}async function Da(e,a){let r=d.join(e,Le,La);await m.ensureDir(d.dirname(r));try{let t=await m.stat(r),o=await m.readJson(r).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,n=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&n)try{process.kill(n,0),s=true;}catch(c){s=c!==null&&typeof c=="object"&&"code"in c&&c.code==="EPERM";}let u=!!(i&&i!==hostname());!s&&!u&&Date.now()-t.mtimeMs>Ka&&await m.remove(r);}catch{}try{await m.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
|
|
2
2
|
`,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await m.readJson(r).catch(async()=>{let o=await m.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await m.remove(r);}}async function Fa(e){let a=await ae(e.workspacePath,e.transaction),r=await $e(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let i=t.get(o.path);if(!i||o.existed!==i.existed||o.beforeHash!==i.beforeHash||o.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function mt(e){if(e.transaction.checkpoint.status==="captured")return;await Fa(e);let a=d.join(ce(e.workspacePath,e.transaction.transactionId),ka);await m.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=await ae(e.workspacePath,e.transaction),i=await T({workspacePath:e.workspacePath,value:t.path,projectBoundary:o,projectName:e.transaction.target.projectName}),n=t.existed?await m.readFile(i):void 0;if(n&&C(n)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let s=`${ka}/${String(r).padStart(4,"0")}.bin`;if(n){let u=d.join(ce(e.workspacePath,e.transaction.transactionId),s),c=`${u}.${process.pid}.${randomUUID()}.tmp`;await m.writeFile(c,n,{flag:"wx"});let p=await m.readFile(c);if(C(p)!==t.beforeHash)throw await m.remove(c),new Error(`Checkpoint backup verification failed for ${t.path}.`);await m.move(c,u,{overwrite:true}),t.backupRef=s;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=H(e.now),e.transaction.state="checkpointed",E(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function ja(e,a){let r=await ae(e,a);for(let t of a.checkpoint.files){let o=await T({workspacePath:e,value:t.path,projectBoundary:r,projectName:a.target.projectName}),i=await m.readFile(o).catch(()=>{});t.afterHash=i?C(i):null;}}function Te(e){return d.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Je(e,a,r,t=[]){let o=d.resolve(e,a.cwd);if(!(I(e,o)||t.some(c=>I(c,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(c=>!c||/[\0\r\n]/.test(c)))throw new Error("Invocation contains invalid arguments.");let n=Te(a.executable),s=d.isAbsolute(a.executable),u=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!I(e,a.executable)&&!t.some(c=>I(c,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!s&&!u&&!Ua.has(n))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(c=>/^(?:--force|-f)$/i.test(c)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(c=>/(?:breaking|legacy-peer-deps)/i.test(c)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(n)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${n} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function Me(e){let a=e.projectBoundary?[d.resolve(e.projectBoundary)]:[],r=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary}),t=Je(e.workspacePath,{...e.invocation,cwd:r},e.policy,a),o=await m.lstat(t.cwd).catch(()=>{});if(!o?.isDirectory()||o.isSymbolicLink()||!await z(e.projectBoundary??e.workspacePath,t.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(d.isAbsolute(t.executable)||/^\.{1,2}[\\/]/.test(t.executable)){let s=d.isAbsolute(t.executable)?t.executable:d.resolve(t.cwd,t.executable);if(!await z(e.projectBoundary??e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),n=await execa(t.executable,e.invocation.args,{cwd:t.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:Aa,stdin:"ignore",extendEnv:false,env:{...i,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:n.exitCode??null,stdout:n.stdout??"",stderr:n.stderr??""}}function kt(e){let a=j.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function wt(e){let a=j.find(p=>p.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await m.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?await T({workspacePath:e.workspacePath,value:e.transaction.target.projectPath,projectName:e.transaction.target.projectName}):d.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);let o=a.scope==="project"?t:e.workspacePath;if(!await z(o,t))throw new Error("The target producer working directory escapes the workspace boundary.");let i=d.resolve(t,a.producerArtifact);if(!I(t,i)||!await z(t,d.dirname(i)))throw new Error("The target producer artifact escapes its canonical scope.");let n=await m.stat(i).catch(()=>{}),s=Object.fromEntries(Object.entries(process.env).filter(([p])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(p))),u=await execa(process.execPath,[r,...kt(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:Aa,stdin:"ignore",extendEnv:false,env:{...s,NO_COLOR:"1",CI:process.env.CI??"1"}}),c=await m.stat(i).catch(()=>{});return {exitCode:u.exitCode??null,stdout:u.stdout??"",stderr:u.stderr??"",evidenceProduced:!!(c?.isFile()&&(!n||c.mtimeMs!==n.mtimeMs||c.ctimeMs!==n.ctimeMs||c.size!==n.size))}}async function bt(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=ne(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=ne(e.sourcePlan)?a.actions.filter(i=>t?r.has(i.id):i.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||i.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||i.projectPath===e.transaction.target.projectPath)):a.actions.filter(i=>r.has(i.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(i=>i.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function vt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(u=>!u.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(u=>u.id)),o=a.filter(u=>!t.has(u)),i=e.transaction.preconditions.map(u=>u.id).find(u=>u.startsWith(He))?.slice(He.length),n=r.actions.filter(u=>t.has(u.id)&&a.includes(u.id)),s=o.length===0&&!!i&&Sa(n)!==i;return {current:o.length===0&&!s,missingActionIds:o,semanticDrift:s}}function ee(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
|
|
3
|
-
${e.slice(-a)}`}async function Pt(e,a){if(a.type==="file-create")return i({projectPath:e,operation:a});if(a.type==="file-append")return j$1({projectPath:e,operation:a});if(a.type==="file-copy")return k({projectPath:e,operation:a});if(a.type==="package-json-script")return h$1({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m$2({projectPath:e,operation:a});if(a.type==="env-key-add")return n({projectPath:e,operation:a});if(a.type==="makefile-target")return o({projectPath:e,operation:a})}async function yt(e){let a=await ae(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!I(a,r)||!await z(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Ba(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(k=>k.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await m.readFile(r).catch(()=>{}),n=i?C(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await m.lstat(r).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!s)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await m.remove(r);return}let u=e.change.content??"";if(Buffer.byteLength(u,"utf8")>Ia)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await m.ensureDir(d.dirname(r));let c=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await m.writeFile(c,u,{encoding:"utf8",flag:"wx"}),await m.move(c,r,{overwrite:true});let p=await m.readFile(r);if(C(p)!==C(u))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function xa(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=H(e.dependencies.now),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):wt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=ee(r.stdout),e.stage.stderrTail=ee(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=ee(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await vt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let i=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${i} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await yt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=We(a.action);if(r){let t=await de(e.workspacePath,a.action),o=await ae(e.workspacePath,e.transaction)??e.workspacePath;if(!await z(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await Pt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=ee(t.stdout),e.stage.stderrTail=ee(t.stderr),t.exitCode!==0)throw new Error(t.stderr||t.stdout||`Repair command exited with ${t.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=ee(a.stdout),e.stage.stderrTail=ee(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false}}async function Re(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",E(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=O(n,["manual-repair","cancel"]),E(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ae(e.workspacePath,e.transaction)??e.workspacePath;for(let n of e.transaction.checkpoint.files){let s=await T({workspacePath:e.workspacePath,value:n.path,projectBoundary:o,projectName:e.transaction.target.projectName});if(!I(o,s)||!await z(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let u=await m.lstat(s).catch(()=>{});if(u?.isSymbolicLink()||u&&!u.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let c=u?await m.readFile(s):void 0,p=c?C(c):null,k=n.afterHash!==void 0&&p===n.afterHash,w=a&&p===n.beforeHash;if(!k&&!w)return r(`Rollback refused because ${n.path} changed outside this transaction.`);if(!n.existed){t.push({entry:n,absolute:s});continue}if(!n.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${n.path}.`);let j=d.join(ce(e.workspacePath,e.transaction.transactionId),n.backupRef),y=await m.lstat(j).catch(()=>{});if(!y?.isFile()||y.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let $=await m.readFile(j);if(C($)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:$});}for(let n of t){if(!n.entry.existed){await m.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let u=d.join(d.dirname(n.absolute),`.${d.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await m.ensureDir(d.dirname(n.absolute)),await m.writeFile(u,s,{flag:"wx"}),n.entry.mode!==void 0&&await m.chmod(u,n.entry.mode),await m.move(u,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=H(e.dependencies.now);let i=e.transaction.stages.filter(n=>n.kind==="reconcile"&&n.invocation);for(let n of i){let s=n.invocation;if(!s)continue;let u=`rollback:${n.id}`,c=e.transaction.stages.find(w=>w.id===u&&w.kind==="rollback"),p=c??{id:u,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};c||e.transaction.stages.push(p),p.status="running",p.startedAt=H(e.dependencies.now),delete p.completedAt,delete p.exitCode,delete p.stdoutTail,delete p.stderrTail,E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let k;try{k=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});}catch(w){k={exitCode:null,stdout:"",stderr:w instanceof Error?w.message:String(w)};}if(p.exitCode=k.exitCode,p.stdoutTail=ee(k.stdout),p.stderrTail=ee(k.stderr),p.completedAt=H(e.dependencies.now),k.exitCode!==0)return p.status="failed",p.summary=k.stderr||k.stdout||`Rollback reconciliation exited with ${k.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=O(`Source files were restored, but the installed dependency tree could not be reconciled: ${p.summary}`,["manual-repair","cancel"]),E(e.transaction,"decision",e.transaction.decision.reason,{stageId:p.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false;p.status="passed",p.summary="Installed dependency tree reconciled with the restored source state.",E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,E(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}async function er(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(Ve(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let i=await Ce(r,e.transactionId);if(C(K(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;if(o.state==="approved"&&ne(i)&&i.goalId){let f=await l({workspacePath:r,goalId:i.goalId}),b=f.active?.repairTransactionIds??(f.active?.repairTransactionId?[f.active.repairTransactionId]:[]);if(f.index.activeGoalId!==i.goalId||!b.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let s=(await ze({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(s){let f=o.stages.find(b=>b.invocation&&`tool:${b.invocation.cwd}:${b.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=O(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...f?{executable:f}:{}}),E(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await x(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}let u=new Map(ne(i)?i.changes.map(f=>[`proposal:${f.id}`,{kind:"proposal",change:f}]):i.actions.map(f=>[`action:${f.id}`,{kind:"canonical",action:f}]));try{await Fa({workspacePath:r,transaction:o});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await x(r,o,a.now),o}let c=o.stages.find(f=>f.id==="target-precondition");if(!c)return o.approval.status="expired",o.state="decision-required",o.decision=O("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await x(r,o,a.now),o;if(!await xa({workspacePath:r,transaction:o,stage:c,actions:u,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=O(`Target precondition failed before checkpoint: ${c.summary}`,["cancel"]),E(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await x(r,o,a.now),o;try{await mt({workspacePath:r,transaction:o,now:a.now});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await x(r,o,a.now),o}o.state="executing",await x(r,o,a.now);for(let f of o.stages.filter(b=>b.id!=="target-precondition"&&b.id!=="canonical-verify"&&b.kind!=="rollback"))if(!await xa({workspacePath:r,transaction:o,stage:f,actions:u,dependencies:a})&&f.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(`Required stage ${f.id} failed: ${f.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(f=>f.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=H(a.now),E(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await x(r,o,a.now);let w;try{w=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(f){w={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},k.stderrTail=ee(f instanceof Error?f.message:String(f));}let j=w.status==="passed"&&w.exitCode===0?"passed":w.status==="failed"||w.exitCode===1?"failed":"blocked",y=await bt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:j}),$=y.status==="passed"&&j!=="failed",q,g;if($&&ne(i)&&i.goalId){let f=await a$3(r);if(f.status==="miss")$=false,g=`Goal-bound repair could not seal its post-repair Model/Graph source state (${f.reason}).`;else {let b=f.graph.source.inputs?.hash;b?q={modelHash:d$1(f.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$3(f.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:b}:($=false,g="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return k.status=$?"passed":"failed",k.completedAt=H(a.now),k.exitCode=w.exitCode,k.summary=$&&j==="passed"?"Selected repair target and canonical workspace verification passed.":$?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":g||(y.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${j}.`),o.verification={status:$?"passed":"failed",targetStatus:y.status,workspaceStatus:j,remainingActionIds:y.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:w.exitCode,summary:k.summary,...q?{sourceBinding:q}:{}},E(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),$?(o.state="closed",delete o.decision,E(o,"closed",k.summary,{status:"passed",now:a.now}),o.integrity.closureHash=qa(o),await x(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Rt(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ar(e,a={}){let r=await le(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,E(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await x(e.workspacePath,r,a.now),r}async function tr(e,a={}){let r=d.resolve(e.workspacePath),t=await le({workspacePath:r,transactionId:e.transactionId});if(t.state!=="decision-required"||!t.decision)throw new Error(`Repair transaction is not awaiting a decision: ${t.state}`);if(!t.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${t.decision.options.join(", ")}.`);if(e.decision==="rollback")return Rt({workspacePath:r,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(t.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,E(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await x(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Ce(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,E(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await x(r,t,a.now);let i={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(ne(o))return ft({workspacePath:r,proposal:o,...i},a);let n=t.target.actionIds.map(s=>s.startsWith("action:")?s.slice(7):s);return gt({workspacePath:r,cardId:t.target.cardId,...n.length===1?{actionId:n[0]}:{},projectName:t.target.projectName,...i},a)}async function jt(e){let a=d.join(e,Le,"transactions"),r=await m.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>le({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Qt as approveWorkspaceRepair,Zt as assertClosedGoalRepairTransactionCurrent,ar as cancelWorkspaceRepair,tr as decideWorkspaceRepair,kt as exactCardProducerArgs,er as executeWorkspaceRepair,Xt as inspectWorkspaceRepairCapabilities,jt as listWorkspaceRepairTransactions,gt as planWorkspaceRepair,ft as planWorkspaceRepairProposal,le as readWorkspaceRepairTransaction,Rt as rollbackWorkspaceRepair};
|
|
3
|
+
${e.slice(-a)}`}async function Pt(e,a){if(a.type==="file-create")return l$1({projectPath:e,operation:a});if(a.type==="file-append")return m$2({projectPath:e,operation:a});if(a.type==="file-copy")return n({projectPath:e,operation:a});if(a.type==="package-json-script")return k({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 yt(e){let a=await ae(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!I(a,r)||!await z(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Ba(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(k=>k.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await m.readFile(r).catch(()=>{}),n=i?C(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await m.lstat(r).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!s)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await m.remove(r);return}let u=e.change.content??"";if(Buffer.byteLength(u,"utf8")>Ia)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await m.ensureDir(d.dirname(r));let c=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await m.writeFile(c,u,{encoding:"utf8",flag:"wx"}),await m.move(c,r,{overwrite:true});let p=await m.readFile(r);if(C(p)!==C(u))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function xa(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=H(e.dependencies.now),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):wt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=ee(r.stdout),e.stage.stderrTail=ee(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=ee(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await vt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let i=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${i} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await yt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=We(a.action);if(r){let t=await de(e.workspacePath,a.action),o=await ae(e.workspacePath,e.transaction)??e.workspacePath;if(!await z(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await Pt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=ee(t.stdout),e.stage.stderrTail=ee(t.stderr),t.exitCode!==0)throw new Error(t.stderr||t.stdout||`Repair command exited with ${t.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=ee(a.stdout),e.stage.stderrTail=ee(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ja(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false}}async function Re(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",E(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=O(n,["manual-repair","cancel"]),E(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ae(e.workspacePath,e.transaction)??e.workspacePath;for(let n of e.transaction.checkpoint.files){let s=await T({workspacePath:e.workspacePath,value:n.path,projectBoundary:o,projectName:e.transaction.target.projectName});if(!I(o,s)||!await z(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let u=await m.lstat(s).catch(()=>{});if(u?.isSymbolicLink()||u&&!u.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let c=u?await m.readFile(s):void 0,p=c?C(c):null,k=n.afterHash!==void 0&&p===n.afterHash,w=a&&p===n.beforeHash;if(!k&&!w)return r(`Rollback refused because ${n.path} changed outside this transaction.`);if(!n.existed){t.push({entry:n,absolute:s});continue}if(!n.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${n.path}.`);let j=d.join(ce(e.workspacePath,e.transaction.transactionId),n.backupRef),y=await m.lstat(j).catch(()=>{});if(!y?.isFile()||y.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let $=await m.readFile(j);if(C($)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:$});}for(let n of t){if(!n.entry.existed){await m.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let u=d.join(d.dirname(n.absolute),`.${d.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await m.ensureDir(d.dirname(n.absolute)),await m.writeFile(u,s,{flag:"wx"}),n.entry.mode!==void 0&&await m.chmod(u,n.entry.mode),await m.move(u,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=H(e.dependencies.now);let i=e.transaction.stages.filter(n=>n.kind==="reconcile"&&n.invocation);for(let n of i){let s=n.invocation;if(!s)continue;let u=`rollback:${n.id}`,c=e.transaction.stages.find(w=>w.id===u&&w.kind==="rollback"),p=c??{id:u,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};c||e.transaction.stages.push(p),p.status="running",p.startedAt=H(e.dependencies.now),delete p.completedAt,delete p.exitCode,delete p.stdoutTail,delete p.stderrTail,E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let k;try{k=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});}catch(w){k={exitCode:null,stdout:"",stderr:w instanceof Error?w.message:String(w)};}if(p.exitCode=k.exitCode,p.stdoutTail=ee(k.stdout),p.stderrTail=ee(k.stderr),p.completedAt=H(e.dependencies.now),k.exitCode!==0)return p.status="failed",p.summary=k.stderr||k.stdout||`Rollback reconciliation exited with ${k.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=O(`Source files were restored, but the installed dependency tree could not be reconciled: ${p.summary}`,["manual-repair","cancel"]),E(e.transaction,"decision",e.transaction.decision.reason,{stageId:p.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false;p.status="passed",p.summary="Installed dependency tree reconciled with the restored source state.",E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,E(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}async function er(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(Ve(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let i=await Ce(r,e.transactionId);if(C(K(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;if(o.state==="approved"&&ne(i)&&i.goalId){let f=await l({workspacePath:r,goalId:i.goalId}),b=f.active?.repairTransactionIds??(f.active?.repairTransactionId?[f.active.repairTransactionId]:[]);if(f.index.activeGoalId!==i.goalId||!b.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let s=(await ze({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(s){let f=o.stages.find(b=>b.invocation&&`tool:${b.invocation.cwd}:${b.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=O(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...f?{executable:f}:{}}),E(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await x(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}let u=new Map(ne(i)?i.changes.map(f=>[`proposal:${f.id}`,{kind:"proposal",change:f}]):i.actions.map(f=>[`action:${f.id}`,{kind:"canonical",action:f}]));try{await Fa({workspacePath:r,transaction:o});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await x(r,o,a.now),o}let c=o.stages.find(f=>f.id==="target-precondition");if(!c)return o.approval.status="expired",o.state="decision-required",o.decision=O("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await x(r,o,a.now),o;if(!await xa({workspacePath:r,transaction:o,stage:c,actions:u,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=O(`Target precondition failed before checkpoint: ${c.summary}`,["cancel"]),E(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await x(r,o,a.now),o;try{await mt({workspacePath:r,transaction:o,now:a.now});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await x(r,o,a.now),o}o.state="executing",await x(r,o,a.now);for(let f of o.stages.filter(b=>b.id!=="target-precondition"&&b.id!=="canonical-verify"&&b.kind!=="rollback"))if(!await xa({workspacePath:r,transaction:o,stage:f,actions:u,dependencies:a})&&f.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(`Required stage ${f.id} failed: ${f.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(f=>f.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=H(a.now),E(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await x(r,o,a.now);let w;try{w=a.verify?await a.verify(r):await c$1({workspacePath:r,strict:true,agent:"generic"});}catch(f){w={status:"failed",exitCode:1,artifactPath:p$1.intelligenceRun},k.stderrTail=ee(f instanceof Error?f.message:String(f));}let j=w.status==="passed"&&w.exitCode===0?"passed":w.status==="failed"||w.exitCode===1?"failed":"blocked",y=await bt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:j}),$=y.status==="passed"&&j!=="failed",q,g;if($&&ne(i)&&i.goalId){let f=await a$3(r);if(f.status==="miss")$=false,g=`Goal-bound repair could not seal its post-repair Model/Graph source state (${f.reason}).`;else {let b=f.graph.source.inputs?.hash;b?q={modelHash:d$1(f.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$2(f.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:b}:($=false,g="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return k.status=$?"passed":"failed",k.completedAt=H(a.now),k.exitCode=w.exitCode,k.summary=$&&j==="passed"?"Selected repair target and canonical workspace verification passed.":$?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":g||(y.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${j}.`),o.verification={status:$?"passed":"failed",targetStatus:y.status,workspaceStatus:j,remainingActionIds:y.remainingActionIds,artifact:p$1.intelligenceRun,exitCode:w.exitCode,summary:k.summary,...q?{sourceBinding:q}:{}},E(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),$?(o.state="closed",delete o.decision,E(o,"closed",k.summary,{status:"passed",now:a.now}),o.integrity.closureHash=qa(o),await x(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Rt(e,a={}){let r=d.resolve(e.workspacePath),t=await Da(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ar(e,a={}){let r=await le(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,E(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await x(e.workspacePath,r,a.now),r}async function tr(e,a={}){let r=d.resolve(e.workspacePath),t=await le({workspacePath:r,transactionId:e.transactionId});if(t.state!=="decision-required"||!t.decision)throw new Error(`Repair transaction is not awaiting a decision: ${t.state}`);if(!t.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${t.decision.options.join(", ")}.`);if(e.decision==="rollback")return Rt({workspacePath:r,transactionId:e.transactionId},a);if(e.decision==="cancel"||e.decision==="manual-repair"){if(t.checkpoint.status==="captured")throw new Error("A mutated transaction must be rolled back before control is released.");return t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,E(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await x(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Ce(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,E(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await x(r,t,a.now);let i={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(ne(o))return ft({workspacePath:r,proposal:o,...i},a);let n=t.target.actionIds.map(s=>s.startsWith("action:")?s.slice(7):s);return gt({workspacePath:r,cardId:t.target.cardId,...n.length===1?{actionId:n[0]}:{},projectName:t.target.projectName,...i},a)}async function jt(e){let a=d.join(e,Le,"transactions"),r=await m.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>le({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Qt as approveWorkspaceRepair,Zt as assertClosedGoalRepairTransactionCurrent,ar as cancelWorkspaceRepair,tr as decideWorkspaceRepair,kt as exactCardProducerArgs,er as executeWorkspaceRepair,Xt as inspectWorkspaceRepairCapabilities,jt as listWorkspaceRepairTransactions,gt as planWorkspaceRepair,ft as planWorkspaceRepairProposal,le as readWorkspaceRepairTransaction,Rt as rollbackWorkspaceRepair};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as runWorkspaceStage}from'./chunk-MHQHRMKU.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-ERVWW5HX.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-
|
|
1
|
+
export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-W6WRT77T.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-3G5FF2JZ.js';import {d,s,m as m$1}from'./chunk-2LZWBUJD.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (m$1(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return d({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r){this.rebuild=r?.rebuild??(()=>s({...o})),this.now=r?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
|
package/docs/README.md
CHANGED
|
@@ -83,6 +83,7 @@ or use `import` to copy or clone one into the workspace.
|
|
|
83
83
|
| Bring an existing repository under governance | [Workspace operations](./workspace-operations.md#import-and-adoption) | Source stays in place with `adopt`, or is copied/cloned with `import` |
|
|
84
84
|
| Run the complete intelligence loop | [Unified runner](./workspace-intelligence-runner.md) | One ordered run report with durable stage evidence |
|
|
85
85
|
| Turn plain language into governed work | [Goal Packs](./goal-packs.md) | A scope-bound, evidence-pinned plan and portable agent handoff |
|
|
86
|
+
| Prove what an agent changed and why | [Proof-Carrying Change](./proof-carrying-change.md) | A Goal-bound, effect-receipted, independently verified change capsule |
|
|
86
87
|
| Ground an agent before broad source discovery | [Canonical-first agent entry](./agent-entry.md) | A portable receipt for host discovery, evidence integrity, and freshness |
|
|
87
88
|
| Repair a blocker through an approved transaction | [Workspace Repair Engine](./workspace-repair-engine.md) | Checkpointed execution, validation, canonical verify, and safe rollback |
|
|
88
89
|
| Set a release, security, or coverage outcome | [Verified engineering goals](./workspace-intelligence-runner.md#verified-engineering-goals) | A durable success contract with a current evidence-backed verdict |
|
|
@@ -111,6 +112,7 @@ with [AI Quickstart](./AI_QUICKSTART.md) only when that is your goal.
|
|
|
111
112
|
| [workspace-intelligence-runner.md](./workspace-intelligence-runner.md) | Canonical unified runner, execution envelope, report schema, exit codes, failure propagation, and CI consumption |
|
|
112
113
|
| [workspace-repair-engine.md](./workspace-repair-engine.md) | CLI-owned plan, approval, checkpoint, execution, verification, decision, and rollback state machine |
|
|
113
114
|
| [goal-packs.md](./goal-packs.md) | Plain-language intent compilation, scope/evidence binding, agent handoff, and mutation boundary |
|
|
115
|
+
| [proof-carrying-change.md](./proof-carrying-change.md) | Generation-pinned Decisions ledger, predicted-vs-actual Graph delta, receipts, verification, and capsule validation |
|
|
114
116
|
| [agent-entry.md](./agent-entry.md) | Host-native discovery, canonical evidence preflight, receipt status, privacy, and consumer integration |
|
|
115
117
|
| [workspace-knowledge-graph.md](./workspace-knowledge-graph.md) | Two-minute graph quickstart, proof model, AI/MCP consumption, performance, and honest token-efficiency measurement |
|
|
116
118
|
| [graph-benchmark-methodology.md](./graph-benchmark-methodology.md) | Reproducible payload-reduction benchmark, formulas, claim boundaries, and publication rules |
|
package/docs/ci-workflows.md
CHANGED
|
@@ -63,7 +63,7 @@ Validate or preview the current CLI announcement locally:
|
|
|
63
63
|
npm --workspace workspai run check:release-announcement
|
|
64
64
|
npm --workspace workspai run release:announcement -- \
|
|
65
65
|
--product workspai-cli \
|
|
66
|
-
--tag v0.
|
|
66
|
+
--tag v0.69.0 \
|
|
67
67
|
--markdown-output /tmp/workspai-discord-announcement.md
|
|
68
68
|
```
|
|
69
69
|
|
|
@@ -64,6 +64,17 @@ npx workspai readiness [--workspace <path>] [--json] [--strict] [--skip-verify]
|
|
|
64
64
|
npx workspai autopilot release [--mode <audit|safe-fix|enforce>] [--json] [--output <file>] [--since <ref>] [--parallel] [--max-workers <n>]
|
|
65
65
|
npx workspai goal <intent> [--workspace <path>] [--scope <workspace|project:name|projects:a,b>] [--runtime <runtime>] [--for-agent <generic|claude|codex>] [--max-attempts <1-25>] [--refresh] [--dry-run] [--json]
|
|
66
66
|
npx workspai goal <--status [goal-id]|--list|--activate <goal-id>|--cancel <goal-id>|--prepare <goal-id>|--verify <goal-id>> [--workspace <path>] [--no-run] [--json]
|
|
67
|
+
npx workspai change begin [--goal <goal-id>] [--workspace <path>] [--json]
|
|
68
|
+
npx workspai change list [--workspace <path>] [--json]
|
|
69
|
+
npx workspai change predict --change <change-id> --file <prediction.json> [--workspace <path>] [--json]
|
|
70
|
+
npx workspai change authorize --change <change-id> --effects <classes> [--granted-by <identity>] [--workspace <path>] [--json]
|
|
71
|
+
npx workspai change effect record --change <change-id> --file <effect-receipt.json> [--workspace <path>] [--json]
|
|
72
|
+
npx workspai change verify --change <change-id> [--strict] [--no-refresh] [--workspace <path>] [--json]
|
|
73
|
+
npx workspai change verification record --change <change-id> --file <verification-receipt.json> [--workspace <path>] [--json]
|
|
74
|
+
npx workspai change <status|explain> --change <change-id> [--workspace <path>] [--json]
|
|
75
|
+
npx workspai change resume --change <change-id> --to <authorized|executing|verifying> --reason <text> [--actor <identity>] [--json]
|
|
76
|
+
npx workspai change abort --change <change-id> --reason <text> [--actor <identity>] [--json]
|
|
77
|
+
npx workspai change capsule <validate|export> --change <change-id> [--output <path>] [--json]
|
|
67
78
|
npx workspai agent bootstrap [--project <path>] [--for-agent <host>] [--no-live-inputs] [--strict] [--json]
|
|
68
79
|
```
|
|
69
80
|
|
|
@@ -210,6 +221,18 @@ claim verification. Lifecycle operations are mutually exclusive, cannot be
|
|
|
210
221
|
combined with an intent or planning-only flags, and `--no-run` is valid only
|
|
211
222
|
with `--verify`. See [Goal Packs](./goal-packs.md).
|
|
212
223
|
|
|
224
|
+
`change` turns an active Goal into a Proof-Carrying Change. `list` is the
|
|
225
|
+
versioned discovery surface for open, blocked, sealed, aborted, and invalid
|
|
226
|
+
capsules. `begin` pins the
|
|
227
|
+
exact Model, Graph, and live-input generation. `predict` is explicitly
|
|
228
|
+
noncanonical and never counts as proof. A human uses `authorize` to grant
|
|
229
|
+
bounded effect classes; agents and tools then append typed, idempotent effect
|
|
230
|
+
receipts. `verify` re-observes the canonical Graph, derives the actual overlay,
|
|
231
|
+
reports prediction surprises, and records Workspace Verify against the exact
|
|
232
|
+
post-effect generation. Additional Goal-domain receipts enter through
|
|
233
|
+
`verification record`. Only complete, passing criteria can seal a capsule. See
|
|
234
|
+
[Proof-Carrying Change](./proof-carrying-change.md).
|
|
235
|
+
|
|
213
236
|
Coverage Goals are runtime-bound. Interactive terminals select from the
|
|
214
237
|
canonical Workspace Model when the chosen scope has multiple runtimes;
|
|
215
238
|
non-interactive consumers receive `needs-confirmation` and rerun with
|