workspai 0.55.0 → 0.55.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/workspace-intelligence/workspace-explain.v1.json +3 -0
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +27 -0
- package/contracts/workspace-repair-capabilities.v1.json +1 -0
- package/dist/autopilot-release-3H5FTF6H.js +1 -0
- package/dist/{chunk-B5AY55A5.js → chunk-D37NEYV6.js} +1 -1
- package/dist/{chunk-KJYLCZRI.js → chunk-DPMO4U3Z.js} +1 -1
- package/dist/{chunk-4GPKQFPY.js → chunk-DS4UYMLX.js} +1 -1
- package/dist/chunk-IBPPMOHM.js +1 -0
- package/dist/chunk-YTLUT6IA.js +13 -0
- package/dist/index.js +8 -8
- package/dist/{pipeline-ZYKDWUKK.js → pipeline-B5S6P36F.js} +1 -1
- package/dist/{verified-goal-PE2PGAHF.js → verified-goal-KOU3WJYN.js} +1 -1
- package/dist/{workspace-explain-SZI2WAAD.js → workspace-explain-ZEWVKDBF.js} +1 -1
- package/dist/{workspace-explain-contract-N2XQHAPM.js → workspace-explain-contract-6CCC26QT.js} +1 -1
- package/dist/{workspace-intelligence-runner-GLC666ER.js → workspace-intelligence-runner-SMEAB4CO.js} +1 -1
- package/dist/{workspace-mcp-serve-COA4FMCA.js → workspace-mcp-serve-X6C3AWTA.js} +1 -1
- package/dist/workspace-repair-engine-GWTXVVKB.js +3 -0
- package/dist/workspace-run-FJTBX4JQ.js +1 -0
- package/package.json +1 -1
- package/dist/autopilot-release-EZXOGAVE.js +0 -1
- package/dist/chunk-EBKYSDCX.js +0 -1
- package/dist/chunk-WZA5ISAQ.js +0 -13
- package/dist/workspace-repair-engine-NMKOWUQP.js +0 -3
- package/dist/workspace-run-2DEVJOVH.js +0 -1
- /package/dist/{chunk-BQ24743S.js → chunk-7S4QNH5A.js} +0 -0
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {c as c$2}from'./chunk-4GPKQFPY.js';import {a as a$1}from'./chunk-TEHQ7XKK.js';import {d as d$1,h as h$2,i as i$1,j as j$2,g as g$1,l,m,n}from'./chunk-CEIJIFY7.js';import {c,e,j as j$1,d,g,b as b$1,i,f}from'./chunk-B5AY55A5.js';import {h as h$1}from'./chunk-H7P7SSUW.js';import {a}from'./chunk-AFIFZTOY.js';import {a as a$2}from'./chunk-44VJHNZB.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import h from'fs-extra';var ve=".workspai/repair",sa="transaction.json",ia="source-plan.json",He="checkpoint",na="engine.lock",ze=5*1024*1024,ca=25*1024*1024,da=25*1024*1024,Ge=4*1024*1024,la=900*1e3,pa=new Set(["package.json","pyproject.toml","requirements.txt","go.mod","Cargo.toml","composer.json","Gemfile","mix.exs","deno.json","deno.jsonc","pom.xml","build.gradle","build.gradle.kts","deps.edn","project.clj","build.sbt"]),ua=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"]),V={safe:0,guarded:1,invasive:2},ha=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 q(e){return (e?.()??new Date).toISOString()}function S(e){return createHash("sha256").update(e).digest("hex")}function J(e){return Array.isArray(e)?`[${e.map(J).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)}:${J(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}var we="causal-action-integrity:";function Ue(e){return S(J([...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,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 Ye(e){if(e.length===0)return;let a=Ue(e);return {id:`${we}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function C(e,a){let r=c$1.relative(c$1.resolve(e),c$1.resolve(a));return r===""||!r.startsWith("..")&&!c$1.isAbsolute(r)}async function G(e,a){let r=await h.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await h.pathExists(t);){let s=c$1.dirname(t);if(s===t)return false;t=s;}let o=await h.realpath(t).catch(()=>c$1.resolve(t));return C(r,o)}function N(e,a){let r=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!C(e,r))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,r).split(c$1.sep).join("/")||"."}function U(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,ve,"transactions",a)}function pe(e,a){return c$1.join(U(e,a),sa)}function ye(e,a){return c$1.join(U(e,a),ia)}async function K(e,a){await h.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await h.writeJson(r,a,{spaces:2}),await h.move(r,e,{overwrite:true});}function j(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:q(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function x(e$1,a$1,r){a$1.revision+=1,a$1.updatedAt=q(r),a(a$1,e,"Workspace repair transaction"),await K(pe(e$1,a$1.transactionId),a$1),await K(c$1.join(e$1,d),a$1);}async function Z(e$1){let a$1=await h.readJson(pe(e$1.workspacePath,e$1.transactionId));if(a$1.schemaVersion!==c)throw new Error(`Unsupported repair transaction schema: ${a$1.schemaVersion}`);return a(a$1,e,"Workspace repair transaction"),a$1}async function Pe(e,a){return await h.readJson(ye(e,a))}function de(e){return e.schemaVersion===f}function re(e,a){let r=a.scope==="project"&&a.projectPath?a.projectPath:".",t=c$1.isAbsolute(r)?c$1.resolve(r):c$1.resolve(e,r);if(!C(e,t))throw new Error(`Repair project scope escapes workspace: ${r}`);return t}function b(e){return {cwd:N(e.workspacePath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function me(e){return h.readFile(e,"utf8").catch(()=>"")}async function ga(e){return h.readJson(e).catch(()=>({}))}function Be(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return b({...e,executable:e.manager,args:a,purpose:e.purpose})}function fa(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(t=>r?[c$1.join(t,e)]:a.map(o=>c$1.join(t,`${e}${o}`)))}function Le(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function Xe(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(c$1.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=c$1.isAbsolute(r)?r:c$1.resolve(a,r),o=await h.stat(t).catch(()=>{});return Le(o)}for(let t of fa(r)){let o=await h.stat(t).catch(()=>{});if(Le(o))return true}return false}async function Re(e){let a=new Set;for(let s of e.stages){if(s.kind!=="repair"||!s.invocation)continue;let d=ue(s.invocation.executable);!["python","python3","py"].includes(d)||!s.invocation.args.includes("venv")||!s.invocation.args.includes(".venv")||a.add(c$1.normalize(c$1.join(c$1.resolve(e.workspacePath,s.invocation.cwd),".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),t=new Map;for(let s of r)t.set(`${s.cwd}\0${s.executable}`,s);let o=[];for(let s of t.values()){let d=c$1.isAbsolute(s.executable)?c$1.normalize(s.executable):c$1.normalize(c$1.resolve(e.workspacePath,s.cwd,s.executable));if(a.has(d)){o.push({id:`tool:${s.cwd}:${s.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${s.executable} (${s.cwd}).`});continue}let i=await Xe({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});o.push({id:`tool:${s.cwd}:${s.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${s.executable} (${s.cwd}).`:`Required repair executable is unavailable: ${s.executable} (${s.cwd}). Install or configure it, then create a fresh plan.`});}return o}function L(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function v(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 ka(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return b({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function ma(e){let a=re(e.workspacePath,e.action),r=N(e.workspacePath,a),t=async l=>h.pathExists(c$1.join(a,l)),o=new Set,s=[],d=[],i$1=l=>`${r}:${e.adapterId}:${l}`,g=l=>l.forEach(y=>o.add(N(e.workspacePath,c$1.join(a,y)))),n=l=>{s.push(l),l.required&&l.status==="blocked"&&d.push(l.summary);},k=ka(e.workspacePath,a,e.action),u=()=>{let l=i.find(y=>y.id===e.adapterId);if(!l)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:s,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:l.id,ecosystem:l.ecosystem,projectPath:r,manifests:l.manifests,support:l.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(s.filter(y=>y.required&&y.invocation).map(y=>y.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${l.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let l=await ga(c$1.join(a,"package.json")),y=l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)?l.scripts:{},R=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",T=R==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":R==="pnpm"?"pnpm-lock.yaml":R==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";g(["package.json",T]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${R} manifest, lockfile, and installed tree.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:R,args:["install"],purpose:"reconcile"})}));let $=b(R==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:R==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:R==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return n(v({id:i$1("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:k??$})),n(typeof y.test=="string"&&y.test.trim()?v({id:i$1("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Be({workspacePath:e.workspacePath,projectPath:a,manager:R,script:"test",purpose:"test"})}):L(i$1("test"),"test","No test script is declared.")),n(typeof y.build=="string"&&y.build.trim()?v({id:i$1("build"),kind:"build",summary:"Run the declared project build contract.",invocation:Be({workspacePath:e.workspacePath,projectPath:a,manager:R,script:"build",purpose:"build"})}):L(i$1("build"),"build","No build script is declared.")),u()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){g(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let l=e.action.transaction?.ecosystem.toLowerCase(),y=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),R=y==="uv"||l==="uv"||await t("uv.lock"),T=!R&&(y==="poetry"||l==="poetry"||await t("poetry.lock")),$=!R&&!T&&["python","python3","py"].includes(y)&&(e.action.invocation?.args??[]).some(F=>F==="venv")&&(e.action.invocation?.args??[]).some(F=>F===".venv"),A=process.platform==="win32"?"python":"python3",O=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await h.pathExists(O)||$)&&(A=O);let H=R?b({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):T?b({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&C(e.workspacePath,A)?b({workspacePath:e.workspacePath,projectPath:a,executable:A,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&C(e.workspacePath,A)?b({workspacePath:e.workspacePath,projectPath:a,executable:A,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:H})),n(v({id:i$1("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:k}));let z=await me(c$1.join(a,"pyproject.toml")),_=await t("tests")||/\[tool\.pytest/i.test(z),B=b(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:R?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:A,args:["-m","pytest"],purpose:"test"}),f=b(T?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:R?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:A,args:["-m","build"],purpose:"build"});return n(_?v({id:i$1("test"),kind:"test",summary:"Run the Python test contract.",invocation:B}):L(i$1("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(z)?v({id:i$1("build"),kind:"build",summary:"Build the declared Python package.",invocation:f}):L(i$1("build"),"build","No Python build contract is declared.")),u()}let m=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let l of m){if(l.adapterId!==e.adapterId)continue;let y=await t(l.manifest)?l.manifest:l.alternateManifest&&await t(l.alternateManifest)?l.alternateManifest:void 0;if(!y)continue;g(l.files),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${y} and its lock/baseline.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l.reconcile[0],args:l.reconcile[1],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:k??(l.audit?b({workspacePath:e.workspacePath,projectPath:a,executable:l.audit[0],args:l.audit[1],purpose:"audit"}):void 0)}));let R=await me(c$1.join(a,y)),T=l.manifest==="composer.json"||l.adapterId==="deno"?/["']test["']\s*:/.test(R):l.manifest==="Gemfile"?await t("Rakefile"):true,$=l.manifest==="composer.json"||l.manifest==="deno.json"?/["']build["']\s*:/.test(R):l.manifest==="Gemfile"?(await h.readdir(a)).some(A=>A.endsWith(".gemspec")):true;return n(T?v({id:i$1("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l.test[0],args:l.test[1],purpose:"test"})}):L(i$1("test"),"test","No test contract is declared.")),n($?v({id:i$1("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l.build[0],args:l.build[1],purpose:"build"})}):L(i$1("build"),"build","No build contract is declared.")),u()}let P=await h.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&P.some(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l)))return g(["Directory.Packages.props","packages.lock.json",...P.filter(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l))]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:k??b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(v({id:i$1("test"),kind:"test",summary:"Run .NET tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(v({id:i$1("build"),kind:"build",summary:"Build the .NET project.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),u();let I=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return g(["pom.xml"]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["dependency:resolve"],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:k})),n(v({id:i$1("test"),kind:"test",summary:"Run Maven tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["test"],purpose:"test"})})),n(v({id:i$1("build"),kind:"build",summary:"Build the Maven artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["package","-DskipTests"],purpose:"build"})})),u();let W=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&W){let l=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g([W,"gradle.lockfile","gradle/libs.versions.toml"]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["dependencies"],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:k})),n(v({id:i$1("test"),kind:"test",summary:"Run Gradle tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["test"],purpose:"test"})})),n(v({id:i$1("build"),kind:"build",summary:"Build the Gradle project.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["build","-x","test"],purpose:"build"})})),u()}let w=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&w){let l=w==="deps.edn",y=await me(c$1.join(a,w)),R=l?"clojure":"lein";g([w]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${w} dependency graph.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:R,args:l?["-P"]:["deps"],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:k}));let T=!l||/:test\b/.test(y);return n(T?v({id:i$1("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:R,args:l?["-M:test"]:["test"],purpose:"test"})}):L(i$1("test"),"test","No Clojure :test alias is declared.")),n(l?L(i$1("build"),"build","No portable Clojure CLI build entrypoint is declared."):v({id:i$1("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),u()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(g(["build.sbt"]),n(v({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),n(v({id:i$1("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:k})),n(v({id:i$1("test"),kind:"test",summary:"Run sbt tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(v({id:i$1("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),u()):(d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),n(v({id:i$1("reconcile"),kind:"reconcile",required:true,summary:d[0]})),u())}async function Ze(e){let a=s=>h.pathExists(c$1.join(e,s)),r=await h.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(s=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(i.map((s,d)=>[s.id,d]));return [...new Set(t)].sort((s,d)=>(o.get(s)??999)-(o.get(d)??999))}function wa(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 Qe(e,a={}){let r=re(e.workspacePath,e.action),t=N(e.workspacePath,r),o=await Ze(r),s=wa(e.action.transaction?.ecosystem),d=s?[s]:o;if(s&&!o.includes(s)){let n=`Doctor declared the ${s} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[v({id:`${t}:${s}:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:s,ecosystem:i.find(k=>k.id===s)?.ecosystem??s,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:n}]}}if(d.length===0){let n=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[v({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:n}]}}let i$1={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let n of d){let k=await ma({...e,adapterId:n});i$1.stages.push(...k.stages),i$1.checkpointFiles.push(...k.checkpointFiles),i$1.blockers.push(...k.blockers),i$1.adapters.push(...k.adapters);}i$1.stages=[...new Map(i$1.stages.map(n=>[n.id,n])).values()],i$1.checkpointFiles=[...new Set(i$1.checkpointFiles)].sort(),i$1.blockers=[...new Set(i$1.blockers)];let g=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let n=new Set(e.action.transaction.requiredStages),k=ue(e.action.invocation?.executable??""),u=e.action.invocation?.args??[],m=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(k)&&u.includes("venv")&&u.includes(".venv");m&&g.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),i$1.stages=i$1.stages.filter(P=>P.kind==="reconcile"?m&&n.has("reconcile"):n.has(P.kind)),i$1.blockers=i$1.stages.filter(P=>P.required&&P.status==="blocked").map(P=>P.summary);}for(let n of i$1.adapters){let k=i$1.stages.filter(m=>m.id.startsWith(`${n.projectPath}:${n.adapterId}:`)),u=[];n.requiredExecutables=[...new Set(k.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))];for(let m of k){if(!m.required||!m.invocation)continue;let P=c$1.isAbsolute(m.invocation.executable)?c$1.normalize(m.invocation.executable):c$1.normalize(c$1.resolve(e.workspacePath,m.invocation.cwd,m.invocation.executable));g.has(P)||await Xe({workspacePath:e.workspacePath,invocation:m.invocation,toolAvailable:a.toolAvailable})||u.push(m.invocation.executable);}n.missingExecutables=[...new Set(u)],n.missingExecutables.length>0&&(n.status="partial",n.message=`Required executable(s) unavailable: ${n.missingExecutables.join(", ")}.`);}if(d.length===1){let n=`:${d[0]}:`;for(let k of i$1.stages)k.id=k.id.replace(n,":");}return i$1}async function at(e={}){let a=j$1();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let s=e.project.trim(),d=await h$1(r),i=s.replace(/\\/g,"/").replace(/^\.\//,""),g=c$1.resolve(r,s),n=d.resolved.filter(k=>{let u=C(r,k.projectPath)?N(r,k.projectPath):void 0;return k.name===s||u===i||c$1.resolve(k.projectPath)===g});if(n.length===0){let k=d.skipped.find(u=>u.name===s);throw k?new Error(`Registered project is unavailable for repair capability inspection: ${s} (${k.reason}).`):new Error(`Registered project not found for repair capability inspection: ${s}.`)}if(n.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${s}.`);t=c$1.resolve(n[0].projectPath),o=n[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!C(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=N(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ze(t)}}}function xe(e){if(e.command){let a=d$1(e.command);if(a)return a}if(e.operation?.type==="file-create")return e.operation}async function ba(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){for(let d of r.files)a.add(N(e.workspacePath,d));let t=xe(r);if(!t)continue;let o=re(e.workspacePath,r),s="path"in t?t.path:void 0;s&&a.add(N(e.workspacePath,c$1.resolve(o,s)));}return [...a].filter(r=>r!==".").sort()}function va(e,a){if(!a.invocation)return;let r=re(e,a);return b({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function je(e){return S(J({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 ea(e){return je({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}async function le(e,a){let r=[],t=[],o=0;for(let s of a){let d=c$1.resolve(e,s);if(!C(e,d)){t.push(`Checkpoint path escapes workspace: ${s}`);continue}if(!await G(e,d)){t.push(`Checkpoint path resolves through a link outside the workspace: ${s}`);continue}let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()){t.push(`Checkpoint refuses symbolic link mutation: ${s}`);continue}if(i&&!i.isFile()){t.push(`Checkpoint target is not a regular file: ${s}`);continue}if(i&&i.size>ze){t.push(`Checkpoint file exceeds 5 MiB: ${s}`);continue}if(o+=i?.size??0,o>ca){t.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let g=i?await h.readFile(d):void 0;r.push({path:s,existed:!!i,beforeHash:g?S(g):null,...i?{mode:i.mode}:{}});}return {entries:r,errors:t}}function aa(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}async function ya(e){let a=await h.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function Pa(e){return pa.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Ra(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;C(e,t);){if((await h.readdir(t).catch(()=>[])).some(Pa))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function xa(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!C(a,o))return false;let s=c$1.basename(o);return ua.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function ja(e){let a=N(e.workspacePath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,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 Ia(e,a){let r=ue(a.executable),[t="",o=""]=a.args;if(a.args.some(i=>/^(?:-e|--eval|-c|--command|-command)$/i.test(i)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let s=["npm","pnpm","yarn","bun"].includes(r);if(!(s&&e.kind==="audit"&&a.args.some(i=>/audit/i.test(i))||s&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(i=>/^(?:test|build|check|verify|package)$/i.test(i))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function Aa(e){let a=[],r=new Set,t=[],o=[],s=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let i of e.proposal.validation??[]){let g=c$1.resolve(e.workspacePath,i.cwd),n=N(e.workspacePath,g),k=await h.lstat(g).catch(()=>{});if(!k?.isDirectory()||k.isSymbolicLink()||!await G(e.workspacePath,g)){t.push(`Validation ${i.id} requires a real directory inside the workspace.`);continue}if(d&&!C(d,g)){t.push(`Validation ${i.id} escapes the declared project scope.`);continue}if(V[i.risk]>V[e.maxRisk]){t.push(`Validation ${i.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let u=b({workspacePath:e.workspacePath,projectPath:g,executable:i.executable,args:i.args,purpose:i.kind,timeoutMs:i.timeoutMs});try{Ie(e.workspacePath,u,e.policy),Ia(i,u);}catch(m){t.push(m instanceof Error?m.message:String(m));continue}a.push(v({id:`validation:${i.id}`,kind:i.kind,risk:i.risk,required:i.required,summary:i.summary,invocation:u})),s.add(`${n}:${i.kind}`);}for(let i of e.projectRoots){let g=ja({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await Qe({workspacePath:e.workspacePath,action:g},e.dependencies);o.push(...n.adapters);let k=xa(e.workspacePath,i,e.proposal.changes);if(k){for(let m of n.checkpointFiles)r.add(m);t.push(...n.blockers);}let u=N(e.workspacePath,i);for(let m of n.stages)!k&&!["test","build"].includes(m.kind)||s.has(`${u}:${m.kind}`)||a.push(m);}return {stages:[...new Map(a.map(i=>[i.id,i])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(i=>[`${i.projectPath}:${i.adapterId}`,i])).values()]}}async function Ea(e$1,a$2={}){let r=c$1.resolve(e$1.workspacePath),t=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(f=>f.cardId===e$1.cardId).filter(f=>!e$1.actionId||f.id===e$1.actionId).filter(f=>!e$1.projectName||f.projectName===e$1.projectName).sort((f,F)=>f.order-F.order||f.id.localeCompare(F.id)),s=o.filter(f=>f.notes.includes("Doctor finding status: blocking")),d$1=!e$1.actionId&&s.length>0?s:o,i=e$1.maxRisk??"guarded",g={maxRisk:i,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},n=[{id:"workspace-root",status:await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:d$1.length>0?"passed":"failed",message:d$1.length>0?`${d$1.length} governed action(s) selected.`:"No governed remediation action matches this target."}],k=Ye(d$1);k&&n.push(k);let u=[],m=[],P=[],I=[],W=new Set(["manual-repair","cancel"]);for(let f of d$1){let F=xe(f),D=va(r,f);if(V[f.risk]<=V[i]||(I.push(`${f.id} exceeds the approved ${i} risk ceiling.`),W.add(f.risk==="invasive"?"approve-invasive":"approve-guarded")),(f.status==="blocked"||f.status==="guidance-only")&&I.push(`${f.id} is ${f.status}: ${f.blocker}`),!F&&!D&&I.push(`${f.id} has no typed operation or structured invocation.`),D)try{Ie(r,D,g);}catch(p){let E=p instanceof Error?p.message:String(p);I.push(E),/Force-based/.test(E)&&W.add("allow-force"),/Breaking dependency/.test(E)&&W.add("allow-breaking");}if(u.push({id:`action:${f.id}`,kind:"repair",status:F||D?"pending":"blocked",required:true,risk:f.risk,summary:f.summary,...D?{invocation:D}:{}}),f.transaction){let p=await Qe({workspacePath:r,action:f},a$2);u.push(...p.stages),m.push(...p.checkpointFiles),I.push(...p.blockers),P.push(...p.adapters);}}let w=[...new Map(u.map(f=>[f.id,f])).values()];u.splice(0,u.length,...w),u.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."}),u.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),u.push({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 Re({workspacePath:r,stages:u,toolAvailable:a$2.toolAvailable}));let l=await ba({workspacePath:r,actions:d$1,dependencyFiles:m}),y=await le(r,l);n.push({id:"rollback-coverage",status:d$1.some(f=>f.mode==="edit-file"||f.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."}),n.push({id:"structured-execution",status:u.some(f=>f.required&&f.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),n.push({id:"checkpoint-boundary",status:y.errors.length===0?"passed":"failed",message:y.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":y.errors.join(" ")});let R=S(J(t)),T=[...new Set(d$1.map(f=>f.projectPath).filter(Boolean))],$={cardId:e$1.cardId,scope:d$1.some(f=>f.scope==="project")?"project":"workspace",...e$1.projectName?{projectName:e$1.projectName}:{},...T.length===1?{projectPath:T[0]}:{},actionIds:d$1.map(f=>f.id)},A=q(a$2.now),O=`repair_${randomUUID().replaceAll("-","")}`,H=n.some(f=>f.status==="failed")||I.length>0,z=[...I,...n.filter(f=>f.status==="failed").map(f=>f.message)],_={schemaVersion:c,transactionId:O,revision:1,createdAt:A,updatedAt:A,workspace:{name:t.workspace.name,rootRef:"."},target:$,state:H?"decision-required":"awaiting-approval",policy:g,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:[...new Map(P.map(f=>[`${f.projectPath}:${f.adapterId}`,f])).values()],checkpoint:{status:l.length>0?"pending":"unavailable",files:y.entries},stages:u,...H?{decision:{reason:[...new Set(z)].join(" "),options:[...W]}}:{},events:[],integrity:{sourceEvidenceHash:R,planHash:je({sourceEvidenceHash:R,target:$,policy:g,preconditions:n,adapterEvaluations:[...new Map(P.map(f=>[`${f.projectPath}:${f.adapterId}`,f])).values()],stages:u,checkpointFiles:y.entries})}};j(_,"planned",H?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$2.now}),a(_,e,"Workspace repair transaction");let B=U(r,O);return await h.ensureDir(B),await K(ye(r,O),t),await K(pe(r,O),_),await K(c$1.join(r,d),_),_}async function $a(e$1,a$2={}){a(e$1.proposal,g,"Workspace repair proposal");let r=c$1.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal)),o=e$1.maxRisk??"guarded",s={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d$1=[],i=[],g$1=new Set(["manual-repair","cancel"]),n=await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"));if(d$1.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."}),t.projectPath){t.projectPath=N(r,t.projectPath);let p=c$1.resolve(r,t.projectPath),E=await h.lstat(p).catch(()=>{});(!E?.isDirectory()||E.isSymbolicLink())&&i.push("The declared project path must be a real directory inside the workspace.");}t.validation=t.validation?.map(p=>({...p,cwd:N(r,p.cwd)}));let k=new Set,u=new Set,m=0;for(let p of t.changes){p.path=N(r,p.path),p.path==="."&&i.push(`${p.id} cannot replace the workspace root.`),k.has(p.id)&&i.push(`Duplicate proposal change id: ${p.id}.`),u.has(p.path)&&i.push(`Multiple proposal changes target ${p.path}.`),k.add(p.id),u.add(p.path),m+=Buffer.byteLength(p.content??"","utf8"),m>da&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let E=aa(p.path);if(E&&i.push(`${p.path}: ${E}`),V[p.risk]>V[o]&&(i.push(`${p.id} exceeds the approved ${o} risk ceiling.`),g$1.add(p.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let he=c$1.resolve(r,t.projectPath),oe=c$1.resolve(r,p.path);C(he,oe)||i.push(`${p.path} escapes the declared project scope.`);}}let P=[...u].sort(),I=await le(r,P);i.push(...I.errors);let W=new Map(I.entries.map(p=>[p.path,p]));for(let p of t.changes){let E=W.get(p.path);if(!E||E.beforeHash!==p.expectedBeforeHash){i.push(`${p.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}p.operation==="delete"&&!E.existed&&i.push(`${p.path} cannot be deleted because it does not exist.`),p.operation==="write"&&E.beforeHash!==null&&S(p.content??"")===E.beforeHash&&i.push(`${p.path} is a no-op and cannot prove source progress.`);}d$1.push({id:"proposal-boundary",status:i.length===0?"passed":"failed",message:i.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(i)].join(" ")});let w=new Set;if(t.projectPath)w.add(c$1.resolve(r,t.projectPath));else for(let p of t.changes)w.add(await Ra(r,p.path));let l=await Aa({workspacePath:r,proposal:t,projectRoots:[...w].sort(),maxRisk:o,policy:s,dependencies:a$2});i.push(...l.blockers);let y=l.stages,R=y.some(p=>p.status!=="skipped"&&["audit","test","build"].includes(p.kind));d$1.push({id:"validation-coverage",status:R?"passed":"unknown",message:R?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let T=[...new Set([...P,...l.checkpointFiles])].sort(),$=await le(r,T);i.push(...$.errors),d$1.push({id:"checkpoint-boundary",status:$.errors.length===0?"passed":"failed",message:$.errors.length===0?`${$.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:$.errors.join(" ")});let A=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(p=>({id:`proposal:${p.id}`,kind:"repair",status:V[p.risk]<=V[o]?"pending":"blocked",required:true,risk:p.risk,summary:p.summary,changedPaths:[p.path]})),...y,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d$1.push(...await Re({workspacePath:r,stages:A,toolAvailable:a$2.toolAvailable}));let O=new Set(A.map(p=>p.id));O.size!==A.length&&i.push("Repair proposal stage ids must be unique."),d$1.push({id:"stage-identity",status:O.size===A.length?"passed":"failed",message:O.size===A.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let p=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true});if(!t.targetActionIds?.length){let se=p.actions.filter(Q=>Q.cardId===t.cardId&&(!t.projectName||Q.projectName===t.projectName)&&(!t.projectPath||Q.projectPath===t.projectPath)).map(Q=>Q.id).sort();se.length>0&&(t.targetActionIds=se);}let E=new Set(t.targetActionIds??[]),he=p.actions.filter(se=>E.has(se.id)),oe=Ye(he);oe&&d$1.push(oe);}catch{}let H=S(J(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(p=>`proposal:${p.id}`)},_=q(a$2.now),B=`repair_${randomUUID().replaceAll("-","")}`,F=d$1.some(p=>p.status==="failed")||i.length>0,D={schemaVersion:c,transactionId:B,revision:1,createdAt:_,updatedAt:_,workspace:{name:await ya(r),rootRef:"."},target:z,state:F?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d$1,adapterEvaluations:l.adapters,checkpoint:{status:"pending",files:$.entries},stages:A,...F?{decision:{reason:[...new Set([...i,...d$1.filter(p=>p.status==="failed").map(p=>p.message)])].join(" "),options:[...g$1]}}:{},events:[],integrity:{sourceEvidenceHash:H,planHash:je({sourceEvidenceHash:H,target:z,policy:s,preconditions:d$1,adapterEvaluations:l.adapters,stages:A,checkpointFiles:$.entries})}};j(D,"planned",F?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a(D,e,"Workspace repair transaction");let Ae=U(r,B);return await h.ensureDir(Ae),await K(ye(r,B),t),await K(pe(r,B),D),await K(c$1.join(r,d),D),D}async function tt(e,a={}){let r=await Z(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(ea(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision={reason:"The compiled repair plan changed after planning.",options:["cancel"]},await x(e.workspacePath,r,a.now),r;let t=await Pe(e.workspacePath,e.transactionId);return S(J(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision={reason:"The persisted source plan changed after planning.",options:["cancel"]},await x(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:q(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",j(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await x(e.workspacePath,r,a.now),r)}async function ta(e,a){let r=c$1.join(e,ve,na);await h.ensureDir(c$1.dirname(r));try{let t=await h.stat(r),o=await h.readJson(r).catch(()=>({})),s=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,i=false;if((!s||s===hostname())&&d)try{process.kill(d,0),i=true;}catch(n){i=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let g=!!(s&&s!==hostname());!i&&!g&&Date.now()-t.mtimeMs>la&&await h.remove(r);}catch{}try{await h.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
|
|
2
|
-
`,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await h.readJson(r).catch(async()=>{let o=await h.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await h.remove(r);}}async function ra(e){let a=await le(e.workspacePath,e.transaction.checkpoint.files.map(t=>t.path));if(a.errors.length>0)throw new Error(a.errors.join(" "));let r=new Map(a.entries.map(t=>[t.path,t]));for(let t of e.transaction.checkpoint.files){let o=r.get(t.path);if(!o||t.existed!==o.existed||t.beforeHash!==o.beforeHash||t.mode!==o.mode)throw new Error(`Checkpoint precondition changed after planning: ${t.path}. Create and approve a fresh plan.`)}}async function Sa(e){if(e.transaction.checkpoint.status==="captured")return;await ra(e);let a=c$1.join(U(e.workspacePath,e.transaction.transactionId),He);await h.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=c$1.resolve(e.workspacePath,t.path),s=t.existed?await h.readFile(o):void 0;if(s&&S(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${He}/${String(r).padStart(4,"0")}.bin`;if(s){let i=c$1.join(U(e.workspacePath,e.transaction.transactionId),d),g=`${i}.${process.pid}.${randomUUID()}.tmp`;await h.writeFile(g,s,{flag:"wx"});let n=await h.readFile(g);if(S(n)!==t.beforeHash)throw await h.remove(g),new Error(`Checkpoint backup verification failed for ${t.path}.`);await h.move(g,i,{overwrite:true}),t.backupRef=d;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=q(e.now),e.transaction.state="checkpointed",j(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function Ve(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),o=await h.readFile(t).catch(()=>{});r.afterHash=o?S(o):null;}}function ue(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Ie(e,a,r){let t=c$1.resolve(e,a.cwd);if(!C(e,t))throw new Error(`Invocation cwd escapes workspace: ${a.cwd}`);if(a.args.length>100||a.args.some(i=>!i||/[\0\r\n]/.test(i)))throw new Error("Invocation contains invalid arguments.");let o=ue(a.executable),s=c$1.isAbsolute(a.executable),d=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!C(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!s&&!d&&!ha.has(o))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(i=>/^(?:--force|-f)$/i.test(i)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(i=>/(?:breaking|legacy-peer-deps)/i.test(i)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(o)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${o} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:t,executable:a.executable}}async function be(e){let a=Ie(e.workspacePath,e.invocation,e.policy),r=await h.lstat(a.cwd).catch(()=>{});if(!r?.isDirectory()||r.isSymbolicLink()||!await G(e.workspacePath,a.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(a.executable)||/^\.{1,2}[\\/]/.test(a.executable)){let s=c$1.isAbsolute(a.executable)?a.executable:c$1.resolve(a.cwd,a.executable);if(!await G(e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let t=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),o=await execa(a.executable,e.invocation.args,{cwd:a.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:Ge,stdin:"ignore",extendEnv:false,env:{...t,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:o.exitCode??null,stdout:o.stdout??"",stderr:o.stderr??""}}function Ca(e){let a=b$1.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function Wa(e){let a=b$1.find(d=>d.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await h.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);if(!await G(e.workspacePath,t))throw new Error("The target producer working directory escapes the workspace boundary.");let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(process.execPath,[r,...Ca(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:Ge,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}async function Ta(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=de(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=de(e.sourcePlan)?a.actions.filter(s=>t?r.has(s.id):s.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||s.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||s.projectPath===e.transaction.target.projectPath)):a.actions.filter(s=>r.has(s.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function qa(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(g=>!g.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(g=>g.id)),o=a.filter(g=>!t.has(g)),s=e.transaction.preconditions.map(g=>g.id).find(g=>g.startsWith(we))?.slice(we.length),d=r.actions.filter(g=>t.has(g.id)&&a.includes(g.id)),i=o.length===0&&!!s&&Ue(d)!==s;return {current:o.length===0&&!i,missingActionIds:o,semanticDrift:i}}function M(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
|
|
3
|
-
${e.slice(-a)}`}async function Na(e,a){if(a.type==="file-create")return h$2({projectPath:e,operation:a});if(a.type==="file-append")return i$1({projectPath:e,operation:a});if(a.type==="file-copy")return j$2({projectPath:e,operation:a});if(a.type==="package-json-script")return g$1({projectPath:e,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return l({projectPath:e,operation:a});if(a.type==="env-key-add")return m({projectPath:e,operation:a});if(a.type==="makefile-target")return n({projectPath:e,operation:a})}async function Fa(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!C(e.workspacePath,a)||!await G(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let r=aa(e.change.path);if(r)throw new Error(`${e.change.path}: ${r}`);let t=e.transaction.checkpoint.files.find(k=>k.path===e.change.path);if(!t)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let o=await h.readFile(a).catch(()=>{}),s=o?S(o):null;if(s!==t.beforeHash||s!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let d=await h.lstat(a).catch(()=>{});if(d?.isSymbolicLink()||d&&!d.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!d)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await h.remove(a);return}let i=e.change.content??"";if(Buffer.byteLength(i,"utf8")>ze)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await h.ensureDir(c$1.dirname(a));let g=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await h.writeFile(g,i,{encoding:"utf8",flag:"wx"}),await h.move(g,a,{overwrite:true});let n=await h.readFile(a);if(S(n)!==S(i))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function Ke(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=q(e.dependencies.now),j(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:""}):Wa))({workspacePath:e.workspacePath,transaction:e.transaction});if(e.stage.exitCode=r.exitCode,e.stage.stdoutTail=M(r.stdout),e.stage.stderrTail=M(r.stderr),r.exitCode!==0&&r.exitCode!==2)throw new Error(r.stderr||r.stdout||`Exact card producer exited with ${String(r.exitCode)}.`);if(e.stage.id==="target-precondition"){let t=await qa({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!t.current){let o=t.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${t.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${o} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await Fa({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=xe(a.action);if(r)await Na(re(e.workspacePath,a.action),r);else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??be)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=M(t.stdout),e.stage.stderrTail=M(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??be)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=M(a.stdout),e.stage.stderrTail=M(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=q(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 Ve(e.workspacePath,e.transaction),j(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=q(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await Ve(e.workspacePath,e.transaction),j(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 te(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",j(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 s=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision={reason:s,options:["manual-repair","cancel"]},j(e.transaction,"decision",s,{status:"conflicted",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let s of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,s.path);if(!C(e.workspacePath,d)||!await G(e.workspacePath,d))return r(`Rollback refused because ${s.path} escaped the workspace boundary.`);let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()||i&&!i.isFile())return r(`Rollback refused because ${s.path} is no longer a regular file.`);let g=i?await h.readFile(d):void 0,n=g?S(g):null,k=s.afterHash!==void 0&&n===s.afterHash,u=a&&n===s.beforeHash;if(!k&&!u)return r(`Rollback refused because ${s.path} changed outside this transaction.`);if(!s.existed){t.push({entry:s,absolute:d});continue}if(!s.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${s.path}.`);let m=c$1.join(U(e.workspacePath,e.transaction.transactionId),s.backupRef),P=await h.lstat(m).catch(()=>{});if(!P?.isFile()||P.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${s.path}.`);let I=await h.readFile(m);if(S(I)!==s.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${s.path}.`);t.push({entry:s,absolute:d,backup:I});}for(let s of t){if(!s.entry.existed){await h.remove(s.absolute);continue}let d=s.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${s.entry.path}.`);let i=c$1.join(c$1.dirname(s.absolute),`.${c$1.basename(s.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await h.ensureDir(c$1.dirname(s.absolute)),await h.writeFile(i,d,{flag:"wx"}),s.entry.mode!==void 0&&await h.chmod(i,s.entry.mode),await h.move(i,s.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=q(e.dependencies.now);let o=e.transaction.stages.filter(s=>s.kind==="reconcile"&&s.invocation);for(let s of o){let d=s.invocation;if(!d)continue;let i=`rollback:${s.id}`,g=e.transaction.stages.find(u=>u.id===i&&u.kind==="rollback"),n=g??{id:i,kind:"rollback",status:"pending",required:true,risk:s.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};g||e.transaction.stages.push(n),n.status="running",n.startedAt=q(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,j(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let k;try{k=await(e.dependencies.runInvocation??be)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy});}catch(u){k={exitCode:null,stdout:"",stderr:u instanceof Error?u.message:String(u)};}if(n.exitCode=k.exitCode,n.stdoutTail=M(k.stdout),n.stderrTail=M(k.stderr),n.completedAt=q(e.dependencies.now),k.exitCode!==0)return n.status="failed",n.summary=k.stderr||k.stdout||`Rollback reconciliation exited with ${k.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision={reason:`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,options:["manual-repair","cancel"]},j(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",j(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,j(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 rt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ta(r,e.transactionId);try{let o=await Z({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(ea(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision={reason:"The compiled repair plan changed after approval. Create and approve a fresh transaction.",options:["cancel"]},j(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let s=await Pe(r,e.transactionId);if(S(J(s))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision={reason:"Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",options:["cancel"]},j(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let i=(await Re({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(w=>w.status==="failed");if(i)return o.approval.status="expired",o.state="decision-required",o.decision={reason:`${i.message} The approved plan cannot execute against a changed toolchain.`,options:["manual-repair","cancel"]},j(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 te({workspacePath:r,transaction:o,dependencies:a}),o}let g=new Map(de(s)?s.changes.map(w=>[`proposal:${w.id}`,{kind:"proposal",change:w}]):s.actions.map(w=>[`action:${w.id}`,{kind:"canonical",action:w}]));try{await ra({workspacePath:r,transaction:o});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision={reason:w instanceof Error?w.message:String(w),options:["cancel"]},j(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await x(r,o,a.now),o}let n=o.stages.find(w=>w.id==="target-precondition");if(!n)return o.approval.status="expired",o.state="decision-required",o.decision={reason:"The approved plan has no exact target precondition. Create and approve a fresh transaction.",options:["cancel"]},await x(r,o,a.now),o;if(!await Ke({workspacePath:r,transaction:o,stage:n,actions:g,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision={reason:`Target precondition failed before checkpoint: ${n.summary}`,options:["cancel"]},j(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await x(r,o,a.now),o;try{await Sa({workspacePath:r,transaction:o,now:a.now});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision={reason:w instanceof Error?w.message:String(w),options:["cancel"]},j(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 w of o.stages.filter(l=>l.id!=="target-precondition"&&l.id!=="canonical-verify"&&l.kind!=="rollback"))if(!await Ke({workspacePath:r,transaction:o,stage:w,actions:g,dependencies:a})&&w.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:`Required stage ${w.id} failed: ${w.summary}`,options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await x(r,o,a.now),o.policy.autoRollback&&await te({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let u=o.stages.find(w=>w.id==="canonical-verify");if(!u)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:"The approved plan has no canonical verification stage.",options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await x(r,o,a.now),o.policy.autoRollback&&await te({workspacePath:r,transaction:o,dependencies:a}),o;u.status="running",u.startedAt=q(a.now),j(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:u.id,status:"running",now:a.now}),await x(r,o,a.now);let m;try{m=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(w){m={status:"failed",exitCode:1,artifactPath:a$2.intelligenceRun},u.stderrTail=M(w instanceof Error?w.message:String(w));}let P=m.status==="passed"&&m.exitCode===0?"passed":m.status==="failed"||m.exitCode===1?"failed":"blocked",I=await Ta({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:P}),W=I.status==="passed"&&P!=="failed";return u.status=W?"passed":"failed",u.completedAt=q(a.now),u.exitCode=m.exitCode,u.summary=W&&P==="passed"?"Selected repair target and canonical workspace verification passed.":W?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":I.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${P}.`,o.verification={status:W?"passed":"failed",targetStatus:I.status,workspaceStatus:P,remainingActionIds:I.remainingActionIds,artifact:a$2.intelligenceRun,exitCode:m.exitCode,summary:u.summary},j(o,"verification",u.summary,{stageId:u.id,status:u.status,now:a.now}),W?(o.state="closed",delete o.decision,j(o,"closed",u.summary,{status:"passed",now:a.now}),await x(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision={reason:u.summary,options:o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await x(r,o,a.now),o.policy.autoRollback&&await te({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Da(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ta(r,e.transactionId);try{let o=await Z({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 te({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ot(e,a={}){let r=await Z(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,j(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await x(e.workspacePath,r,a.now),r}async function st(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Z({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 Da({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,j(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 Pe(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,j(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 s={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(de(o))return $a({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return Ea({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function it(e){let a=c$1.join(e,ve,"transactions"),r=await h.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>Z({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}export{tt as approveWorkspaceRepair,ot as cancelWorkspaceRepair,st as decideWorkspaceRepair,Ca as exactCardProducerArgs,rt as executeWorkspaceRepair,at as inspectWorkspaceRepairCapabilities,it as listWorkspaceRepairTransactions,Ea as planWorkspaceRepair,$a as planWorkspaceRepairProposal,Z as readWorkspaceRepairTransaction,Da as rollbackWorkspaceRepair};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{a as runWorkspaceStage}from'./chunk-BQ24743S.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-WD2XDMGB.js';
|
|
File without changes
|