workspai 0.54.0 → 0.55.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/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/studio-card-repair-capabilities.v1.json +65 -1
- package/contracts/workspace-intelligence/workspace-repair-proposal.v1.json +8 -0
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +1 -0
- package/contracts/workspace-repair-capabilities.v1.json +56 -0
- package/dist/{artifact-remediation-plan-A2PRCUNA.js → artifact-remediation-plan-O3YIULQN.js} +1 -1
- package/dist/autopilot-release-EZXOGAVE.js +1 -0
- package/dist/chunk-4GPKQFPY.js +1 -0
- package/dist/chunk-B5AY55A5.js +1 -0
- package/dist/chunk-CEIJIFY7.js +88 -0
- package/dist/{chunk-2FJW6GSW.js → chunk-HUPLAFZQ.js} +1 -1
- package/dist/{chunk-BPACED27.js → chunk-KJYLCZRI.js} +1 -1
- package/dist/{chunk-OLX6LX77.js → chunk-NWQ5VWUW.js} +3 -3
- package/dist/chunk-TEHQ7XKK.js +3 -0
- package/dist/{chunk-3GRKUP5W.js → chunk-W3HXTCSY.js} +6 -6
- package/dist/{chunk-HRN5J6PW.js → chunk-WSAFBPS5.js} +1 -1
- package/dist/{create-R6A7EHQZ.js → create-3NSOY7CA.js} +1 -1
- package/dist/{doctor-HJ3O7SAO.js → doctor-UEFFNAUD.js} +1 -1
- package/dist/index.js +147 -147
- package/dist/{pipeline-TDQK5QYQ.js → pipeline-ZYKDWUKK.js} +1 -1
- package/dist/{pythonRapidkitExec-YR7P5LWG.js → pythonRapidkitExec-4YTAMLBD.js} +1 -1
- package/dist/{verified-goal-S2PEBJUV.js → verified-goal-PE2PGAHF.js} +1 -1
- package/dist/{workspace-B53XH35L.js → workspace-C4UETGY7.js} +1 -1
- package/dist/{workspace-foundation-FFNCK5ZD.js → workspace-foundation-3EVAQ5X6.js} +1 -1
- package/dist/{workspace-intelligence-runner-EQFLRVRL.js → workspace-intelligence-runner-GLC666ER.js} +1 -1
- package/dist/{workspace-onboarding-2B7CYZ5H.js → workspace-onboarding-5KO7Z7AD.js} +1 -1
- package/dist/workspace-repair-engine-NMKOWUQP.js +3 -0
- package/dist/workspace-run-2DEVJOVH.js +1 -0
- package/docs/ci-workflows.md +1 -1
- package/docs/workspace-repair-engine.md +42 -2
- package/package.json +3 -3
- package/dist/autopilot-release-63XHNGR6.js +0 -1
- package/dist/chunk-4HTSZGEU.js +0 -88
- package/dist/chunk-I5CGTCP5.js +0 -1
- package/dist/chunk-IQQWQ3II.js +0 -3
- package/dist/chunk-ZLYEYHMH.js +0 -1
- package/dist/workspace-repair-engine-OZXOXVVV.js +0 -3
- package/dist/workspace-run-VPXRRHDK.js +0 -1
- /package/dist/{chunk-3LVJBH7V.js → chunk-BQ24743S.js} +0 -0
package/dist/chunk-I5CGTCP5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {b,a,c as c$1}from'./chunk-44VJHNZB.js';var c=b.repairTransaction,l=a.repairTransaction,d=c$1.repairTransaction;var g="workspai.workspace-repair-proposal.v1",m="contracts/workspace-intelligence/workspace-repair-proposal.v1.json";var o="workspai.workspace-repair-capabilities.v1",s=[{id:"node",ecosystem:"JavaScript / TypeScript",manifests:["package.json"],lockfiles:["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],packageManagers:["npm","pnpm","yarn","bun"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["selected package manager"]},{id:"python",ecosystem:"Python",manifests:["pyproject.toml","requirements.txt"],lockfiles:["uv.lock","poetry.lock","requirements.txt"],packageManagers:["uv","poetry","pip"],support:"conditional",stages:{reconcile:"conditional",audit:"conditional",test:"conditional",build:"declared"},requiredToolFamilies:["isolated Python","selected environment manager","pip-audit or governed Doctor audit"],limitation:"A bounded isolated environment and an installed audit surface are required."},{id:"go",ecosystem:"Go",manifests:["go.mod"],lockfiles:["go.sum"],packageManagers:["go modules"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["go","govulncheck"],limitation:"govulncheck must be installed; the engine never fetches an unreviewed tool."},{id:"rust",ecosystem:"Rust",manifests:["Cargo.toml"],lockfiles:["Cargo.lock"],packageManagers:["cargo"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["cargo","cargo-audit"],limitation:"The cargo-audit subcommand must already be installed."},{id:"php-composer",ecosystem:"PHP",manifests:["composer.json"],lockfiles:["composer.lock"],packageManagers:["composer"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["composer"]},{id:"ruby-bundler",ecosystem:"Ruby",manifests:["Gemfile"],lockfiles:["Gemfile.lock"],packageManagers:["bundler"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"declared",build:"declared"},requiredToolFamilies:["bundle","bundle-audit"],limitation:"bundle-audit and the declared Rake tasks must already exist."},{id:"elixir-mix",ecosystem:"Elixir",manifests:["mix.exs"],lockfiles:["mix.lock"],packageManagers:["mix"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mix","Hex audit task"],limitation:"The project must expose the Hex audit task used by its dependency policy."},{id:"deno",ecosystem:"Deno",manifests:["deno.json","deno.jsonc"],lockfiles:["deno.lock"],packageManagers:["deno"],support:"full",stages:{reconcile:"native",audit:"native",test:"declared",build:"declared"},requiredToolFamilies:["deno"]},{id:"dotnet",ecosystem:".NET",manifests:["*.sln","*.csproj","*.fsproj","*.vbproj"],lockfiles:["Directory.Packages.props","packages.lock.json"],packageManagers:["NuGet / dotnet"],support:"full",stages:{reconcile:"native",audit:"native",test:"native",build:"native"},requiredToolFamilies:["dotnet"]},{id:"jvm-maven",ecosystem:"JVM / Maven",manifests:["pom.xml"],lockfiles:[],packageManagers:["Maven Wrapper","Maven"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["mvnw or mvn","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"jvm-gradle",ecosystem:"JVM / Gradle",manifests:["build.gradle.kts","build.gradle"],lockfiles:["gradle.lockfile","gradle/libs.versions.toml"],packageManagers:["Gradle Wrapper","Gradle"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["gradlew or gradle","governed Doctor audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."},{id:"clojure",ecosystem:"Clojure",manifests:["deps.edn","project.clj"],lockfiles:[],packageManagers:["Clojure CLI","Leiningen"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"conditional",build:"conditional"},requiredToolFamilies:["clojure or lein","governed project audit"],limitation:"Tests and builds run only when the selected Clojure project surface declares a deterministic entrypoint."},{id:"scala-sbt",ecosystem:"Scala / sbt",manifests:["build.sbt"],lockfiles:[],packageManagers:["sbt"],support:"conditional",stages:{reconcile:"native",audit:"conditional",test:"native",build:"native"},requiredToolFamilies:["sbt","governed project audit"],limitation:"A project-specific dependency audit command must be declared by Doctor evidence."}];function R(){return {schemaVersion:o,owner:"Workspai CLI",workflow:["plan","preconditions","approval","checkpoint","execute","reconcile","audit","test","build","canonical-verify","close-or-rollback-or-decision"],invariants:{multiAdapterProjects:true,missingTools:"decision-required",unsupportedEcosystems:"decision-required",silentFallbackToModelExecution:false,approvalBoundToPlanHash:true,canonicalVerificationRequired:true,rollbackConflictDetection:true},adapters:s}}export{c as a,l as b,d as c,g as d,m as e,o as f,s as g,R as h};
|
package/dist/chunk-IQQWQ3II.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-UFOCUHG3.js';import {a as a$1}from'./chunk-5XDPQ3CB.js';import {a,e,b}from'./chunk-WIO6L24E.js';import {e as e$1,d}from'./chunk-44VJHNZB.js';import w from'path';import {existsSync}from'fs';import F from'fs-extra';var L=[{artifactKind:"bootstrap-compliance",cardId:"bootstrap",fileNames:["bootstrap-compliance.latest.json"]},{artifactKind:"doctor-workspace",cardId:"doctor",fileNames:["doctor-remediation-plan-last-run.json","doctor-last-run.json"]},{artifactKind:"analyze",cardId:"analyze",fileNames:["analyze-last-run.json"]},{artifactKind:"readiness",cardId:"readiness",fileNames:["release-readiness-last-run.json"]},{artifactKind:"pipeline",cardId:"pipeline",fileNames:["pipeline-last-run.json"]},{artifactKind:"workspace-run",cardId:"workspaceRun",fileNames:["workspace-run-last.json"]},{artifactKind:"workspace-verify",cardId:"workspaceVerify",fileNames:["workspace-verify-last-run.json"]}];function u(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function k(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function v(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))]}function x(e,t,o){return o?t:w.relative(e,t).split(w.sep).join("/")}function q(e){let t=e?.trim()||"npx workspai bootstrap";if(!/(?:^|\s)--ci(?:\s|$)/.test(t)&&/(?:^|\s)--json(?:\s|$)/.test(t))return t.replace(/(?:^|\s)--json(?:\s|$)/,n=>{let r=n.startsWith(" ")?" ":"",a=n.endsWith(" ")?" ":"";return `${r}--ci --json${a}`}).trim();let o=/(?:^|\s)--ci(?:\s|$)/.test(t)?t:`${t} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(o)?o:`${o} --json`}function W(e){return `${JSON.stringify({schemaVersion:d.compatibilityMatrix.schemaVersion,generatedAt:e,source:"workspai workspace remediation-plan",runtimes:{},notes:["Minimal enterprise baseline. Add runtime and toolchain entries as governance matures."]},null,2)}
|
|
2
|
-
`}function J(e){return `${JSON.stringify({schema_version:"1.0",enabled:false,strategy:"on-demand",artifacts:[],created_at:e,note:"Minimal enterprise baseline. Set enabled: true and add artifact entries to activate mirroring."},null,2)}
|
|
3
|
-
`}function U(e){let t=e.payload,o=k(t.blockers),n=k(t.blockingReasons),r=k(t.failures),a=k(t.reasons),d=k(t.policyViolations),s=u(t.summary),l=k(s?.blockers);if(e.artifactKind==="analyze"){let c=(Array.isArray(t.findings)?t.findings:[]).map(i=>u(i)).filter(i=>!!i).map(i=>String(i.message??i.title??i.id??"").trim()).filter(Boolean);return v([...o,...c,...n])}if(e.artifactKind==="workspace-run"){let g=u(t.stages),c=Object.entries(g??{}).flatMap(([i,p])=>{let b=u(p);return (Array.isArray(b?.projects)?b.projects:[]).map(f=>u(f)).filter(f=>!!f).filter(f=>f.status==="failed"||f.ok===false).map(f=>`${i}: ${String(f.project??f.name??"project")} failed`)});return v([...o,...c,...n])}return v([...o,...n,...r,...a,...d,...l])}function A(e){return {id:e.id,artifactKind:e.artifactKind,cardId:e.cardId,title:e.title,order:e.order,phase:e.phase,scope:e.scope??"workspace",...e.projectName?{projectName:e.projectName}:{},...e.projectPath?{projectPath:e.projectPath}:{},...e.sourceStepId?{sourceStepId:e.sourceStepId}:{},...e.dependsOn?{dependsOn:e.dependsOn}:{},...e.strategy?{strategy:structuredClone(e.strategy)}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},status:e.status??"ready",mode:e.mode,risk:e.risk,requiresApproval:true,blocker:e.blocker,summary:e.summary,...e.command?{command:e.command}:{},...e.invocation?{invocation:structuredClone(e.invocation)}:{},verifyCommand:e.verifyCommand,cwd:e.cwd??"workspace",files:e.files??[],...e.operation?{operation:e.operation}:{},rollback:e.rollback??(e.operation?{available:true,strategy:"idempotent"}:{available:false,strategy:"none"}),notes:e.notes??[]}}function H(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((o,n)=>{let r=u(o),a=typeof r?.id=="string"?r.id.trim():"",d=typeof r?.projectName=="string"?r.projectName.trim():"",s=typeof r?.projectPath=="string"?r.projectPath.trim():"",l=typeof r?.originalCommand=="string"?r.originalCommand.trim():"";if(!r||!a||!d||!s)return [];let g=u(r.studioStatus),c=g?.state==="ready"||g?.state==="review-required"||g?.state==="blocked"||g?.state==="guidance-only"?g.state:"guidance-only",i=r.risk==="safe"||r.risk==="guarded"||r.risk==="invasive"?r.risk:"guarded",p=u(r.preview),b=x(e.workspacePath,s,e.includeAbsolutePaths),h=_({capability:{...r,command:l},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),f=B({capability:r,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),j=r.executableInCurrentEnvironment===true&&!!h,R=V({strategy:r.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),m=u(r.transaction),y=m?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(m):void 0;return y&&(y.projectPath=b),[A({id:`doctor.${a}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof p?.title=="string"&&p.title.trim()?p.title.trim():`Repair ${d}`,order:e.startOrder+n,phase:typeof r.phase=="string"?r.phase:"doctor-remediation",blocker:typeof p?.summary=="string"&&p.summary.trim()?p.summary.trim():`Doctor remediation is pending for ${d}.`,summary:typeof p?.summary=="string"&&p.summary.trim()?p.summary.trim():`Execute the CLI-authored Doctor step for ${d}.`,mode:j?"run-command":"manual-guidance",risk:i,status:c,...j&&h?{command:h}:{},...j&&f?{invocation:f}:{},verifyCommand:typeof r.verifyCommand=="string"&&r.verifyCommand.trim()?r.verifyCommand.trim():"npx workspai doctor project --json",files:k(r.files).map(P=>{let S=w.isAbsolute(P)?P:w.resolve(s,P);return x(e.workspacePath,S,e.includeAbsolutePaths)}),notes:[`Source Doctor step: ${a}`,...typeof g?.reason=="string"?[g.reason]:[]],scope:"project",projectName:d,projectPath:b,sourceStepId:a,dependsOn:k(r.dependsOn).map(P=>`doctor.${P}`),strategy:R,transaction:y,cwd:"project",...u(r.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function _(e){let t=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&t)return t;let o=Z({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(o)return a$2(o);let n=u(e.capability.invocation),r=typeof n?.executable=="string"?n.executable.trim():"",a=k(n?.args);if(r)return [r,...a].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!t)return;let d=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(`^cd\\s+["']?${d}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function B(e){let t=u(e.capability.invocation),o=typeof t?.executable=="string"?t.executable.trim():"",n=k(t?.args);if(!(!o||n.length!==(Array.isArray(t?.args)?t.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:o,args:n}}function Z(e){let t=u(e.operation);if(!t||typeof t.type!="string")return;let o=structuredClone(t);for(let n of ["path","sourcePath"]){let r=o[n];if(typeof r!="string")continue;let a=w.isAbsolute(r)?w.relative(e.absoluteProjectPath,r):r;if(!a||a===".."||a.startsWith(`..${w.sep}`)||w.isAbsolute(a))return;o[n]=a.split(w.sep).join("/");}return o}function V(e){if(!Array.isArray(e.strategy))return;let t=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let o of t)o.invocation&&(o.invocation.cwd=".");return t}function G(e){let t=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],o=new Set,n=[];for(let r of t){let a=u(r);if(!a)continue;let d=typeof a.name=="string"?a.name.trim():"",s=typeof a.path=="string"?a.path.trim():"";if(!d||!s)continue;let l=Array.isArray(a.repairCapabilities)?a.repairCapabilities:Array.isArray(a.probes)?a.probes.map(c=>u(c)?.repairCapability).filter(c=>c!==void 0):[],g=new Map;for(let c of Array.isArray(a.probes)?a.probes:[]){let i=u(c),p=u(i?.repairCapability),b=typeof p?.id=="string"?p.id.trim():"";b&&g.set(b,i?.status==="fail"?"blocking":"advisory");}for(let c of l){let i=u(c),p=typeof i?.id=="string"?i.id.trim():"";if(!i||!p)continue;let b=`${d}:${p}`;if(o.has(b))continue;o.add(b);let h=i.risk==="safe"||i.risk==="guarded"||i.risk==="invasive"?i.risk:"guarded",f=_({capability:i,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),j=B({capability:i,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),R=i.status==="available"&&!!f,m=u(i.transaction),y=m?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(m):void 0,P=g.get(p)??(y?"blocking":"advisory");y&&(y.projectPath=x(e.workspacePath,s,e.includeAbsolutePaths));let S=V({strategy:i.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),O=k(i.files).map(I=>x(e.workspacePath,I,e.includeAbsolutePaths)),C=f?n.find(I=>I.projectName===d&&I.command===f&&I.cwd==="project"):void 0;if(C){C.files=v([...C.files,...O]),C.notes=v([...C.notes,`Also satisfies Doctor capability: ${p}`]);continue}n.push(A({id:`doctor.${d}.${p}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof i.title=="string"&&i.title.trim()?i.title.trim():`Repair ${d}`,order:e.startOrder+n.length,phase:y?"dependency-remediation":"doctor-remediation",blocker:typeof i.reason=="string"&&i.reason.trim()?i.reason.trim():`Doctor remediation is pending for ${d}.`,summary:typeof i.reason=="string"&&i.reason.trim()?i.reason.trim():`Execute the Doctor-authored repair capability for ${d}.`,mode:R?i.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:h,status:R?"ready":i.status==="manual"?"guidance-only":"blocked",...f?{command:f}:{},...j?{invocation:j}:{},verifyCommand:typeof i.verifyCommand=="string"&&i.verifyCommand.trim()?i.verifyCommand.trim():"npx workspai doctor project --json",files:O,notes:[`Source Doctor capability: ${p}`,`Doctor finding status: ${P}`,...k(i.limitations)],scope:"project",projectName:d,projectPath:x(e.workspacePath,s,e.includeAbsolutePaths),sourceStepId:p,strategy:S,transaction:y,cwd:"project",...i.operation?{rollback:{available:true,strategy:"manual"}}:{}}));}}return n}function Q(e){let t=[],o=q("npx workspai bootstrap --json");for(let n of e.blockers)n.includes("profile.enterprise.ci")&&t.push(A({id:"bootstrap.enterprise-ci",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Run bootstrap in deterministic CI mode",order:10,phase:"bootstrap-preflight",blocker:n,summary:"Enterprise bootstrap compliance requires --ci for deterministic execution.",mode:"run-command",risk:"safe",command:o,verifyCommand:o})),n.includes("profile.enterprise.compatibility-matrix")&&t.push(A({id:"bootstrap.compatibility-matrix",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise compatibility matrix baseline",order:20,phase:"bootstrap-config",blocker:n,summary:"Create the missing compatibility matrix baseline without overwriting user data.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[e$1.compatibilityMatrix],operation:{type:"file-create",path:e$1.compatibilityMatrix,content:W(e.generatedAt),overwrite:false}})),n.includes("profile.enterprise.mirror-config")&&t.push(A({id:"bootstrap.mirror-config",artifactKind:"bootstrap-compliance",cardId:"bootstrap",title:"Create enterprise mirror config baseline",order:30,phase:"bootstrap-config",blocker:n,summary:"Create the missing mirror configuration baseline without enabling mirroring.",mode:"edit-file",risk:"safe",verifyCommand:o,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:J(e.generatedAt),overwrite:false}}));return t}function X(e){let t=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],o=[],n=new Map;for(let r of t){let a=u(r),d=u(a?.command),s=typeof a?.id=="string"?a.id.trim():"",l=typeof a?.project=="string"?a.project.trim():"",g=typeof a?.status=="string"?a.status:"",c=typeof d?.display=="string"?d.display.trim():"",i=a?.required===true;if(!s.startsWith("project.")||!l||!i||g!=="fail"&&g!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(c))continue;let p=s.split(".").at(-1)??"stage",b=`workspaceVerify.${s}`,h=n.get(l),f=/(?:^|\s)--no-gates(?:\s|$)/.test(c)?c:`${c} --no-gates`;o.push(A({id:b,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof a.label=="string"&&a.label.trim()?a.label.trim():`Run ${p} for ${l}`,order:e.startOrder+o.length,phase:"fleet-run",blocker:typeof a.message=="string"&&a.message.trim()?a.message.trim():`${p} evidence is not current for ${l}.`,summary:`Produce fresh ${p} evidence for ${l} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:p==="start"?"guarded":"safe",status:"ready",command:f,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:l,projectPath:l,sourceStepId:s,...h?{dependsOn:[h]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),n.set(l,b);}return o}function Y(e){let t=v(e.blockers.flatMap(n=>{let r=n.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return r?.[1]?r[1].split(",").map(a=>a.trim().toLowerCase()).filter(a=>/^(python|node|go|java|dotnet|rust|php)$/.test(a)):[]})),o=[];for(let n of t){let r=`readiness.toolchain.${n}.setup`,a=e.blockers.find(d=>d.toLowerCase().includes(`(${n})`))??`The ${n} runtime is not pinned in the canonical workspace toolchain.`;o.push(A({id:r,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${n} in the workspace toolchain`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:a,summary:`Detect and persist the current ${n} runtime in the canonical workspace toolchain lock.`,mode:"run-command",risk:"safe",command:`npx workspai setup ${n} --json`,verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Run from the workspace root so the canonical toolchain.lock is updated."]})),o.push(A({id:`readiness.toolchain.${n}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${n} workspace foundation`,order:e.startOrder+o.length,phase:"toolchain-reconciliation",blocker:`The ${n} runtime pin must be reconciled with the workspace foundation.`,summary:"Refresh the workspace foundation after the runtime pin is written.",mode:"run-command",risk:"guarded",command:"npx workspai bootstrap --ci --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",dependsOn:[r]}));}return o}function ee(e){if(e.report.artifactKind==="readiness"&&/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(e.blocker))return A({id:`${e.report.cardId}.doctor-owner.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:"Resolve dependency vulnerability through Doctor",order:e.order,phase:"dependency-remediation",blocker:e.blocker,summary:"Release Readiness is the aggregate gate; use the project-scoped Doctor remediation capability that owns this dependency failure.",mode:"verify-before-fix",risk:"guarded",status:"review-required",command:"npx workspai doctor workspace --plan --json",verifyCommand:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",notes:["Read doctor-remediation-plan-last-run.json and execute the matching surface-security-hygiene capability before rerunning Readiness.","Do not treat a Readiness refresh as remediation for a source dependency vulnerability."]});let o={analyze:{title:"Refresh analyze evidence",phase:"analysis",command:"npx workspai analyze --strict --json",verify:"npx workspai analyze --strict --json"},readiness:{title:"Refresh release readiness",phase:"release-readiness",command:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json",verify:e.ciMode?"npx workspai readiness --strict --json":"npx workspai readiness --json"},pipeline:{title:"Rerun governance pipeline",phase:"governance-pipeline",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"},"workspace-run":{title:"Rerun failed workspace stage",phase:"fleet-run",command:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json",verify:e.ciMode?"npx workspai workspace run test --strict --json":"npx workspai workspace run test --json"},"workspace-verify":{title:"Refresh workspace verify gate",phase:"verification",command:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",verify:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json"},"doctor-workspace":{title:"Use Doctor remediation plan",phase:"doctor-remediation",command:"npx workspai doctor workspace --plan --json",verify:"npx workspai doctor workspace --json"}}[e.report.artifactKind]??{title:"Refresh artifact evidence",phase:"evidence-refresh",command:"npx workspai pipeline --json --strict",verify:"npx workspai pipeline --json --strict"};return A({id:`${e.report.cardId}.refresh.${e.order}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:o.title,order:e.order,phase:o.phase,blocker:e.blocker,summary:"No deterministic file operation is available for this artifact yet; refresh the evidence and continue with the card-specific plan.",mode:e.report.artifactKind==="doctor-workspace"?"verify-before-fix":"run-command",risk:"guarded",status:e.report.artifactKind==="doctor-workspace"?"review-required":"ready",command:o.command,verifyCommand:o.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function te(e){let t=[a(e,".workspai/reports"),b(e,".workspai/reports")],o=[],n=new Set;for(let r of L)for(let a of r.fileNames){let d=(await Promise.all(t.map(s=>w.join(s,a)))).find(s=>existsSync(s));if(!(!d||n.has(`${r.artifactKind}:${a}`))){n.add(`${r.artifactKind}:${a}`);try{let s=await F.readJSON(d),l=u(s);if(!l)continue;o.push({artifactKind:r.artifactKind,cardId:r.cardId,fileName:a,absolutePath:d,payload:l});break}catch{o.push({artifactKind:r.artifactKind,cardId:r.cardId,fileName:a,absolutePath:d,payload:{blockers:[`${r.artifactKind}: report exists but could not be parsed.`]}});break}}}return o}async function le(e){let t=w.resolve(e.workspacePath),o=e.includeAbsolutePaths===true,n=e.ciMode===true,r=new Date().toISOString(),a$2=a(t,".workspai/reports"),d=await te(t),s=[],l=1;for(let c of d){if(c.artifactKind==="doctor-workspace"){let m=Array.isArray(c.payload.steps)?H({report:c,workspacePath:t,includeAbsolutePaths:o,startOrder:l}):G({report:c,workspacePath:t,includeAbsolutePaths:o,startOrder:l});s.push(...m),l+=m.length;continue}let i=U(c);if(i.length===0)continue;if(c.artifactKind==="bootstrap-compliance"){s.push(...Q({blockers:i,generatedAt:r})),l=s.length+1;continue}if(c.artifactKind==="workspace-verify"){let m=X({report:c,startOrder:l,ciMode:n});if(m.length>0){s.push(...m),l+=m.length;continue}}if(c.artifactKind==="readiness"){let m=Y({report:c,blockers:i,startOrder:l,ciMode:n});if(m.length>0){s.push(...m),l+=m.length;continue}}let p=s.some(m=>m.transaction?.kind==="dependency-security"),b=c.artifactKind==="readiness"&&i.some(m=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(m));if(p&&b)continue;let h=i[0],f=ee({report:c,blocker:h,order:l,ciMode:n}),R={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[c.cardId];if(c.cardId==="pipeline"){let m=["doctor","analyze","readiness"].find(y=>h.toLowerCase().includes(y));m&&(R=new Set([m]));}if(R){let m=s.filter(y=>R.has(y.cardId)&&y.risk!=="invasive"&&y.status!=="blocked"&&y.status!=="guidance-only").map(y=>y.id);m.length>0&&(f.dependsOn=v([...f.dependsOn??[],...m]),f.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}i.length>1&&f.notes.push(...i.slice(1,8).map(m=>`Related blocker: ${m}`)),s.push(f),l+=1;}let g={safe:s.filter(c=>c.risk==="safe").length,guarded:s.filter(c=>c.risk==="guarded").length,invasive:s.filter(c=>c.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:r,workspace:{name:w.basename(t),...o?{path:t}:{}},source:{command:"workspace remediation-plan",reportsDir:x(t,a$2,o),includeAbsolutePaths:o,ciMode:n},summary:{artifactsScanned:d.length,cardsCovered:v(s.map(c=>c.cardId)).length,totalActions:s.length,executableActions:s.filter(c=>c.status==="ready").length,risk:g},actions:s}}async function me(e$2,t){return e(t,e$1.artifactRemediationPlan,e$2)}export{le as a,me as b};
|
package/dist/chunk-ZLYEYHMH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {b as b$1,c as c$1}from'./chunk-WZA5ISAQ.js';import {a as a$2}from'./chunk-KVUYAYTY.js';import {q as q$1}from'./chunk-4HTSZGEU.js';import {a as a$3}from'./chunk-RMXXK64P.js';import {g}from'./chunk-HRN5J6PW.js';import {j,e as e$1}from'./chunk-GDU7VP6G.js';import {l as l$2}from'./chunk-OUBBBC7T.js';import {c,d}from'./chunk-P7K5RHJC.js';import {a as a$1}from'./chunk-RA24WQLF.js';import {f,g as g$1,h as h$2}from'./chunk-XVRJVKOX.js';import {k as k$1,l as l$1,h as h$1,m as m$1,n,p as p$1,q}from'./chunk-S7Z4DP3P.js';import {m,p,s}from'./chunk-7AR5PDLD.js';import {o,r as r$1,s as s$1}from'./chunk-MQ73VS4E.js';import {e}from'./chunk-WIO6L24E.js';import {b as b$2}from'./chunk-BYVTHIC3.js';import {a,b,k,l,j as j$1,i}from'./chunk-44VJHNZB.js';import {d as d$1}from'./chunk-VRW6KXNK.js';import oe from'path';import ce from'fs-extra';function r(t,s){if(!t)throw new Error(`Workspace Intelligence run semantic violation: ${s}`)}function ie(t,s){return t.length===s.length&&t.every((u,d)=>u===s[d])}function ne(t){b$2(a.intelligenceRun,t,"Workspace Intelligence run report"),r(t.chainSchemaVersion===a$1,`chainSchemaVersion must be ${a$1}`),r(t.artifactPath===a.intelligenceRun,`artifactPath must be ${a.intelligenceRun}`),r(t.preflight.length===j$1.length,`preflight must contain exactly ${j$1.length} entries`);for(let[o,i]of j$1.entries()){let a=t.preflight[o];r(a?.id===i,`preflight[${o}].id must be ${i}`),r(ie(a.artifacts,k[i]),`${i} preflight artifacts must match the runtime registry`),i==="sync"?r(a.status==="passed"&&a.result==="synchronized"||a.status==="failed"&&a.result==="failed","sync preflight status and result are incoherent"):r(a.status==="passed"&&(a.result==="created"||a.result==="reused")||a.status==="failed"&&a.result==="failed"||a.status==="skipped"&&a.result==="skipped","baseline preflight status and result are incoherent");}let s=t.preflight[1];r(t.baselineCreated===(s?.result==="created"),"baselineCreated must match the baseline preflight result"),r(t.stages.length===i.length,`stages must contain exactly ${i.length} canonical steps`);let u=t.preflight[0],d=u?.status==="failed";for(let[o,i$1]of i.entries()){let a=t.stages[o];r(a?.id===i$1,`stages[${o}].id must be ${i$1}`),r(ie(a.artifacts,l[i$1].produces),`${i$1} artifacts must match the runtime registry`),d&&r(a.status==="skipped",`${i$1} must be skipped after a hard failure`),a.status==="passed"?r(a.exitCode===0,`${i$1} passed stage must have exitCode 0`):a.status==="blocked"?r(a.exitCode!==0,`${i$1} blocked stage must have a non-zero exitCode`):a.status==="failed"?(r(a.exitCode===1,`${i$1} failed stage must have exitCode 1`),d=true):(r(a.exitCode===0,`${i$1} skipped stage must have exitCode 0`),r(a.durationMs===0,`${i$1} skipped stage must have durationMs 0`)),o===0&&((u?.status==="failed"||a.status==="failed")&&r(s?.status==="skipped","baseline must be skipped when sync or model fails"),s?.status==="skipped"&&r(u?.status==="failed"||a.status==="failed"||a.status==="skipped","baseline may be skipped only after an upstream failure"),s?.status!=="passed"&&(d=true));}let m=t.preflight.some(o=>o.status==="failed")||t.stages.some(o=>o.status==="failed"),y=t.stages.some(o=>o.status==="blocked"),n=m?"failed":y?"blocked":"passed",f=n==="failed"?1:n==="blocked"?2:0;r(t.status===n,`status must be ${n}`),r(t.exitCode===f,`exitCode must be ${f}`);}var me=a.intelligenceRun,fe=b.intelligenceRun,le=me;function h(t){d$1({action:"intelligence",status:t.status==="started"?"started":t.status==="passed"?"succeeded":t.status==="failed"?"failed":"warn",message:t.message,metadata:{phase:`workspace.intelligence.${t.kind}.${t.id}`,intelligenceMilestoneId:t.id,intelligenceMilestoneKind:t.kind,intelligenceMilestoneStatus:t.status}});}async function He(t){let s$2=oe.resolve(t.workspacePath),u=[],d$1=[],m$2=false,y=async(e,l)=>{let g=[...k[e]];if(m$2){h({id:e,kind:"preflight",status:"skipped",message:`${e} prerequisite skipped after an upstream failure`}),u.push({id:e,status:"skipped",result:"skipped",durationMs:0,artifacts:g,message:"skipped because a required upstream operation failed"});return}let I=Date.now();h({id:e,kind:"preflight",status:"started",message:`${e} prerequisite started`});try{let c=await l();h({id:e,kind:"preflight",status:"passed",message:c.message}),u.push({id:e,status:"passed",result:c.result,durationMs:Date.now()-I,artifacts:g,message:c.message});}catch(c){m$2=true;let k=c instanceof Error?c.message:String(c);h({id:e,kind:"preflight",status:"failed",message:k}),u.push({id:e,status:"failed",result:"failed",durationMs:Date.now()-I,artifacts:g,message:k});}},n$1=async(e,l$1)=>{let g=[...l[e].produces];if(m$2){h({id:e,kind:"stage",status:"skipped",message:`${e} skipped after an upstream failure`}),d$1.push({id:e,status:"skipped",durationMs:0,artifacts:g,exitCode:0,message:"skipped because a required upstream stage failed"});return}let I=Date.now();h({id:e,kind:"stage",status:"started",message:`${e} started`});try{let c=await l$1(),k=c.exitCode??0,x=c.blocked||k!==0?"blocked":"passed";h({id:e,kind:"stage",status:x,message:c.message}),d$1.push({id:e,status:x,durationMs:Date.now()-I,artifacts:g,exitCode:k,message:c.message});}catch(c){m$2=true;let k=c instanceof Error?c.message:String(c);h({id:e,kind:"stage",status:"failed",message:k}),d$1.push({id:e,status:"failed",durationMs:Date.now()-I,artifacts:g,exitCode:1,message:k});}};await y("sync",async()=>{let e=await g(s$2,true),l=await o({workspacePath:s$2});return {result:"synchronized",message:`registry ${e.added.length} added/${e.skipped} existing; contract ${l.contract.projects.length} projects`}});let f$1,o$1=()=>{if(!f$1)throw new Error("canonical workspace model is unavailable");return f$1};await n$1("model",async()=>(f$1={...await p({workspacePath:s$2,includeEvidence:true}),build:m({mode:"full",engineStatus:"disabled"})},await s(f$1,s$2),{message:`${f$1.summary.projectCount} projects modeled`}));let i=oe.join(s$2,a.snapshot),a$4=false;await y("baseline",async()=>{if(!await ce.pathExists(i)){let g=await k$1({workspacePath:s$2,model:o$1()});return await l$1(g,s$2),a$4=true,{result:"created",message:"initial structural baseline created"}}let e=await ce.readJson(i),l=h$1(e);return l?(await l$1(l,s$2),{result:"reused",message:"legacy structural baseline migrated and reused"}):{result:"reused",message:"existing structural baseline reused"}}),await n$1("diff",async()=>{let e=await m$1({workspacePath:s$2,fromPath:a.snapshot,model:o$1()});return await n(e,s$2),{message:e.summary.changed?"workspace changes detected":"no workspace changes"}}),await n$1("impact",async()=>{let e=await p$1({workspacePath:s$2,fromPath:a.diff});return await q(e,s$2),{message:`${e.summary.risk} risk; ${e.summary.affectedProjects} affected`}}),await n$1("doctor-evidence",async()=>{let e=await q$1({workspace:s$2,json:true,quiet:true});return {exitCode:e,blocked:e!==0,message:`doctor exit ${e}`}}),await n$1("contract-evidence",async()=>{let e=await r$1({workspacePath:s$2,strict:true});return await s$1({workspacePath:s$2,result:e}),{exitCode:e.status==="passed"?0:1,blocked:e.status!=="passed",message:`contract ${e.status}`}}),await n$1("analyze-evidence",async()=>{let e=await a$2({workspacePath:s$2,json:true,strict:false});return {blocked:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention",exitCode:e.summary.verdict==="blocked"||t.strict===true&&e.summary.verdict==="needs-attention"?1:0,message:`analyze ${e.summary.verdict} (${e.summary.score}/100)`}}),await n$1("readiness-evidence",async()=>{let e=await a$3({startPath:s$2,writeReport:true,skipVerify:true});return {blocked:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn",exitCode:e.overallStatus==="fail"||t.strict===true&&e.overallStatus==="warn"?1:0,message:`pre-verify readiness ${e.overallStatus}`}}),await n$1("verify",async()=>{let e=await f({workspacePath:s$2,fromImpactPath:a.impact});await g$1(e,s$2);let l=h$2(e,{strict:t.strict===true});return await j(s$2,e$1(e,l.passed)),{blocked:!l.passed,exitCode:l.exitCode,message:`${e.summary.verdict}; gate ${l.passed?"passed":"blocked"}`}}),await n$1("context",async()=>{let e=await c({workspacePath:s$2,model:o$1(),agent:t.agent??"generic",includeEvidence:true});return await d(e,s$2),{message:`context grounded for ${e.agent}`}}),await n$1("agent-sync",async()=>({message:`${(await l$2({workspacePath:s$2,agent:t.agent??"generic",write:true,refreshContext:false,strict:false,preset:"enterprise"})).writtenFiles.length} grounding files written`})),await n$1("explain",async()=>{let e=await b$1({workspacePath:s$2,target:{kind:"release-blocked"}});return await c$1(e,s$2),{message:e.summary}});let de=d$1.some(e=>e.status==="blocked"),P=m$2?"failed":de?"blocked":"passed",ue=m$2?1:P==="blocked"?2:0,R={schemaVersion:fe,chainSchemaVersion:a$1,generatedAt:new Date().toISOString(),workspacePath:s$2,baselineCreated:a$4,preflight:u,status:P,exitCode:ue,stages:d$1,artifactPath:le};return ne(R),await e(s$2,le,R),R}export{me as a,fe as b,He as c};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {c as c$2}from'./chunk-ZLYEYHMH.js';import {a as a$2}from'./chunk-IQQWQ3II.js';import {d,h as h$1,i,j,g as g$1,l,m,n}from'./chunk-4HTSZGEU.js';import {a,c,h,b as b$1,e,g,d as d$1}from'./chunk-I5CGTCP5.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a as a$3}from'./chunk-44VJHNZB.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import u from'fs-extra';var he=".workspai/repair",ze="transaction.json",Xe="source-plan.json",Te="checkpoint",Ye="engine.lock",De=5*1024*1024,Ze=25*1024*1024,Qe=25*1024*1024,ea=4*1024*1024,aa=900*1e3,ta=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"]),ra=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"]),_={safe:0,guarded:1,invasive:2},sa=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 S(e){return (e?.()??new Date).toISOString()}function A(e){return createHash("sha256").update(e).digest("hex")}function V(e){return Array.isArray(e)?`[${e.map(V).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${V(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function W(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 u.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await u.pathExists(t);){let i=c$1.dirname(t);if(i===t)return false;t=i;}let s=await u.realpath(t).catch(()=>c$1.resolve(t));return W(r,s)}function q(e,a){let r=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!W(e,r))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,r).split(c$1.sep).join("/")||"."}function J(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,he,"transactions",a)}function ne(e,a){return c$1.join(J(e,a),ze)}function ke(e,a){return c$1.join(J(e,a),Xe)}async function H(e,a){await u.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await u.writeJson(r,a,{spaces:2}),await u.move(r,e,{overwrite:true});}function x(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:S(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function R(e,a,r){a.revision+=1,a.updatedAt=S(r),a$1(a,c,"Workspace repair transaction"),await H(ne(e,a.transactionId),a),await H(c$1.join(e,b$1),a);}async function z(e){let a$2=await u.readJson(ne(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 ge(e,a){return await u.readJson(ke(e,a))}function me(e){return e.schemaVersion===d$1}function ee(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(!W(e,t))throw new Error(`Repair project scope escapes workspace: ${r}`);return t}function b(e){return {cwd:q(e.workspacePath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function pe(e){return u.readFile(e,"utf8").catch(()=>"")}async function oa(e){return u.readJson(e).catch(()=>({}))}function qe(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return b({...e,executable:e.manager,args:a,purpose:e.purpose})}function ia(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(s=>c$1.join(t,`${e}${s}`)))}function Fe(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function Me(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),s=await u.stat(t).catch(()=>{});return Fe(s)}for(let t of ia(r)){let s=await u.stat(t).catch(()=>{});if(Fe(s))return true}return false}async function fe(e){let a=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),r=new Map;for(let s of a)r.set(`${s.cwd}\0${s.executable}`,s);let t=[];for(let s of r.values()){let i=await Me({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});t.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 t}function O(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function w(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 na(e,a,r){let t=r.strategy?.find(s=>s.kind==="verify"&&s.invocation)?.invocation;if(t)return b({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function ca(e){let a=ee(e.workspacePath,e.action),r=q(e.workspacePath,a),t=async l=>u.pathExists(c$1.join(a,l)),s=new Set,i=[],d=[],o=l=>`${r}:${e.adapterId}:${l}`,p=l=>l.forEach(v=>s.add(q(e.workspacePath,c$1.join(a,v)))),n=l=>{i.push(l),l.required&&l.status==="blocked"&&d.push(l.summary);},h=na(e.workspacePath,a,e.action),m=()=>{let l=g.find(v=>v.id===e.adapterId);if(!l)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...s],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(i.filter(v=>v.required&&v.invocation).map(v=>v.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 oa(c$1.join(a,"package.json")),v=l.scripts&&typeof l.scripts=="object"&&!Array.isArray(l.scripts)?l.scripts:{},P=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",C=P==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":P==="pnpm"?"pnpm-lock.yaml":P==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";p(["package.json",C]),n(w({id:o("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${P} manifest, lockfile, and installed tree.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["install"],purpose:"reconcile"})}));let I=b(P==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:P==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:P==="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(w({id:o("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:h??I})),n(typeof v.test=="string"&&v.test.trim()?w({id:o("test"),kind:"test",summary:"Run the declared project test contract.",invocation:qe({workspacePath:e.workspacePath,projectPath:a,manager:P,script:"test",purpose:"test"})}):O(o("test"),"test","No test script is declared.")),n(typeof v.build=="string"&&v.build.trim()?w({id:o("build"),kind:"build",summary:"Run the declared project build contract.",invocation:qe({workspacePath:e.workspacePath,projectPath:a,manager:P,script:"build",purpose:"build"})}):O(o("build"),"build","No build script is declared.")),m()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){p(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let l=process.platform==="win32"?"python":"python3",v=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");await u.pathExists(v)&&(l=v);let P=await t("uv.lock")?b({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):await t("poetry.lock")?b({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&W(e.workspacePath,l)?b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):void 0;n(w({id:o("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:P})),n(w({id:o("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:h}));let C=await pe(c$1.join(a,"pyproject.toml")),I=await t("tests")||/\[tool\.pytest/i.test(C);return n(I?w({id:o("test"),kind:"test",summary:"Run the Python test contract.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","pytest"],purpose:"test"})}):O(o("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(C)?w({id:o("build"),kind:"build",summary:"Build the declared Python package.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["-m","build"],purpose:"build"})}):O(o("build"),"build","No Python build contract is declared.")),m()}let y=[{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 y){if(l.adapterId!==e.adapterId)continue;let v=await t(l.manifest)?l.manifest:l.alternateManifest&&await t(l.alternateManifest)?l.alternateManifest:void 0;if(!v)continue;p(l.files),n(w({id:o("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${v} and its lock/baseline.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l.reconcile[0],args:l.reconcile[1],purpose:"reconcile"})})),n(w({id:o("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:h??(l.audit?b({workspacePath:e.workspacePath,projectPath:a,executable:l.audit[0],args:l.audit[1],purpose:"audit"}):void 0)}));let P=await pe(c$1.join(a,v)),C=l.manifest==="composer.json"||l.adapterId==="deno"?/["']test["']\s*:/.test(P):l.manifest==="Gemfile"?await t("Rakefile"):true,I=l.manifest==="composer.json"||l.manifest==="deno.json"?/["']build["']\s*:/.test(P):l.manifest==="Gemfile"?(await u.readdir(a)).some(T=>T.endsWith(".gemspec")):true;return n(C?w({id:o("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"})}):O(o("test"),"test","No test contract is declared.")),n(I?w({id:o("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"})}):O(o("build"),"build","No build contract is declared.")),m()}let j=await u.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&j.some(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l)))return p(["Directory.Packages.props","packages.lock.json",...j.filter(l=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(l))]),n(w({id:o("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(w({id:o("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:h??b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(w({id:o("test"),kind:"test",summary:"Run .NET tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(w({id:o("build"),kind:"build",summary:"Build the .NET project.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),m();let f=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return p(["pom.xml"]),n(w({id:o("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["dependency:resolve"],purpose:"reconcile"})})),n(w({id:o("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:h})),n(w({id:o("test"),kind:"test",summary:"Run Maven tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["test"],purpose:"test"})})),n(w({id:o("build"),kind:"build",summary:"Build the Maven artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["package","-DskipTests"],purpose:"build"})})),m();let N=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&N){let l=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return p([N,"gradle.lockfile","gradle/libs.versions.toml"]),n(w({id:o("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(w({id:o("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:h})),n(w({id:o("test"),kind:"test",summary:"Run Gradle tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["test"],purpose:"test"})})),n(w({id:o("build"),kind:"build",summary:"Build the Gradle project.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:l,args:["build","-x","test"],purpose:"build"})})),m()}let E=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&E){let l=E==="deps.edn",v=await pe(c$1.join(a,E)),P=l?"clojure":"lein";p([E]),n(w({id:o("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${E} dependency graph.`,invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:P,args:l?["-P"]:["deps"],purpose:"reconcile"})})),n(w({id:o("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:h}));let C=!l||/:test\b/.test(v);return n(C?w({id:o("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:P,args:l?["-M:test"]:["test"],purpose:"test"})}):O(o("test"),"test","No Clojure :test alias is declared.")),n(l?O(o("build"),"build","No portable Clojure CLI build entrypoint is declared."):w({id:o("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),m()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(p(["build.sbt"]),n(w({id:o("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(w({id:o("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:h})),n(w({id:o("test"),kind:"test",summary:"Run sbt tests.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(w({id:o("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:b({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),m()):(d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),n(w({id:o("reconcile"),kind:"reconcile",required:true,summary:d[0]})),m())}async function Oe(e){let a=i=>u.pathExists(c$1.join(e,i)),r=await u.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$|\.sln$/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 s=new Map(g.map((i,d)=>[i.id,d]));return [...new Set(t)].sort((i,d)=>(s.get(i)??999)-(s.get(d)??999))}function da(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 _e(e,a={}){let r=ee(e.workspacePath,e.action),t=q(e.workspacePath,r),s=await Oe(r),i=da(e.action.transaction?.ecosystem),d=i?[i]:s;if(i&&!s.includes(i)){let p=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[w({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:p})],checkpointFiles:[],blockers:[p],adapters:[{adapterId:i,ecosystem:g.find(n=>n.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:p}]}}if(d.length===0){let p=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[w({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:p})],checkpointFiles:[],blockers:[p],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:p}]}}let o={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let p of d){let n=await ca({...e,adapterId:p});o.stages.push(...n.stages),o.checkpointFiles.push(...n.checkpointFiles),o.blockers.push(...n.blockers),o.adapters.push(...n.adapters);}if(o.stages=[...new Map(o.stages.map(p=>[p.id,p])).values()],o.checkpointFiles=[...new Set(o.checkpointFiles)].sort(),o.blockers=[...new Set(o.blockers)],e.action.transaction?.kind==="dependency-materialization"){let p=new Set(e.action.transaction.requiredStages);o.stages=o.stages.filter(n=>n.kind!=="reconcile"&&p.has(n.kind)),o.blockers=o.stages.filter(n=>n.required&&n.status==="blocked").map(n=>n.summary);}for(let p of o.adapters){let n=o.stages.filter(m=>m.id.startsWith(`${p.projectPath}:${p.adapterId}:`)),h=[];p.requiredExecutables=[...new Set(n.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))];for(let m of n)!m.required||!m.invocation||await Me({workspacePath:e.workspacePath,invocation:m.invocation,toolAvailable:a.toolAvailable})||h.push(m.invocation.executable);p.missingExecutables=[...new Set(h)],p.missingExecutables.length>0&&(p.status="partial",p.message=`Required executable(s) unavailable: ${p.missingExecutables.join(", ")}.`);}if(d.length===1){let p=`:${d[0]}:`;for(let n of o.stages)n.id=n.id.replace(p,":");}return o}async function Ba(e={}){let a=h();if(!e.workspacePath&&!e.projectPath)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t=c$1.resolve(r,e.projectPath??".");if(!W(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");return {...a,inspection:{projectPath:q(r,t),detectedAdapters:await Oe(t)}}}function we(e){if(e.command){let a=d(e.command);if(a)return a}if(e.operation?.type==="file-create")return e.operation}async function la(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){for(let d of r.files)a.add(q(e.workspacePath,d));let t=we(r);if(!t)continue;let s=ee(e.workspacePath,r),i="path"in t?t.path:void 0;i&&a.add(q(e.workspacePath,c$1.resolve(s,i)));}return [...a].filter(r=>r!==".").sort()}function pa(e,a){if(!a.invocation)return;let r=ee(e,a);return b({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function be(e){return A(V({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function He(e){return be({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 ie(e,a){let r=[],t=[],s=0;for(let i of a){let d=c$1.resolve(e,i);if(!W(e,d)){t.push(`Checkpoint path escapes workspace: ${i}`);continue}if(!await G(e,d)){t.push(`Checkpoint path resolves through a link outside the workspace: ${i}`);continue}let o=await u.lstat(d).catch(()=>{});if(o?.isSymbolicLink()){t.push(`Checkpoint refuses symbolic link mutation: ${i}`);continue}if(o&&!o.isFile()){t.push(`Checkpoint target is not a regular file: ${i}`);continue}if(o&&o.size>De){t.push(`Checkpoint file exceeds 5 MiB: ${i}`);continue}if(s+=o?.size??0,s>Ze){t.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=o?await u.readFile(d):void 0;r.push({path:i,existed:!!o,beforeHash:p?A(p):null,...o?{mode:o.mode}:{}});}return {entries:r,errors:t}}function Be(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 ua(e){let a=await u.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function ha(e){return ta.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function ka(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;W(e,t);){if((await u.readdir(t).catch(()=>[])).some(ha))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function ga(e,a,r){return r.some(t=>{let s=c$1.resolve(e,t.path);if(!W(a,s))return false;let i=c$1.basename(s);return ra.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function ma(e){let a=q(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 fa(e,a){let r=Ve(a.executable),[t="",s=""]=a.args;if(a.args.some(o=>/^(?:-e|--eval|-c|--command|-command)$/i.test(o)))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(o=>/audit/i.test(o))||i&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||s===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(s.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"&&s==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(o=>/^(?:test|build|check|verify|package)$/i.test(o))||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(s))))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 wa(e){let a=[],r=new Set,t=[],s=[],i=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let o of e.proposal.validation??[]){let p=c$1.resolve(e.workspacePath,o.cwd),n=q(e.workspacePath,p),h=await u.lstat(p).catch(()=>{});if(!h?.isDirectory()||h.isSymbolicLink()||!await G(e.workspacePath,p)){t.push(`Validation ${o.id} requires a real directory inside the workspace.`);continue}if(d&&!W(d,p)){t.push(`Validation ${o.id} escapes the declared project scope.`);continue}if(_[o.risk]>_[e.maxRisk]){t.push(`Validation ${o.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let m=b({workspacePath:e.workspacePath,projectPath:p,executable:o.executable,args:o.args,purpose:o.kind,timeoutMs:o.timeoutMs});try{ve(e.workspacePath,m,e.policy),fa(o,m);}catch(y){t.push(y instanceof Error?y.message:String(y));continue}a.push(w({id:`validation:${o.id}`,kind:o.kind,risk:o.risk,required:o.required,summary:o.summary,invocation:m})),i.add(`${n}:${o.kind}`);}for(let o of e.projectRoots){let p=ma({workspacePath:e.workspacePath,projectPath:o,proposal:e.proposal}),n=await _e({workspacePath:e.workspacePath,action:p},e.dependencies);s.push(...n.adapters);let h=ga(e.workspacePath,o,e.proposal.changes);if(h){for(let y of n.checkpointFiles)r.add(y);t.push(...n.blockers);}let m=q(e.workspacePath,o);for(let y of n.stages)!h&&!["test","build"].includes(y.kind)||i.has(`${m}:${y.kind}`)||a.push(y);}return {stages:[...new Map(a.map(o=>[o.id,o])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(s.map(o=>[`${o.projectPath}:${o.adapterId}`,o])).values()]}}async function ba(e,a$3={}){let r=c$1.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),s=t.actions.filter(k=>k.cardId===e.cardId).filter(k=>!e.actionId||k.id===e.actionId).filter(k=>!e.projectName||k.projectName===e.projectName).sort((k,D)=>k.order-D.order||k.id.localeCompare(D.id)),i=s.filter(k=>k.notes.includes("Doctor finding status: blocking")),d=!e.actionId&&i.length>0?i:s,o=e.maxRisk??"guarded",p={maxRisk:o,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},n=[{id:"workspace-root",status:await u.pathExists(c$1.join(r,".workspai-workspace"))||await u.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:d.length>0?"passed":"failed",message:d.length>0?`${d.length} governed action(s) selected.`:"No governed remediation action matches this target."}],h=[],m=[],y=[],j=[],f=new Set(["manual-repair","cancel"]);for(let k of d){let D=we(k),B=pa(r,k);if(_[k.risk]<=_[o]||(j.push(`${k.id} exceeds the approved ${o} risk ceiling.`),f.add(k.risk==="invasive"?"approve-invasive":"approve-guarded")),(k.status==="blocked"||k.status==="guidance-only")&&j.push(`${k.id} is ${k.status}: ${k.blocker}`),!D&&!B&&j.push(`${k.id} has no typed operation or structured invocation.`),B)try{ve(r,B,p);}catch($){let Y=$ instanceof Error?$.message:String($);j.push(Y),/Force-based/.test(Y)&&f.add("allow-force"),/Breaking dependency/.test(Y)&&f.add("allow-breaking");}if(h.push({id:`action:${k.id}`,kind:"repair",status:D||B?"pending":"blocked",required:true,risk:k.risk,summary:k.summary,...B?{invocation:B}:{}}),k.transaction){let $=await _e({workspacePath:r,action:k},a$3);h.push(...$.stages),m.push(...$.checkpointFiles),j.push(...$.blockers),y.push(...$.adapters);}}let N=[...new Map(h.map(k=>[k.id,k])).values()];h.splice(0,h.length,...N),h.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 fe({workspacePath:r,stages:h,toolAvailable:a$3.toolAvailable}));let E=await la({workspacePath:r,actions:d,dependencyFiles:m}),l=await ie(r,E);n.push({id:"rollback-coverage",status:d.some(k=>k.mode==="edit-file"||k.mode==="run-command")&&E.length===0?"failed":"passed",message:E.length>0?`${E.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),n.push({id:"structured-execution",status:h.some(k=>k.required&&k.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),n.push({id:"checkpoint-boundary",status:l.errors.length===0?"passed":"failed",message:l.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":l.errors.join(" ")});let v=A(V(t)),P={cardId:e.cardId,scope:d.some(k=>k.scope==="project")?"project":"workspace",...e.projectName?{projectName:e.projectName}:{},...d.length===1&&d[0].projectPath?{projectPath:d[0].projectPath}:{},actionIds:d.map(k=>k.id)},C=S(a$3.now),I=`repair_${randomUUID().replaceAll("-","")}`,T=n.some(k=>k.status==="failed")||j.length>0,X=[...j,...n.filter(k=>k.status==="failed").map(k=>k.message)],M={schemaVersion:a,transactionId:I,revision:1,createdAt:C,updatedAt:C,workspace:{name:t.workspace.name,rootRef:"."},target:P,state:T?"decision-required":"awaiting-approval",policy:p,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:[...new Map(y.map(k=>[`${k.projectPath}:${k.adapterId}`,k])).values()],checkpoint:{status:E.length>0?"pending":"unavailable",files:l.entries},stages:h,...T?{decision:{reason:[...new Set(X)].join(" "),options:[...f]}}:{},events:[],integrity:{sourceEvidenceHash:v,planHash:be({sourceEvidenceHash:v,target:P,policy:p,preconditions:n,adapterEvaluations:[...new Map(y.map(k=>[`${k.projectPath}:${k.adapterId}`,k])).values()],stages:h,checkpointFiles:l.entries})}};x(M,"planned",T?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(M,c,"Workspace repair transaction");let ae=J(r,I);return await u.ensureDir(ae),await H(ke(r,I),t),await H(ne(r,I),M),await H(c$1.join(r,b$1),M),M}async function va(e$1,a$2={}){a$1(e$1.proposal,e,"Workspace repair proposal");let r=c$1.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal)),s=e$1.maxRisk??"guarded",i={maxRisk:s,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d=[],o=[],p=new Set(["manual-repair","cancel"]),n=await u.pathExists(c$1.join(r,".workspai-workspace"))||await u.pathExists(c$1.join(r,".workspai"));if(d.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."}),t.projectPath){t.projectPath=q(r,t.projectPath);let g=c$1.resolve(r,t.projectPath),F=await u.lstat(g).catch(()=>{});(!F?.isDirectory()||F.isSymbolicLink())&&o.push("The declared project path must be a real directory inside the workspace.");}t.validation=t.validation?.map(g=>({...g,cwd:q(r,g.cwd)}));let h=new Set,m=new Set,y=0;for(let g of t.changes){g.path=q(r,g.path),g.path==="."&&o.push(`${g.id} cannot replace the workspace root.`),h.has(g.id)&&o.push(`Duplicate proposal change id: ${g.id}.`),m.has(g.path)&&o.push(`Multiple proposal changes target ${g.path}.`),h.add(g.id),m.add(g.path),y+=Buffer.byteLength(g.content??"","utf8"),y>Qe&&o.push("The model proposal exceeds the 25 MiB source-change limit.");let F=Be(g.path);if(F&&o.push(`${g.path}: ${F}`),_[g.risk]>_[s]&&(o.push(`${g.id} exceeds the approved ${s} risk ceiling.`),p.add(g.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let Je=c$1.resolve(r,t.projectPath),Ke=c$1.resolve(r,g.path);W(Je,Ke)||o.push(`${g.path} escapes the declared project scope.`);}}let j=[...m].sort(),f=await ie(r,j);o.push(...f.errors);let N=new Map(f.entries.map(g=>[g.path,g]));for(let g of t.changes){let F=N.get(g.path);if(!F||F.beforeHash!==g.expectedBeforeHash){o.push(`${g.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}g.operation==="delete"&&!F.existed&&o.push(`${g.path} cannot be deleted because it does not exist.`),g.operation==="write"&&F.beforeHash!==null&&A(g.content??"")===F.beforeHash&&o.push(`${g.path} is a no-op and cannot prove source progress.`);}d.push({id:"proposal-boundary",status:o.length===0?"passed":"failed",message:o.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(o)].join(" ")});let E=new Set;if(t.projectPath)E.add(c$1.resolve(r,t.projectPath));else for(let g of t.changes)E.add(await ka(r,g.path));let l=await wa({workspacePath:r,proposal:t,projectRoots:[...E].sort(),maxRisk:s,policy:i,dependencies:a$2});o.push(...l.blockers);let v=l.stages,P=v.some(g=>g.status!=="skipped"&&["audit","test","build"].includes(g.kind));d.push({id:"validation-coverage",status:P?"passed":"unknown",message:P?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let C=[...new Set([...j,...l.checkpointFiles])].sort(),I=await ie(r,C);o.push(...I.errors),d.push({id:"checkpoint-boundary",status:I.errors.length===0?"passed":"failed",message:I.errors.length===0?`${I.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:I.errors.join(" ")});let T=[...t.changes.map(g=>({id:`proposal:${g.id}`,kind:"repair",status:_[g.risk]<=_[s]?"pending":"blocked",required:true,risk:g.risk,summary:g.summary,changedPaths:[g.path]})),...v,{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d.push(...await fe({workspacePath:r,stages:T,toolAvailable:a$2.toolAvailable}));let X=new Set(T.map(g=>g.id));X.size!==T.length&&o.push("Repair proposal stage ids must be unique."),d.push({id:"stage-identity",status:X.size===T.length?"passed":"failed",message:X.size===T.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});let M=A(V(t)),ae={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},actionIds:t.changes.map(g=>`proposal:${g.id}`)},k=S(a$2.now),D=`repair_${randomUUID().replaceAll("-","")}`,te=d.some(g=>g.status==="failed")||o.length>0,$={schemaVersion:a,transactionId:D,revision:1,createdAt:k,updatedAt:k,workspace:{name:await ua(r),rootRef:"."},target:ae,state:te?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:d,adapterEvaluations:l.adapters,checkpoint:{status:"pending",files:I.entries},stages:T,...te?{decision:{reason:[...new Set([...o,...d.filter(g=>g.status==="failed").map(g=>g.message)])].join(" "),options:[...p]}}:{},events:[],integrity:{sourceEvidenceHash:M,planHash:be({sourceEvidenceHash:M,target:ae,policy:i,preconditions:d,adapterEvaluations:l.adapters,stages:T,checkpointFiles:I.entries})}};x($,"planned",te?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a$1($,c,"Workspace repair transaction");let Y=J(r,D);return await u.ensureDir(Y),await H(ke(r,D),t),await H(ne(r,D),$),await H(c$1.join(r,b$1),$),$}async function La(e,a={}){let r=await z(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(He(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 R(e.workspacePath,r,a.now),r;let t=await ge(e.workspacePath,e.transactionId);return A(V(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 R(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:S(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",x(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await R(e.workspacePath,r,a.now),r)}async function Le(e,a){let r=c$1.join(e,he,Ye);await u.ensureDir(c$1.dirname(r));try{let t=await u.stat(r),s=await u.readJson(r).catch(()=>({})),i=typeof s.host=="string"?s.host:void 0,d=typeof s.pid=="number"&&Number.isSafeInteger(s.pid)&&s.pid>0?s.pid:void 0,o=false;if((!i||i===hostname())&&d)try{process.kill(d,0),o=true;}catch(n){o=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let p=!!(i&&i!==hostname());!o&&!p&&Date.now()-t.mtimeMs>aa&&await u.remove(r);}catch{}try{await u.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 u.readJson(r).catch(async()=>{let s=await u.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(s)}catch{return {}}})).transactionId===a&&await u.remove(r);}}async function ya(e){if(e.transaction.checkpoint.status==="captured")return;let a=await ie(e.workspacePath,e.transaction.checkpoint.files.map(s=>s.path));if(a.errors.length>0)throw new Error(a.errors.join(" "));let r=new Map(a.entries.map(s=>[s.path,s]));for(let s of e.transaction.checkpoint.files){let i=r.get(s.path);if(!i||s.existed!==i.existed||s.beforeHash!==i.beforeHash||s.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${s.path}. Create and approve a fresh plan.`)}let t=c$1.join(J(e.workspacePath,e.transaction.transactionId),Te);await u.ensureDir(t);for(let s=0;s<e.transaction.checkpoint.files.length;s+=1){let i=e.transaction.checkpoint.files[s],d=c$1.resolve(e.workspacePath,i.path),o=i.existed?await u.readFile(d):void 0;if(o&&A(o)!==i.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${i.path}. Create and approve a fresh plan.`);let p=`${Te}/${String(s).padStart(4,"0")}.bin`;if(o){let n=c$1.join(J(e.workspacePath,e.transaction.transactionId),p),h=`${n}.${process.pid}.${randomUUID()}.tmp`;await u.writeFile(h,o,{flag:"wx"});let m=await u.readFile(h);if(A(m)!==i.beforeHash)throw await u.remove(h),new Error(`Checkpoint backup verification failed for ${i.path}.`);await u.move(h,n,{overwrite:true}),i.backupRef=p;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=S(e.now),e.transaction.state="checkpointed",x(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function Ne(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),s=await u.readFile(t).catch(()=>{});r.afterHash=s?A(s):null;}}function Ve(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function ve(e,a,r){let t=c$1.resolve(e,a.cwd);if(!W(e,t))throw new Error(`Invocation cwd escapes workspace: ${a.cwd}`);if(a.args.length>100||a.args.some(o=>!o||/[\0\r\n]/.test(o)))throw new Error("Invocation contains invalid arguments.");let s=Ve(a.executable),i=c$1.isAbsolute(a.executable),d=/^\.{1,2}[\\/]/.test(a.executable);if(i&&!W(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!i&&!d&&!sa.has(s))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(o=>/^(?:--force|-f)$/i.test(o)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(o=>/(?:breaking|legacy-peer-deps)/i.test(o)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(s)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${s} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:t,executable:a.executable}}async function ue(e){let a=ve(e.workspacePath,e.invocation,e.policy),r=await u.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 i=c$1.isAbsolute(a.executable)?a.executable:c$1.resolve(a.cwd,a.executable);if(!await G(e.workspacePath,i))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let t=Object.fromEntries(Object.entries(process.env).filter(([i])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(i))),s=await execa(a.executable,e.invocation.args,{cwd:a.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ea,stdin:"ignore",extendEnv:false,env:{...t,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}async function Pa(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=me(e.sourcePlan)?a.actions.filter(s=>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:t.length===0?"passed":"failed",remainingActionIds:t.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}function L(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
|
|
3
|
-
${e.slice(-a)}`}async function Ra(e,a){if(a.type==="file-create")return h$1({projectPath:e,operation:a});if(a.type==="file-append")return i({projectPath:e,operation:a});if(a.type==="file-copy")return j({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 xa(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!W(e.workspacePath,a)||!await G(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let r=Be(e.change.path);if(r)throw new Error(`${e.change.path}: ${r}`);let t=e.transaction.checkpoint.files.find(h=>h.path===e.change.path);if(!t)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let s=await u.readFile(a).catch(()=>{}),i=s?A(s):null;if(i!==t.beforeHash||i!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let d=await u.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 u.remove(a);return}let o=e.change.content??"";if(Buffer.byteLength(o,"utf8")>De)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await u.ensureDir(c$1.dirname(a));let p=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await u.writeFile(p,o,{encoding:"utf8",flag:"wx"}),await u.move(p,a,{overwrite:true});let n=await u.readFile(a);if(A(n)!==A(o))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function ja(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=S(e.dependencies.now),x(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);try{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 xa({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=we(a.action);if(r)await Ra(ee(e.workspacePath,a.action),r);else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??ue)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=L(t.stdout),e.stage.stderrTail=L(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??ue)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=L(a.stdout),e.stage.stderrTail=L(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=S(e.dependencies.now),e.stage.summary=`${e.stage.kind} completed.`,await Ne(e.workspacePath,e.transaction),x(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=S(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await Ne(e.workspacePath,e.transaction),x(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false}}async function Q(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",x(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let r=async i=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision={reason:i,options:["manual-repair","cancel"]},x(e.transaction,"decision",i,{status:"conflicted",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let i of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,i.path);if(!W(e.workspacePath,d)||!await G(e.workspacePath,d))return r(`Rollback refused because ${i.path} escaped the workspace boundary.`);let o=await u.lstat(d).catch(()=>{});if(o?.isSymbolicLink()||o&&!o.isFile())return r(`Rollback refused because ${i.path} is no longer a regular file.`);let p=o?await u.readFile(d):void 0,n=p?A(p):null,h=i.afterHash!==void 0&&n===i.afterHash,m=a&&n===i.beforeHash;if(!h&&!m)return r(`Rollback refused because ${i.path} changed outside this transaction.`);if(!i.existed){t.push({entry:i,absolute:d});continue}if(!i.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${i.path}.`);let y=c$1.join(J(e.workspacePath,e.transaction.transactionId),i.backupRef),j=await u.lstat(y).catch(()=>{});if(!j?.isFile()||j.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${i.path}.`);let f=await u.readFile(y);if(A(f)!==i.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${i.path}.`);t.push({entry:i,absolute:d,backup:f});}for(let i of t){if(!i.entry.existed){await u.remove(i.absolute);continue}let d=i.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${i.entry.path}.`);let o=c$1.join(c$1.dirname(i.absolute),`.${c$1.basename(i.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await u.ensureDir(c$1.dirname(i.absolute)),await u.writeFile(o,d,{flag:"wx"}),i.entry.mode!==void 0&&await u.chmod(o,i.entry.mode),await u.move(o,i.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=S(e.dependencies.now);let s=e.transaction.stages.filter(i=>i.kind==="reconcile"&&i.invocation);for(let i of s){let d=i.invocation;if(!d)continue;let o=`rollback:${i.id}`,p=e.transaction.stages.find(m=>m.id===o&&m.kind==="rollback"),n=p??{id:o,kind:"rollback",status:"pending",required:true,risk:i.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};p||e.transaction.stages.push(n),n.status="running",n.startedAt=S(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,x(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let h;try{h=await(e.dependencies.runInvocation??ue)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy});}catch(m){h={exitCode:null,stdout:"",stderr:m instanceof Error?m.message:String(m)};}if(n.exitCode=h.exitCode,n.stdoutTail=L(h.stdout),n.stderrTail=L(h.stderr),n.completedAt=S(e.dependencies.now),h.exitCode!==0)return n.status="failed",n.summary=h.stderr||h.stdout||`Rollback reconciliation exited with ${h.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"]},x(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",x(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,x(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}async function Va(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Le(r,e.transactionId);try{let s=await z({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(s.state))throw new Error(`Repair transaction cannot execute from state ${s.state}.`);if(s.approval.status!=="approved"||s.approval.approvedPlanHash!==s.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(He(s)!==s.integrity.planHash)return s.approval.status="expired",s.state="decision-required",s.decision={reason:"The compiled repair plan changed after approval. Create and approve a fresh transaction.",options:["cancel"]},x(s,"decision",s.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,s,a.now),s;let i=await ge(r,e.transactionId);if(A(V(i))!==s.integrity.sourceEvidenceHash)return s.approval.status="expired",s.state="decision-required",s.decision={reason:"Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",options:["cancel"]},x(s,"decision",s.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,s,a.now),s;let o=(await fe({workspacePath:r,stages:s.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(o)return s.approval.status="expired",s.state="decision-required",s.decision={reason:`${o.message} The approved plan cannot execute against a changed toolchain.`,options:["manual-repair","cancel"]},x(s,"decision",s.decision.reason,{status:"tool-precondition-failed",now:a.now}),await R(r,s,a.now),s;if(s.state==="rollback-required"||s.state==="rolling-back"){if(!["captured","restored"].includes(s.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await Q({workspacePath:r,transaction:s,dependencies:a}),s}let p=new Map(me(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 ya({workspacePath:r,transaction:s,now:a.now});}catch(f){return s.approval.status="expired",s.state="decision-required",s.decision={reason:f instanceof Error?f.message:String(f),options:["cancel"]},x(s,"decision",s.decision.reason,{status:"precondition-failed",now:a.now}),await R(r,s,a.now),s}s.state="executing",await R(r,s,a.now);for(let f of s.stages.filter(N=>N.kind!=="verify"&&N.kind!=="rollback"))if(!await ja({workspacePath:r,transaction:s,stage:f,actions:p,dependencies:a})&&f.required)return s.state=s.policy.autoRollback?"rollback-required":"decision-required",s.decision={reason:`Required stage ${f.id} failed: ${f.summary}`,options:s.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await R(r,s,a.now),s.policy.autoRollback&&await Q({workspacePath:r,transaction:s,dependencies:a}),s;s.state="verifying";let n=s.stages.find(f=>f.kind==="verify");if(!n)return s.state=s.policy.autoRollback?"rollback-required":"decision-required",s.decision={reason:"The approved plan has no canonical verification stage.",options:s.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await R(r,s,a.now),s.policy.autoRollback&&await Q({workspacePath:r,transaction:s,dependencies:a}),s;n.status="running",n.startedAt=S(a.now),x(s,"verification","Canonical Workspace Intelligence verification started.",{stageId:n.id,status:"running",now:a.now}),await R(r,s,a.now);let h;try{h=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(f){h={status:"failed",exitCode:1,artifactPath:a$3.intelligenceRun},n.stderrTail=L(f instanceof Error?f.message:String(f));}let m=h.status==="passed"&&h.exitCode===0?"passed":h.status==="failed"||h.exitCode===1?"failed":"blocked",y=await Pa({workspacePath:r,transaction:s,sourcePlan:i,dependencies:a,workspaceStatus:m}),j=y.status==="passed"&&m!=="failed";return n.status=j?"passed":"failed",n.completedAt=S(a.now),n.exitCode=h.exitCode,n.summary=j&&m==="passed"?"Selected repair target and canonical workspace verification passed.":j?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":y.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${m}.`,s.verification={status:j?"passed":"failed",targetStatus:y.status,workspaceStatus:m,remainingActionIds:y.remainingActionIds,artifact:a$3.intelligenceRun,exitCode:h.exitCode,summary:n.summary},x(s,"verification",n.summary,{stageId:n.id,status:n.status,now:a.now}),j?(s.state="closed",delete s.decision,x(s,"closed",n.summary,{status:"passed",now:a.now}),await R(r,s,a.now),s):(s.state=s.policy.autoRollback?"rollback-required":"decision-required",s.decision={reason:n.summary,options:s.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]},await R(r,s,a.now),s.policy.autoRollback&&await Q({workspacePath:r,transaction:s,dependencies:a}),s)}finally{await t();}}async function Ia(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Le(r,e.transactionId);try{let s=await z({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(s.state))throw new Error(`Repair transaction cannot roll back from state ${s.state}.`);if(!["captured","restored"].includes(s.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await Q({workspacePath:r,transaction:s,dependencies:a}),s}finally{await t();}}async function Ja(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,x(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await R(e.workspacePath,r,a.now),r}async function Ka(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 Ia({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,x(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 R(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 s=await ge(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,x(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await R(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(me(s))return va({workspacePath:r,proposal:s,...i},a);let d=t.target.actionIds.map(o=>o.startsWith("action:")?o.slice(7):o);return ba({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...i},a)}async function Ga(e){let a=c$1.join(e,he,"transactions"),r=await u.readdir(a).catch(()=>[]);return (await Promise.all(r.map(s=>z({workspacePath:e,transactionId:s}).catch(()=>{})))).filter(s=>!!s).sort((s,i)=>i.updatedAt.localeCompare(s.updatedAt))}export{La as approveWorkspaceRepair,Ja as cancelWorkspaceRepair,Ka as decideWorkspaceRepair,Va as executeWorkspaceRepair,Ba as inspectWorkspaceRepairCapabilities,Ga as listWorkspaceRepairTransactions,ba as planWorkspaceRepair,va as planWorkspaceRepairProposal,z as readWorkspaceRepairTransaction,Ia as rollbackWorkspaceRepair};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{a as runWorkspaceStage}from'./chunk-3LVJBH7V.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-WD2XDMGB.js';
|
|
File without changes
|