workspai 0.53.0 → 0.54.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/artifact-remediation-plan.v1.json +22 -3
- package/contracts/doctor-project-evidence.v1.json +21 -2
- package/contracts/doctor-remediation-plan.v1.json +22 -3
- package/contracts/doctor-workspace-evidence.v1.json +21 -2
- package/contracts/extension-cli-compatibility.v1.json +1 -1
- package/contracts/workspace-intelligence/doctor-dependency-repair-transaction.v1.json +52 -13
- package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +56 -6
- package/contracts/workspace-repair-capabilities.v1.json +48 -0
- package/dist/{artifact-remediation-plan-CJSPCMWA.js → artifact-remediation-plan-A2PRCUNA.js} +1 -1
- package/dist/autopilot-release-63XHNGR6.js +1 -0
- package/dist/{chunk-T6JI7GYZ.js → chunk-4HTSZGEU.js} +50 -50
- package/dist/{chunk-HOVJUP7K.js → chunk-BPACED27.js} +1 -1
- package/dist/{chunk-E5YYVFM2.js → chunk-I5CGTCP5.js} +1 -1
- package/dist/chunk-IQQWQ3II.js +3 -0
- package/dist/chunk-UFOCUHG3.js +1 -0
- package/dist/{chunk-27AXFTKW.js → chunk-ZLYEYHMH.js} +1 -1
- package/dist/{doctor-KNIYGDM7.js → doctor-HJ3O7SAO.js} +1 -1
- package/dist/index.js +7 -7
- package/dist/{pipeline-PVCLAQDI.js → pipeline-TDQK5QYQ.js} +1 -1
- package/dist/{verified-goal-MCSNMA3P.js → verified-goal-S2PEBJUV.js} +1 -1
- package/dist/{workspace-intelligence-runner-JNCQLUH7.js → workspace-intelligence-runner-EQFLRVRL.js} +1 -1
- package/dist/workspace-repair-engine-OZXOXVVV.js +3 -0
- package/dist/workspace-run-VPXRRHDK.js +1 -0
- package/docs/doctor-command.md +6 -0
- package/docs/workspace-repair-engine.md +17 -8
- package/package.json +1 -1
- package/dist/autopilot-release-LZWNQQLY.js +0 -1
- package/dist/chunk-SUV7Y2FH.js +0 -3
- package/dist/chunk-ZTKIBREF.js +0 -1
- package/dist/workspace-repair-engine-SRWECKZO.js +0 -3
- package/dist/workspace-run-3U77TMKX.js +0 -1
- /package/dist/{chunk-USMLRNZ7.js → chunk-3LVJBH7V.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-KVUYAYTY.js';import {c}from'./chunk-
|
|
1
|
+
import {a as a$3}from'./chunk-KVUYAYTY.js';import {c}from'./chunk-BPACED27.js';import {q}from'./chunk-4HTSZGEU.js';import {c as c$1}from'./chunk-FPJNWPKU.js';import {a as a$4}from'./chunk-RMXXK64P.js';import {f,e as e$1}from'./chunk-T3GJ7YVG.js';import {a}from'./chunk-MRFN5ZQP.js';import {g}from'./chunk-HRN5J6PW.js';import {d,a as a$2,e as e$2}from'./chunk-WIO6L24E.js';import {a as a$1,e,d as d$1}from'./chunk-44VJHNZB.js';import c$2 from'chalk';import h from'path';import I from'fs-extra';function O(s){return s===0?"pass":s===2?"warn":"fail"}async function G(s){try{let r=I.readJsonSync(s),i=r.policyProfile,o=(Array.isArray(r.projects)?r.projects:[]).flatMap(u=>{let l=u,m=typeof l.name=="string"?l.name:"project",f=Array.isArray(l.issues)?l.issues.filter(p=>typeof p=="string"):[],P=(Array.isArray(l.probes)?l.probes:[]).flatMap(p=>{let g=p;if(g.status!=="fail"&&g.status!=="warn")return [];let y=typeof g.reason=="string"?g.reason.trim():"";return y?[`${m}: ${y}`]:[]});return [...f.map(p=>`${m}: ${p}`),...P]});return {policyProfile:typeof i?.name=="string"?i.name:void 0,blockers:[...new Set(o)].slice(0,12)}}catch{return {blockers:[]}}}function L(s){return s.some(r=>r.status==="fail")?"blocked":s.some(r=>r.status==="warn")?"needs-attention":"ready"}function _(s,r){if(r)return 3;let i=s.some(o=>o.status==="fail"),t=s.some(o=>o.status==="warn");return i?1:t?2:0}function V(s,r){return s===2&&!r?0:s}async function K(s){let r=await g(s,true),i=false;try{let{syncWorkspaceContract:t}=await import('./workspace-contract-AYFTZIKM.js');await t({workspacePath:s}),i=true;}catch{i=false;}return {sync:r,contractSynced:i}}async function J(s={}){let r=h.resolve(s.workspacePath??process.cwd()),i=a(r);if(!i)throw new Error("No Workspai workspace found in current directory or parents");let t=[],o=[],u=false,l,m,f$1,k=Date.now();try{let{sync:e,contractSynced:a}=await K(i),n=e.workspaceFound&&(e.added.length>0||e.skipped>=0)||e.workspaceFound?"pass":"warn";t.push({name:"sync",status:n,durationMs:Date.now()-k,summary:e.workspaceFound?`registry sync complete (${e.added.length} added, ${e.skipped} existing)${a?", contract synced":""}`:"workspace not registered in global registry; contract sync attempted"}),e.workspaceFound||o.push("workspace registry entry missing \u2014 run workspai create workspace or register manually");}catch(e){u=true,t.push({name:"sync",status:"fail",durationMs:Date.now()-k,summary:`sync failed: ${e instanceof Error?e.message:String(e)}`}),o.push("workspace sync stage failed");}let P=Date.now();try{let e=await q({workspace:true,json:true,quiet:true,strict:s.strict===true,ci:s.strict!==true}),a=O(e),n=await d(i,a$1.doctor)??a$2(i,a$1.doctor),d$1=await G(n);t.push({name:"doctor",status:a,durationMs:Date.now()-P,summary:a==="pass"?"doctor workspace passed":a==="warn"?"doctor workspace reported warnings":"doctor workspace did not pass",exitCode:e,evidencePath:n,policyProfile:d$1.policyProfile,blockers:d$1.blockers}),a==="fail"?o.push(...d$1.blockers.length>0?d$1.blockers.map(j=>`doctor: ${j}`):["doctor workspace gate failed"]):a==="warn"&&o.push("doctor workspace reported warnings");}catch(e){u=true,t.push({name:"doctor",status:"fail",durationMs:Date.now()-P,summary:`doctor failed: ${e instanceof Error?e.message:String(e)}`}),o.push("doctor workspace stage failed");}if(s.skipAnalyze)t.push({name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped"});else {let e=Date.now();try{let a=await a$3({workspacePath:i,json:true,strict:s.strict===true});l=h.isAbsolute(a.enterpriseControls.evidencePath)?a.enterpriseControls.evidencePath:h.join(i,a.enterpriseControls.evidencePath);let n=a.summary.verdict==="blocked"?"fail":a.summary.verdict==="needs-attention"?"warn":"pass";t.push({name:"analyze",status:n,durationMs:Date.now()-e,summary:`analyze verdict: ${a.summary.verdict} (score ${a.summary.score}/100)`,evidencePath:l}),n==="fail"?o.push("analyze reported blocked verdict"):n==="warn"&&o.push("analyze reported needs-attention verdict");}catch(a){u=true,t.push({name:"analyze",status:"fail",durationMs:Date.now()-e,summary:`analyze failed: ${a instanceof Error?a.message:String(a)}`}),o.push("analyze stage failed");}}let p=Date.now();try{let e=await a$4({startPath:i,writeReport:true,skipVerify:s.skipVerify===true});m=e.evidencePath;let a=e.overallStatus==="pass"?"pass":e.overallStatus==="warn"?"warn":"fail";t.push({name:"readiness",status:a,durationMs:Date.now()-p,summary:`readiness overall: ${e.overallStatus}`,evidencePath:e.evidencePath}),a==="fail"?o.push(...e.blockingReasons.map(n=>`readiness: ${n}`)):a==="warn"&&o.push(...e.gates.filter(n=>n.status==="warn").map(n=>`readiness warn: ${n.gate}: ${n.summary}`));}catch(e){u=true,t.push({name:"readiness",status:"fail",durationMs:Date.now()-p,summary:`readiness failed: ${e instanceof Error?e.message:String(e)}`}),o.push("readiness stage failed");}if(s.skipAutopilot)t.push({name:"autopilot",status:"skipped",durationMs:0,summary:"autopilot stage skipped"});else {let e=Date.now(),a=s.autopilotMode??"audit";try{let n=await c({workspacePath:i,mode:a,json:true,skipPipelineStages:true});f$1=n.artifacts.reportPath;let d=n.summary.verdict==="approved"?"pass":n.summary.verdict==="partial"?"warn":"fail";t.push({name:"autopilot",status:d,durationMs:Date.now()-e,summary:`autopilot ${a}: ${n.summary.verdict}`,exitCode:n.summary.exitCode,evidencePath:f$1}),d!=="pass"&&o.push(...n.blockingReasons.slice(0,5));}catch(n){u=true,t.push({name:"autopilot",status:"fail",durationMs:Date.now()-e,summary:`autopilot failed: ${n instanceof Error?n.message:String(n)}`}),o.push("autopilot release stage failed");}}let g=L(t),y=_(t,u),N=h.join(i,e.pipelineLastRun),w={schemaVersion:d$1.pipelineLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:i,summary:{verdict:g,exitCode:y,stagesPassed:t.filter(e=>e.status==="pass").length,stagesWarn:t.filter(e=>e.status==="warn").length,stagesFailed:t.filter(e=>e.status==="fail").length},stages:t,blockingReasons:[...new Set(o)],artifacts:{reportPath:N,analyzeEvidencePath:l,readinessEvidencePath:m,autopilotEvidencePath:f$1}};if(s.writeReport!==false){let e$3=f(w,{commandId:"workspacePipeline",exitCode:y,generatedAt:w.generatedAt,blockers:w.blockingReasons,runId:e$1()});await e$2(i,e.pipelineLastRun,e$3);}if(s.writeReport!==false&&s.noAgentSync!==true&&process.env.RAPIDKIT_NO_AGENT_SYNC!=="1"&&s.agentSync!==false)try{let{syncWorkspaceAgentGrounding:e}=await import('./workspace-agent-sync-446AXPHJ.js'),a=await e({workspacePath:i,write:true,refreshContext:true,strict:false});w.agentGrounding={indexPath:a.indexPath,writtenFiles:a.writtenFiles,blockers:a.blockers};}catch{}return w}async function ce(s){let r;try{r=await J(s);}catch(t){let o=t instanceof Error?t.message:String(t);s.json?console.log(JSON.stringify(c$1({operation:"pipeline",code:"pipeline.failed",message:o}),null,2)):console.log(c$2.red(`Pipeline failed: ${o}`)),process.exit(1);}if(s.json)console.log(JSON.stringify(r,null,2));else {console.log(c$2.bold.cyan(`
|
|
2
2
|
\u{1F517} Workspai Governance Pipeline
|
|
3
3
|
`)),console.log(c$2.bold(`Workspace: ${c$2.cyan(h.basename(r.workspacePath))}`)),console.log(c$2.gray(`Path: ${r.workspacePath}`)),console.log(c$2.white(`Verdict: ${r.summary.verdict} Exit: ${r.summary.exitCode} (${r.summary.stagesPassed} pass / ${r.summary.stagesWarn} warn / ${r.summary.stagesFailed} fail)`));for(let t of r.stages){let o=t.status==="pass"?c$2.green("PASS"):t.status==="warn"?c$2.yellow("WARN"):t.status==="skipped"?c$2.gray("SKIP"):c$2.red("FAIL");console.log(` - ${t.name}: ${o} ${t.summary}`);}if(r.blockingReasons.length>0){console.log(c$2.bold(`
|
|
4
4
|
Blocking reasons:`));for(let t of r.blockingReasons.slice(0,8))console.log(c$2.gray(` \u2022 ${t}`));}console.log(c$2.gray(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-27AXFTKW.js';import {a as a$3}from'./chunk-USMLRNZ7.js';import {c as c$1}from'./chunk-SJLUE6AY.js';import {a as a$2}from'./chunk-RMXXK64P.js';import {p}from'./chunk-7AR5PDLD.js';import {a as a$4}from'./chunk-GR6442P7.js';import {e,d}from'./chunk-WIO6L24E.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,b}from'./chunk-44VJHNZB.js';import {createHash}from'crypto';import l from'path';import y from'fs-extra';var W="workspai.verified-goal.v1",x=b.verifiedGoalStatus,C=a.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",G="contracts/workspace-intelligence/verified-goal-status.v1.json";function A(e){return Array.isArray(e)?`[${e.map(A).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${A(a)}`).join(",")}}`:JSON.stringify(e)}function H(e){return createHash("sha256").update(A(e)).digest("hex")}var te=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","packages.lock.json","Directory.Packages.props","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","build.sbt"],ae=new Set(te.map(e=>e.toLowerCase())),se=new Set([".git",".hg",".svn",".workspai",".venv","venv",".tox",".mypy_cache",".pytest_cache","__pycache__","node_modules","vendor","pods","dist","build","out","target","bin","obj","coverage",".coverage",".next",".nuxt",".svelte-kit"]),F=1e5;function ne(e){return ae.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function re(e){let t=[e],a=[],s=0;for(;t.length>0;){let o=t.shift();if(o===void 0)break;let i=await y.readdir(o,{withFileTypes:true});if(i.sort((n,r)=>n.name.localeCompare(r.name)),s+=i.length,s>F)throw new Error(`Dependency safety baseline exceeded ${F} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of i){let r=l.join(o,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$4(n.name)&&t.push(r);continue}n.isFile()&&ne(n.name)&&a.push(r);}}return a}function ie(e){return /^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/i.test(e)?"node":/^(?:pyproject\.toml|requirements\.txt|Pipfile(?:\.lock)?|poetry\.lock|uv\.lock)$/i.test(e)?"python":/^go\.(?:mod|sum)$/i.test(e)?"go":/^Cargo\.(?:toml|lock)$/i.test(e)?"rust":/^(?:pom\.xml|build\.gradle(?:\.kts)?|gradle\.lockfile)$/i.test(e)?"jvm":/^(?:Directory\.Packages\.props|packages\.lock\.json)$/i.test(e)?"dotnet":/^composer\.(?:json|lock)$/i.test(e)?"php":/^Gemfile(?:\.lock)?$/i.test(e)?"ruby":/^mix\.(?:exs|lock)$/i.test(e)?"elixir":/^(?:deps\.edn|project\.clj)$/i.test(e)?"clojure":/^build\.sbt$/i.test(e)?"scala":/\.(?:csproj|fsproj|vbproj)$/i.test(e)?"dotnet":"unknown"}function K(e){try{let t=JSON.parse(e),a={};for(let s of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t[s];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[i,n]of Object.entries(o))typeof n=="string"&&(a[`${s}:${i}`]=n);}return a}catch{return}}async function U(e,t){let s=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(i=>t.kind==="workspace"||i.name===t.projectName||l.resolve(e,i.path)===l.resolve(t.projectPath??"")),o=new Map;for(let i of s){let n=l.resolve(e,i.path),r=await re(n);for(let c of r){let p=l.basename(c),f=await y.readFile(c,"utf8"),d=l.relative(e,c).split(l.sep).join("/");o.set(d,{path:d,ecosystem:ie(p),sha256:createHash("sha256").update(f).digest("hex"),...p==="package.json"?{dependencies:K(f)??{}}:{}});}}return {manifests:[...o.values()].sort((i,n)=>i.path.localeCompare(n.path))}}function O(e){let a=e.replace(/^(?:workspace:|npm:[^@]+@)/,"").match(/(?:^|[^\d])(\d+)(?:\.\d+)?(?:\.\d+)?/);return a?Number(a[1]):null}function S(e){return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|poetry\.lock|uv\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|gradle\.lockfile|packages\.lock\.json|composer\.lock|Gemfile\.lock|mix\.lock)$/i.test(e)}async function oe(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],s=await U(e.workspace.path,e.scope),o=new Map(s.manifests.map(r=>[r.path,r])),i=new Map(t.manifests.map(r=>[r.path,r])),n=new Set;for(let r of t.manifests){let c=o.get(r.path);(!c||c.sha256!==r.sha256)&&n.add(r.path);}for(let r of s.manifests)i.has(r.path)||n.add(r.path);for(let r of s.manifests)!i.has(r.path)&&!S(r.path)&&a.push(`${r.path} was added after the safety baseline`);for(let r of t.manifests){let c=o.get(r.path);if(!c){a.push(`${r.path} was removed`);continue}if(c.sha256===r.sha256)continue;if(r.dependencies){let d=await y.readFile(l.join(e.workspace.path,r.path),"utf8"),m=K(d);if(!m){a.push(`${r.path} is not valid dependency JSON`);continue}for(let[u,g]of Object.entries(r.dependencies)){let h=m[u];if(!h){a.push(`${u.replace(/^[^:]+:/,"")} was removed`);continue}if(h===g)continue;let $=O(g),R=O(h);($===null||R===null||$!==R||/(?:latest|\*)/i.test(h))&&a.push(`${u.replace(/^[^:]+:/,"")} changed outside its proven major range (${g} \u2192 ${h})`);}continue}if(S(r.path))continue;let p=l.posix.dirname(r.path);[...o.values()].some(d=>{let m=l.posix.dirname(d.path);return d.ecosystem===r.ecosystem&&(m===p||p.startsWith(`${m}/`))&&S(d.path)&&n.has(d.path)})||a.push(`${r.path} changed without a matching reconciled ${r.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=l.join(e,".workspai","goals",t);return {directory:a,goal:l.join(a,"goal.json"),status:l.join(a,"status.json"),latestReport:l.join(e,C)}}function ce(e){return {workspacePath:l.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,constraints:e.constraints}}async function V(e,t){await y.ensureDir(l.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await y.writeJson(a,t,{spaces:2}),await y.rename(a,e);}async function le(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let s=a.startsWith("project:")?a.slice(8).trim():a;if(!s)throw new Error("Project goal scope must name a project.");let i=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(c=>{let p=l.resolve(e,c.path);return c.name===s||c.path===s||p===l.resolve(s)});if(i.length!==1)throw new Error(i.length===0?`Project goal scope was not found: ${s}`:`Project goal scope is ambiguous: ${s}`);let n=i[0],r=l.resolve(e,n.path);return {project:n,scope:{kind:"project",projectName:n.name,projectPath:r}}}function z(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Y(e){if(!e)return null;try{let t=await y.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function de(e){return Array.isArray(e.projects)?e.projects.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):e.project&&typeof e.project=="object"&&!Array.isArray(e.project)?[e.project]:[]}function ue(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function X(e,t){let a$1=await d(e,a.doctor),s=await Y(a$1);if(!s)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let o=de(s).filter(c=>{if(t.kind==="workspace")return true;let p=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?l.resolve(c.path):typeof c.projectPath=="string"?l.resolve(c.projectPath):"";return p===t.projectName||t.projectPath!==void 0&&f===l.resolve(t.projectPath)}),i=o.map(ue).filter(c=>c!==null),n=i.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),r=o.length>0&&n.length===o.length?n.reduce((c,p)=>c+p,0):null;return {measuredAt:(()=>{let c=i.map(p=>p.generatedAt).filter(p=>typeof p=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:r,target:0,unit:"blocking-vulnerabilities",status:z(r,0,"maximum"),evidencePaths:a$1?[a$1]:[],message:r===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${r} blocking dependency vulnerability finding(s) remain.`}}async function Q(e){let t=await a$2({startPath:e,writeReport:false}),a=t.gates.filter(o=>o.status==="pass").length,s=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:s,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(o=>o.evidencePath).filter(o=>typeof o=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${s-a} release readiness gate(s) still require work.`}}async function B(e){let t=await c$1({projectPath:e.projectPath,target:e.target,run:e.run}),s=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:s,target:e.target,unit:"percent",status:z(s,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":s===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${s}% (target ${e.target}%).`}}}async function Z(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return B({projectPath:e.scope.projectPath,target:e.target,run:e.run})}let t=await p({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=[];for(let d of t.projects)a.push({projectName:d.name,result:await B({projectPath:l.resolve(e.workspacePath,d.path),target:e.target,run:e.run})});let s=a.filter(d=>d.result.executionStatus==="failed"),o=a.filter(d=>d.result.measurement.status==="unavailable"),i=a.filter(d=>d.result.measurement.status==="unsatisfied"),n=a.map(d=>d.result.measurement.value).filter(d=>d!==null),r=n.length===a.length&&n.length>0?Math.min(...n):null,c=s.length>0?"failed":o.length>0?"unavailable":i.length>0?"below-target":"passed",p$1=a.map(d=>d.result.measurement.measuredAt).sort(),f=[...s.map(d=>`${d.projectName}: coverage command failed`),...o.map(d=>`${d.projectName}: coverage unavailable`),...i.map(d=>`${d.projectName}: ${d.result.measurement.value??"unknown"}%`)];return {executionStatus:c,measurement:{measuredAt:p$1[p$1.length-1]??new Date().toISOString(),value:r,target:e.target,unit:"percent",status:c==="passed"?"satisfied":c==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(a.flatMap(d=>d.result.measurement.evidencePaths))],message:c==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${f.join("; ")}.`}}}function pe(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${t} test coverage to ${e.target??80}% without breaking its build.`}function ge(e,t){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t}}async function fe(e){return e.kind==="release-readiness"?Q(e.workspacePath):e.kind==="dependency-security"?X(e.workspacePath,e.scope):(await Z({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false})).measurement}async function Ge(e$1){let t=l.resolve(e$1.workspacePath),a=Math.max(0,Math.min(100,Math.round(e$1.target??80))),{scope:s}=await le(t,e$1.scope),o={workspacePath:l.resolve(t),kind:e$1.kind,scope:s,target:e$1.kind==="test-coverage"?a:null,constraints:{allowBreakingChanges:e$1.allowBreakingChanges===true,allowForce:e$1.allowForce===true,requireBuild:e$1.requireBuild!==false,requireTests:e$1.requireTests!==false}},i=H(o),n=`goal-${e$1.kind}-${i.slice(0,16)}`,r=E(t,n);if(await y.pathExists(r.goal)){let{goal:m,status:u}=await ee(t,n);if(m.fingerprint===i)return {goal:m,status:u,resumed:u.state!=="verified"}}let c=new Date().toISOString(),p=await fe({workspacePath:t,kind:e$1.kind,scope:s,target:a}),f={schemaVersion:W,id:n,fingerprint:i,createdAt:c,updatedAt:c,workspace:{name:l.basename(t),path:t},scope:s,kind:e$1.kind,summary:pe({kind:e$1.kind,scope:s,target:a}),constraints:o.constraints,criteria:ge(e$1.kind,a),baseline:p,...e$1.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,s)}:{},artifactPaths:{goal:r.goal,status:r.status,latestReport:r.latestReport}},d={schemaVersion:x,goalId:n,goalFingerprint:i,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:p,checks:[],blockingReasons:[],evidencePaths:p.evidencePaths,nextActions:e$1.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e$1.kind==="dependency-security"?["Inspect the fresh project dependency audit.","Apply only compatible non-force dependency repairs.","Reconcile the lockfile, test, build, and verify again."]:["Inspect the current remediation plan and failing release gates.","Repair the next causal blocker, then verify again."],artifactPath:r.status};return a$1(f,J,"Verified goal"),a$1(d,G,"Verified goal status"),await V(r.goal,f),await V(r.status,d),await e(t,C,d),{goal:f,status:d,resumed:false}}async function ee(e,t){let a=E(l.resolve(e),t),s=await y.readJson(a.goal),o=await y.readJson(a.status);a$1(s,J,"Verified goal"),a$1(o,G,"Verified goal status");let i=l.resolve(e),n=l.resolve(s.artifactPaths.goal)===l.resolve(a.goal)&&l.resolve(s.artifactPaths.status)===l.resolve(a.status)&&l.resolve(s.artifactPaths.latestReport)===l.resolve(a.latestReport);if(s.schemaVersion!==W||o.schemaVersion!==x||s.id!==o.goalId||s.fingerprint!==o.goalFingerprint||s.fingerprint!==H(ce(s))||l.resolve(s.workspace.path)!==i||l.resolve(o.workspacePath)!==i||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:s,status:o}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function q(e){let t=[],a=e.goal.scope.kind==="project"&&e.goal.scope.projectName?`project:${e.goal.scope.projectName}`:void 0;for(let s of ["test","build"]){if(s==="test"&&e.includeTests===false)continue;if(!(s==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:s,label:`${s} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:s,label:`${s} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let i=await a$3({workspacePath:e.goal.workspace.path,stage:s,scope:a,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false});if(t.push(k({id:s,label:`${s} validation`,status:i.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${i.summary.exitCode}`,evidencePath:l.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),i.summary.exitCode!==0)break}return t}async function Ee(e$1){let t=l.resolve(e$1.workspacePath),{goal:a$2,status:s}=await ee(t,e$1.goalId),o=e$1.run!==false,i=[],n;if(o&&e$1.runIntelligence!==false){let u=await c({workspacePath:t,strict:true,agent:"generic"}),g=u.exitCode===0||u.exitCode===2,h=a$2.kind==="release-readiness";i.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:u.exitCode===0||u.exitCode===2&&!h?"passed":u.exitCode===2?"blocked":"failed",expected:"passed",actual:u.exitCode===2&&g&&!h?`${u.status}; canonical evidence refreshed for goal-scoped verification`:u.status,evidencePath:l.join(t,a.intelligenceRun)}));}if(a$2.kind==="release-readiness"){n=await Q(t),i.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:l.join(t,a.readiness)}));let u=await d(t,a.verify),g=await Y(u),h=g?.summary&&typeof g.summary=="object"&&!Array.isArray(g.summary)?String(g.summary.verdict??"missing"):"missing";i.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:l.join(t,a.verify)}));}else if(a$2.kind==="dependency-security")n=await X(t,a$2.scope),i.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(a$2.constraints.allowBreakingChanges||a$2.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$2.constraints.allowBreakingChanges}, allowForce=${a$2.constraints.allowForce}`}):await oe(a$2)),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o}));else {let u=a$2.criteria.kind==="test-coverage"?a$2.criteria.minimumPercent:a$2.baseline.target;if(u===null)throw new Error("Coverage goal does not have a valid target.");let g=await Z({workspacePath:t,scope:a$2.scope,target:u,run:o});n=g.measurement,i.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${u}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(k({id:"test",label:"Coverage test execution",status:g.executionStatus==="failed"?"failed":g.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:g.executionStatus==="failed"?"coverage test command failed":g.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o,includeTests:false}));}let r=i.filter(u=>u.status==="blocked"||u.status==="failed"||u.status==="missing").map(u=>u.message),c$1=[...new Set([...n.evidencePaths,...i.map(u=>u.evidencePath).filter(u=>typeof u=="string")])],p=n.status==="satisfied"&&i.every(u=>u.status==="passed"||u.status==="skipped"),f=E(t,a$2.id),d$1=p?[]:a$2.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$2.kind==="dependency-security"?["Use fresh audit candidates and compatible package-manager repairs.","Reconcile lockfiles before running verified goal checks again."]:["Repair the first blocking readiness gate and verify the goal again."],m={schemaVersion:x,goalId:a$2.id,goalFingerprint:a$2.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:p?"verified":i.some(u=>u.status==="failed")?"failed":"blocked",attempt:s.attempt+1,progress:n,checks:i,blockingReasons:r,evidencePaths:c$1,nextActions:d$1,artifactPath:f.status};return a$1(m,G,"Verified goal status"),await V(f.status,m),await e(t,C,m),m}export{C as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,x as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ge as planVerifiedGoal,ee as readVerifiedGoal,Ee as verifyVerifiedGoal};
|
|
1
|
+
import {c}from'./chunk-ZLYEYHMH.js';import {a as a$3}from'./chunk-3LVJBH7V.js';import {c as c$1}from'./chunk-SJLUE6AY.js';import {a as a$2}from'./chunk-RMXXK64P.js';import {p}from'./chunk-7AR5PDLD.js';import {a as a$4}from'./chunk-GR6442P7.js';import {e,d}from'./chunk-WIO6L24E.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {a,b}from'./chunk-44VJHNZB.js';import {createHash}from'crypto';import l from'path';import y from'fs-extra';var W="workspai.verified-goal.v1",x=b.verifiedGoalStatus,C=a.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",G="contracts/workspace-intelligence/verified-goal-status.v1.json";function A(e){return Array.isArray(e)?`[${e.map(A).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${A(a)}`).join(",")}}`:JSON.stringify(e)}function H(e){return createHash("sha256").update(A(e)).digest("hex")}var te=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","packages.lock.json","Directory.Packages.props","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","build.sbt"],ae=new Set(te.map(e=>e.toLowerCase())),se=new Set([".git",".hg",".svn",".workspai",".venv","venv",".tox",".mypy_cache",".pytest_cache","__pycache__","node_modules","vendor","pods","dist","build","out","target","bin","obj","coverage",".coverage",".next",".nuxt",".svelte-kit"]),F=1e5;function ne(e){return ae.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function re(e){let t=[e],a=[],s=0;for(;t.length>0;){let o=t.shift();if(o===void 0)break;let i=await y.readdir(o,{withFileTypes:true});if(i.sort((n,r)=>n.name.localeCompare(r.name)),s+=i.length,s>F)throw new Error(`Dependency safety baseline exceeded ${F} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of i){let r=l.join(o,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$4(n.name)&&t.push(r);continue}n.isFile()&&ne(n.name)&&a.push(r);}}return a}function ie(e){return /^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/i.test(e)?"node":/^(?:pyproject\.toml|requirements\.txt|Pipfile(?:\.lock)?|poetry\.lock|uv\.lock)$/i.test(e)?"python":/^go\.(?:mod|sum)$/i.test(e)?"go":/^Cargo\.(?:toml|lock)$/i.test(e)?"rust":/^(?:pom\.xml|build\.gradle(?:\.kts)?|gradle\.lockfile)$/i.test(e)?"jvm":/^(?:Directory\.Packages\.props|packages\.lock\.json)$/i.test(e)?"dotnet":/^composer\.(?:json|lock)$/i.test(e)?"php":/^Gemfile(?:\.lock)?$/i.test(e)?"ruby":/^mix\.(?:exs|lock)$/i.test(e)?"elixir":/^(?:deps\.edn|project\.clj)$/i.test(e)?"clojure":/^build\.sbt$/i.test(e)?"scala":/\.(?:csproj|fsproj|vbproj)$/i.test(e)?"dotnet":"unknown"}function K(e){try{let t=JSON.parse(e),a={};for(let s of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t[s];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[i,n]of Object.entries(o))typeof n=="string"&&(a[`${s}:${i}`]=n);}return a}catch{return}}async function U(e,t){let s=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(i=>t.kind==="workspace"||i.name===t.projectName||l.resolve(e,i.path)===l.resolve(t.projectPath??"")),o=new Map;for(let i of s){let n=l.resolve(e,i.path),r=await re(n);for(let c of r){let p=l.basename(c),f=await y.readFile(c,"utf8"),d=l.relative(e,c).split(l.sep).join("/");o.set(d,{path:d,ecosystem:ie(p),sha256:createHash("sha256").update(f).digest("hex"),...p==="package.json"?{dependencies:K(f)??{}}:{}});}}return {manifests:[...o.values()].sort((i,n)=>i.path.localeCompare(n.path))}}function O(e){let a=e.replace(/^(?:workspace:|npm:[^@]+@)/,"").match(/(?:^|[^\d])(\d+)(?:\.\d+)?(?:\.\d+)?/);return a?Number(a[1]):null}function S(e){return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|poetry\.lock|uv\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|gradle\.lockfile|packages\.lock\.json|composer\.lock|Gemfile\.lock|mix\.lock)$/i.test(e)}async function oe(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],s=await U(e.workspace.path,e.scope),o=new Map(s.manifests.map(r=>[r.path,r])),i=new Map(t.manifests.map(r=>[r.path,r])),n=new Set;for(let r of t.manifests){let c=o.get(r.path);(!c||c.sha256!==r.sha256)&&n.add(r.path);}for(let r of s.manifests)i.has(r.path)||n.add(r.path);for(let r of s.manifests)!i.has(r.path)&&!S(r.path)&&a.push(`${r.path} was added after the safety baseline`);for(let r of t.manifests){let c=o.get(r.path);if(!c){a.push(`${r.path} was removed`);continue}if(c.sha256===r.sha256)continue;if(r.dependencies){let d=await y.readFile(l.join(e.workspace.path,r.path),"utf8"),m=K(d);if(!m){a.push(`${r.path} is not valid dependency JSON`);continue}for(let[u,g]of Object.entries(r.dependencies)){let h=m[u];if(!h){a.push(`${u.replace(/^[^:]+:/,"")} was removed`);continue}if(h===g)continue;let $=O(g),R=O(h);($===null||R===null||$!==R||/(?:latest|\*)/i.test(h))&&a.push(`${u.replace(/^[^:]+:/,"")} changed outside its proven major range (${g} \u2192 ${h})`);}continue}if(S(r.path))continue;let p=l.posix.dirname(r.path);[...o.values()].some(d=>{let m=l.posix.dirname(d.path);return d.ecosystem===r.ecosystem&&(m===p||p.startsWith(`${m}/`))&&S(d.path)&&n.has(d.path)})||a.push(`${r.path} changed without a matching reconciled ${r.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=l.join(e,".workspai","goals",t);return {directory:a,goal:l.join(a,"goal.json"),status:l.join(a,"status.json"),latestReport:l.join(e,C)}}function ce(e){return {workspacePath:l.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,constraints:e.constraints}}async function V(e,t){await y.ensureDir(l.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await y.writeJson(a,t,{spaces:2}),await y.rename(a,e);}async function le(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let s=a.startsWith("project:")?a.slice(8).trim():a;if(!s)throw new Error("Project goal scope must name a project.");let i=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(c=>{let p=l.resolve(e,c.path);return c.name===s||c.path===s||p===l.resolve(s)});if(i.length!==1)throw new Error(i.length===0?`Project goal scope was not found: ${s}`:`Project goal scope is ambiguous: ${s}`);let n=i[0],r=l.resolve(e,n.path);return {project:n,scope:{kind:"project",projectName:n.name,projectPath:r}}}function z(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Y(e){if(!e)return null;try{let t=await y.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function de(e){return Array.isArray(e.projects)?e.projects.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):e.project&&typeof e.project=="object"&&!Array.isArray(e.project)?[e.project]:[]}function ue(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function X(e,t){let a$1=await d(e,a.doctor),s=await Y(a$1);if(!s)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let o=de(s).filter(c=>{if(t.kind==="workspace")return true;let p=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?l.resolve(c.path):typeof c.projectPath=="string"?l.resolve(c.projectPath):"";return p===t.projectName||t.projectPath!==void 0&&f===l.resolve(t.projectPath)}),i=o.map(ue).filter(c=>c!==null),n=i.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),r=o.length>0&&n.length===o.length?n.reduce((c,p)=>c+p,0):null;return {measuredAt:(()=>{let c=i.map(p=>p.generatedAt).filter(p=>typeof p=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:r,target:0,unit:"blocking-vulnerabilities",status:z(r,0,"maximum"),evidencePaths:a$1?[a$1]:[],message:r===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${r} blocking dependency vulnerability finding(s) remain.`}}async function Q(e){let t=await a$2({startPath:e,writeReport:false}),a=t.gates.filter(o=>o.status==="pass").length,s=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:s,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(o=>o.evidencePath).filter(o=>typeof o=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${s-a} release readiness gate(s) still require work.`}}async function B(e){let t=await c$1({projectPath:e.projectPath,target:e.target,run:e.run}),s=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:s,target:e.target,unit:"percent",status:z(s,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":s===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${s}% (target ${e.target}%).`}}}async function Z(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return B({projectPath:e.scope.projectPath,target:e.target,run:e.run})}let t=await p({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=[];for(let d of t.projects)a.push({projectName:d.name,result:await B({projectPath:l.resolve(e.workspacePath,d.path),target:e.target,run:e.run})});let s=a.filter(d=>d.result.executionStatus==="failed"),o=a.filter(d=>d.result.measurement.status==="unavailable"),i=a.filter(d=>d.result.measurement.status==="unsatisfied"),n=a.map(d=>d.result.measurement.value).filter(d=>d!==null),r=n.length===a.length&&n.length>0?Math.min(...n):null,c=s.length>0?"failed":o.length>0?"unavailable":i.length>0?"below-target":"passed",p$1=a.map(d=>d.result.measurement.measuredAt).sort(),f=[...s.map(d=>`${d.projectName}: coverage command failed`),...o.map(d=>`${d.projectName}: coverage unavailable`),...i.map(d=>`${d.projectName}: ${d.result.measurement.value??"unknown"}%`)];return {executionStatus:c,measurement:{measuredAt:p$1[p$1.length-1]??new Date().toISOString(),value:r,target:e.target,unit:"percent",status:c==="passed"?"satisfied":c==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(a.flatMap(d=>d.result.measurement.evidencePaths))],message:c==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${f.join("; ")}.`}}}function pe(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${t} test coverage to ${e.target??80}% without breaking its build.`}function ge(e,t){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t}}async function fe(e){return e.kind==="release-readiness"?Q(e.workspacePath):e.kind==="dependency-security"?X(e.workspacePath,e.scope):(await Z({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false})).measurement}async function Ge(e$1){let t=l.resolve(e$1.workspacePath),a=Math.max(0,Math.min(100,Math.round(e$1.target??80))),{scope:s}=await le(t,e$1.scope),o={workspacePath:l.resolve(t),kind:e$1.kind,scope:s,target:e$1.kind==="test-coverage"?a:null,constraints:{allowBreakingChanges:e$1.allowBreakingChanges===true,allowForce:e$1.allowForce===true,requireBuild:e$1.requireBuild!==false,requireTests:e$1.requireTests!==false}},i=H(o),n=`goal-${e$1.kind}-${i.slice(0,16)}`,r=E(t,n);if(await y.pathExists(r.goal)){let{goal:m,status:u}=await ee(t,n);if(m.fingerprint===i)return {goal:m,status:u,resumed:u.state!=="verified"}}let c=new Date().toISOString(),p=await fe({workspacePath:t,kind:e$1.kind,scope:s,target:a}),f={schemaVersion:W,id:n,fingerprint:i,createdAt:c,updatedAt:c,workspace:{name:l.basename(t),path:t},scope:s,kind:e$1.kind,summary:pe({kind:e$1.kind,scope:s,target:a}),constraints:o.constraints,criteria:ge(e$1.kind,a),baseline:p,...e$1.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,s)}:{},artifactPaths:{goal:r.goal,status:r.status,latestReport:r.latestReport}},d={schemaVersion:x,goalId:n,goalFingerprint:i,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:p,checks:[],blockingReasons:[],evidencePaths:p.evidencePaths,nextActions:e$1.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e$1.kind==="dependency-security"?["Inspect the fresh project dependency audit.","Apply only compatible non-force dependency repairs.","Reconcile the lockfile, test, build, and verify again."]:["Inspect the current remediation plan and failing release gates.","Repair the next causal blocker, then verify again."],artifactPath:r.status};return a$1(f,J,"Verified goal"),a$1(d,G,"Verified goal status"),await V(r.goal,f),await V(r.status,d),await e(t,C,d),{goal:f,status:d,resumed:false}}async function ee(e,t){let a=E(l.resolve(e),t),s=await y.readJson(a.goal),o=await y.readJson(a.status);a$1(s,J,"Verified goal"),a$1(o,G,"Verified goal status");let i=l.resolve(e),n=l.resolve(s.artifactPaths.goal)===l.resolve(a.goal)&&l.resolve(s.artifactPaths.status)===l.resolve(a.status)&&l.resolve(s.artifactPaths.latestReport)===l.resolve(a.latestReport);if(s.schemaVersion!==W||o.schemaVersion!==x||s.id!==o.goalId||s.fingerprint!==o.goalFingerprint||s.fingerprint!==H(ce(s))||l.resolve(s.workspace.path)!==i||l.resolve(o.workspacePath)!==i||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:s,status:o}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function q(e){let t=[],a=e.goal.scope.kind==="project"&&e.goal.scope.projectName?`project:${e.goal.scope.projectName}`:void 0;for(let s of ["test","build"]){if(s==="test"&&e.includeTests===false)continue;if(!(s==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:s,label:`${s} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:s,label:`${s} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let i=await a$3({workspacePath:e.goal.workspace.path,stage:s,scope:a,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false});if(t.push(k({id:s,label:`${s} validation`,status:i.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${i.summary.exitCode}`,evidencePath:l.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),i.summary.exitCode!==0)break}return t}async function Ee(e$1){let t=l.resolve(e$1.workspacePath),{goal:a$2,status:s}=await ee(t,e$1.goalId),o=e$1.run!==false,i=[],n;if(o&&e$1.runIntelligence!==false){let u=await c({workspacePath:t,strict:true,agent:"generic"}),g=u.exitCode===0||u.exitCode===2,h=a$2.kind==="release-readiness";i.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:u.exitCode===0||u.exitCode===2&&!h?"passed":u.exitCode===2?"blocked":"failed",expected:"passed",actual:u.exitCode===2&&g&&!h?`${u.status}; canonical evidence refreshed for goal-scoped verification`:u.status,evidencePath:l.join(t,a.intelligenceRun)}));}if(a$2.kind==="release-readiness"){n=await Q(t),i.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:l.join(t,a.readiness)}));let u=await d(t,a.verify),g=await Y(u),h=g?.summary&&typeof g.summary=="object"&&!Array.isArray(g.summary)?String(g.summary.verdict??"missing"):"missing";i.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:l.join(t,a.verify)}));}else if(a$2.kind==="dependency-security")n=await X(t,a$2.scope),i.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(a$2.constraints.allowBreakingChanges||a$2.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$2.constraints.allowBreakingChanges}, allowForce=${a$2.constraints.allowForce}`}):await oe(a$2)),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o}));else {let u=a$2.criteria.kind==="test-coverage"?a$2.criteria.minimumPercent:a$2.baseline.target;if(u===null)throw new Error("Coverage goal does not have a valid target.");let g=await Z({workspacePath:t,scope:a$2.scope,target:u,run:o});n=g.measurement,i.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${u}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(k({id:"test",label:"Coverage test execution",status:g.executionStatus==="failed"?"failed":g.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:g.executionStatus==="failed"?"coverage test command failed":g.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&i.push(...await q({goal:a$2,run:o,includeTests:false}));}let r=i.filter(u=>u.status==="blocked"||u.status==="failed"||u.status==="missing").map(u=>u.message),c$1=[...new Set([...n.evidencePaths,...i.map(u=>u.evidencePath).filter(u=>typeof u=="string")])],p=n.status==="satisfied"&&i.every(u=>u.status==="passed"||u.status==="skipped"),f=E(t,a$2.id),d$1=p?[]:a$2.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$2.kind==="dependency-security"?["Use fresh audit candidates and compatible package-manager repairs.","Reconcile lockfiles before running verified goal checks again."]:["Repair the first blocking readiness gate and verify the goal again."],m={schemaVersion:x,goalId:a$2.id,goalFingerprint:a$2.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:p?"verified":i.some(u=>u.status==="failed")?"failed":"blocked",attempt:s.attempt+1,progress:n,checks:i,blockingReasons:r,evidencePaths:c$1,nextActions:d$1,artifactPath:f.status};return a$1(m,G,"Verified goal status"),await V(f.status,m),await e(t,C,m),m}export{C as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,x as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ge as planVerifiedGoal,ee as readVerifiedGoal,Ee as verifyVerifiedGoal};
|
package/dist/{workspace-intelligence-runner-JNCQLUH7.js → workspace-intelligence-runner-EQFLRVRL.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-
|
|
1
|
+
export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-ZLYEYHMH.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as runWorkspaceStage}from'./chunk-3LVJBH7V.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-WD2XDMGB.js';
|
package/docs/doctor-command.md
CHANGED
|
@@ -155,6 +155,12 @@ unparseable response, or unsupported zero-configuration workflow is explicit
|
|
|
155
155
|
evidence—not a zero-vulnerability result. Compatible automatic fixes never use
|
|
156
156
|
force.
|
|
157
157
|
|
|
158
|
+
When a declared dependency tree has not been installed, Doctor emits a typed
|
|
159
|
+
`dependency-materialization` capability instead of only a human shell hint. The capability
|
|
160
|
+
records the runtime-native executable, project scope, observable installed-tree state, and
|
|
161
|
+
required validation stages. An unchanged manifest or lockfile is valid in this case: successful
|
|
162
|
+
installation plus declared test/build checks and canonical verification are the completion proof.
|
|
163
|
+
|
|
158
164
|
When a scanner has no direct automatic fix—or advertises a downgrade—Doctor
|
|
159
165
|
does not conclude that the project has no compatible repair. It emits guarded
|
|
160
166
|
`resolutionCandidates` for the affected direct or transitive dependency. Each
|
|
@@ -57,6 +57,12 @@ hashes, duplicate targets, workspace evidence edits, Git internals, installed de
|
|
|
57
57
|
secret-bearing files, path/link escapes, and ungoverned commands. Dependency manifest proposals
|
|
58
58
|
still receive CLI-inferred reconcile, audit, test, and build stages before strict verification.
|
|
59
59
|
|
|
60
|
+
Doctor also publishes a distinct `dependency-materialization` transaction when manifests exist
|
|
61
|
+
but the installed runtime tree is missing. Its install or restore invocation is the repair stage
|
|
62
|
+
itself; it does not require a manifest or lockfile diff and is never run twice. Declared tests and
|
|
63
|
+
builds, followed by canonical verification, prove closure. Dependency-security transactions still
|
|
64
|
+
require manifest/lock reconciliation and a clean focused audit.
|
|
65
|
+
|
|
60
66
|
## Safety and ownership
|
|
61
67
|
|
|
62
68
|
- The immutable plan hash covers target, policy, preconditions, structured invocations, risk,
|
|
@@ -75,7 +81,10 @@ still receive CLI-inferred reconcile, audit, test, and build stages before stric
|
|
|
75
81
|
rollback verifies every target and backup hash, rejects path/link conflicts, restores files
|
|
76
82
|
atomically with their recorded modes, and reconciles installed dependencies with the restored
|
|
77
83
|
manifests and lockfiles. It reports `decision-required` if any part cannot be proven complete.
|
|
78
|
-
-
|
|
84
|
+
- Strict canonical Workspace Intelligence always runs before closure. The receipt separates
|
|
85
|
+
`verification.targetStatus` from `verification.workspaceStatus`: a proven selected action may
|
|
86
|
+
close while unrelated governed findings keep the workspace blocked. Those findings remain the
|
|
87
|
+
next repair target and never trigger rollback of a valid bounded repair.
|
|
79
88
|
- Required executables are resolved before approval and again immediately before execution. A
|
|
80
89
|
missing or changed toolchain expires approval instead of starting a partial transaction.
|
|
81
90
|
|
|
@@ -86,13 +95,13 @@ Dependency transactions are package-manager aware. The canonical inventory is pu
|
|
|
86
95
|
capabilities`. It distinguishes full support from conditional support instead of treating “the
|
|
87
96
|
command exists” as proof that the whole repair is executable.
|
|
88
97
|
|
|
89
|
-
Node, Python, Go, Rust, Composer, Bundler, Elixir, Deno, .NET, Maven,
|
|
90
|
-
detected independently. A genuinely multi-runtime project receives collision-free
|
|
91
|
-
every applicable adapter. Doctor dependency actions remain bound to the ecosystem
|
|
92
|
-
their evidence so an npm finding cannot accidentally trigger an unrelated Python
|
|
93
|
-
If a manifest, required executable, isolated environment, project-declared
|
|
94
|
-
surface is unavailable, the engine returns `decision-required`; it never
|
|
95
|
-
model fallback.
|
|
98
|
+
Node, Python, Go, Rust, Composer, Bundler, Elixir, Deno, .NET, Maven, Gradle, Clojure, and sbt
|
|
99
|
+
surfaces are detected independently. A genuinely multi-runtime project receives collision-free
|
|
100
|
+
stages for every applicable adapter. Doctor dependency actions remain bound to the ecosystem
|
|
101
|
+
declared by their evidence so an npm finding cannot accidentally trigger an unrelated Python
|
|
102
|
+
transaction. If a manifest, required executable, isolated environment, project-declared
|
|
103
|
+
validation, or audit surface is unavailable, the engine returns `decision-required`; it never
|
|
104
|
+
hides the gap behind a model fallback.
|
|
96
105
|
|
|
97
106
|
## Consumer contract
|
|
98
107
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "workspai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.54.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Open-source workspace intelligence CLI for software systems: create, adopt, govern, verify, and align polyglot workspaces for humans, CI, IDEs, and AI agents.",
|
|
6
6
|
"keywords": [
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{b as AUTOPILOT_RELEASE_ALIAS_FILENAME,a as AUTOPILOT_RELEASE_LAST_RUN_FILENAME,c as runAutopilotRelease}from'./chunk-HOVJUP7K.js';
|
package/dist/chunk-SUV7Y2FH.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a as a$2}from'./chunk-ZTKIBREF.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 V from'fs-extra';var z=[{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 g(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 j(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))]}function C(e,t,a){return a?t:w.relative(e,t).split(w.sep).join("/")}function L(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 o=n.startsWith(" ")?" ":"",i=n.endsWith(" ")?" ":"";return `${o}--ci --json${i}`}).trim();let a=/(?:^|\s)--ci(?:\s|$)/.test(t)?t:`${t} --ci`;return /(?:^|\s)--json(?:\s|$)/.test(a)?a:`${a} --json`}function F(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 q(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 W(e){let t=e.payload,a=k(t.blockers),n=k(t.blockingReasons),o=k(t.failures),i=k(t.reasons),c=k(t.policyViolations),s=g(t.summary),p=k(s?.blockers);if(e.artifactKind==="analyze"){let r=(Array.isArray(t.findings)?t.findings:[]).map(l=>g(l)).filter(l=>!!l).map(l=>String(l.message??l.title??l.id??"").trim()).filter(Boolean);return j([...a,...r,...n])}if(e.artifactKind==="workspace-run"){let f=g(t.stages),r=Object.entries(f??{}).flatMap(([l,u])=>{let h=g(u);return (Array.isArray(h?.projects)?h.projects:[]).map(m=>g(m)).filter(m=>!!m).filter(m=>m.status==="failed"||m.ok===false).map(m=>`${l}: ${String(m.project??m.name??"project")} failed`)});return j([...a,...r,...n])}return j([...a,...n,...o,...i,...c,...p])}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 J(e){return (Array.isArray(e.report.payload.steps)?e.report.payload.steps:[]).flatMap((a,n)=>{let o=g(a),i=typeof o?.id=="string"?o.id.trim():"",c=typeof o?.projectName=="string"?o.projectName.trim():"",s=typeof o?.projectPath=="string"?o.projectPath.trim():"",p=typeof o?.originalCommand=="string"?o.originalCommand.trim():"";if(!o||!i||!c||!s)return [];let f=g(o.studioStatus),r=f?.state==="ready"||f?.state==="review-required"||f?.state==="blocked"||f?.state==="guidance-only"?f.state:"guidance-only",l=o.risk==="safe"||o.risk==="guarded"||o.risk==="invasive"?o.risk:"guarded",u=g(o.preview),h=C(e.workspacePath,s,e.includeAbsolutePaths),y=E({capability:{...o,command:p},absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),m=T({capability:o,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),P=o.executableInCurrentEnvironment===true&&!!y,R=_({strategy:o.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),d=g(o.transaction),b=d?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(d):void 0;return b&&(b.projectPath=h),[A({id:`doctor.${i}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof u?.title=="string"&&u.title.trim()?u.title.trim():`Repair ${c}`,order:e.startOrder+n,phase:typeof o.phase=="string"?o.phase:"doctor-remediation",blocker:typeof u?.summary=="string"&&u.summary.trim()?u.summary.trim():`Doctor remediation is pending for ${c}.`,summary:typeof u?.summary=="string"&&u.summary.trim()?u.summary.trim():`Execute the CLI-authored Doctor step for ${c}.`,mode:P?"run-command":"manual-guidance",risk:l,status:r,...P&&y?{command:y}:{},...P&&m?{invocation:m}:{},verifyCommand:typeof o.verifyCommand=="string"&&o.verifyCommand.trim()?o.verifyCommand.trim():"npx workspai doctor project --json",files:k(o.files).map(v=>{let x=w.isAbsolute(v)?v:w.resolve(s,v);return C(e.workspacePath,x,e.includeAbsolutePaths)}),notes:[`Source Doctor step: ${i}`,...typeof f?.reason=="string"?[f.reason]:[]],scope:"project",projectName:c,projectPath:h,sourceStepId:i,dependsOn:k(o.dependsOn).map(v=>`doctor.${v}`),strategy:R,transaction:b,cwd:"project",...g(o.rollback)?.available===true?{rollback:{available:true,strategy:"manual"}}:{}})]})}function E(e){let t=typeof e.capability.command=="string"?e.capability.command.trim():"";if(e.includeAbsolutePaths&&t)return t;let a=U({operation:e.capability.operation,absoluteProjectPath:e.absoluteProjectPath});if(a)return a$2(a);let n=g(e.capability.invocation),o=typeof n?.executable=="string"?n.executable.trim():"",i=k(n?.args);if(o)return [o,...i].map(s=>/^[a-zA-Z0-9_./:@=+-]+$/.test(s)?s:JSON.stringify(s)).join(" ");if(!t)return;let c=e.absoluteProjectPath.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.replace(new RegExp(`^cd\\s+["']?${c}["']?\\s*&&\\s*`,"i"),"").replaceAll(e.absoluteProjectPath,".")}function T(e){let t=g(e.capability.invocation),a=typeof t?.executable=="string"?t.executable.trim():"",n=k(t?.args);if(!(!a||n.length!==(Array.isArray(t?.args)?t.args.length:0)))return {cwd:e.includeAbsolutePaths?e.absoluteProjectPath:".",executable:a,args:n}}function U(e){let t=g(e.operation);if(!t||typeof t.type!="string")return;let a=structuredClone(t);for(let n of ["path","sourcePath"]){let o=a[n];if(typeof o!="string")continue;let i=w.isAbsolute(o)?w.relative(e.absoluteProjectPath,o):o;if(!i||i===".."||i.startsWith(`..${w.sep}`)||w.isAbsolute(i))return;a[n]=i.split(w.sep).join("/");}return a}function _(e){if(!Array.isArray(e.strategy))return;let t=structuredClone(e.strategy);if(!e.includeAbsolutePaths)for(let a of t)a.invocation&&(a.invocation.cwd=".");return t}function H(e){let t=Array.isArray(e.report.payload.projects)?e.report.payload.projects:e.report.payload.project?[e.report.payload.project]:[],a=new Set,n=[];for(let o of t){let i=g(o);if(!i)continue;let c=typeof i.name=="string"?i.name.trim():"",s=typeof i.path=="string"?i.path.trim():"";if(!c||!s)continue;let p=Array.isArray(i.repairCapabilities)?i.repairCapabilities:Array.isArray(i.probes)?i.probes.map(f=>g(f)?.repairCapability).filter(f=>f!==void 0):[];for(let f of p){let r=g(f),l=typeof r?.id=="string"?r.id.trim():"";if(!r||!l)continue;let u=`${c}:${l}`;if(a.has(u))continue;a.add(u);let h=r.risk==="safe"||r.risk==="guarded"||r.risk==="invasive"?r.risk:"guarded",y=E({capability:r,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),m=T({capability:r,absoluteProjectPath:s,includeAbsolutePaths:e.includeAbsolutePaths}),P=r.status==="available"&&!!y,R=g(r.transaction),d=R?.schemaVersion==="workspai.doctor-dependency-repair-transaction.v1"?structuredClone(R):void 0;d&&(d.projectPath=C(e.workspacePath,s,e.includeAbsolutePaths));let b=_({strategy:r.strategy,includeAbsolutePaths:e.includeAbsolutePaths}),v=k(r.files).map(I=>C(e.workspacePath,I,e.includeAbsolutePaths)),x=y?n.find(I=>I.projectName===c&&I.command===y&&I.cwd==="project"):void 0;if(x){x.files=j([...x.files,...v]),x.notes=j([...x.notes,`Also satisfies Doctor capability: ${l}`]);continue}n.push(A({id:`doctor.${c}.${l}`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof r.title=="string"&&r.title.trim()?r.title.trim():`Repair ${c}`,order:e.startOrder+n.length,phase:d?"dependency-remediation":"doctor-remediation",blocker:typeof r.reason=="string"&&r.reason.trim()?r.reason.trim():`Doctor remediation is pending for ${c}.`,summary:typeof r.reason=="string"&&r.reason.trim()?r.reason.trim():`Execute the Doctor-authored repair capability for ${c}.`,mode:P?r.canEditFiles===true?"edit-file":"run-command":"manual-guidance",risk:h,status:P?"ready":r.status==="manual"?"guidance-only":"blocked",...y?{command:y}:{},...m?{invocation:m}:{},verifyCommand:typeof r.verifyCommand=="string"&&r.verifyCommand.trim()?r.verifyCommand.trim():"npx workspai doctor project --json",files:v,notes:[`Source Doctor capability: ${l}`,...k(r.limitations)],scope:"project",projectName:c,projectPath:C(e.workspacePath,s,e.includeAbsolutePaths),sourceStepId:l,strategy:b,transaction:d,cwd:"project",...r.operation?{rollback:{available:true,strategy:"manual"}}:{}}));}}return n}function Z(e){let t=[],a=L("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:a,verifyCommand:a})),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:a,files:[e$1.compatibilityMatrix],operation:{type:"file-create",path:e$1.compatibilityMatrix,content:F(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:a,files:[".workspai/mirror-config.json"],operation:{type:"file-create",path:".workspai/mirror-config.json",content:q(e.generatedAt),overwrite:false}}));return t}function G(e){let t=Array.isArray(e.report.payload.steps)?e.report.payload.steps:[],a=[],n=new Map;for(let o of t){let i=g(o),c=g(i?.command),s=typeof i?.id=="string"?i.id.trim():"",p=typeof i?.project=="string"?i.project.trim():"",f=typeof i?.status=="string"?i.status:"",r=typeof c?.display=="string"?c.display.trim():"",l=i?.required===true;if(!s.startsWith("project.")||!p||!l||f!=="fail"&&f!=="missing"||!/^npx\s+workspai\s+workspace\s+run\s+/i.test(r))continue;let u=s.split(".").at(-1)??"stage",h=`workspaceVerify.${s}`,y=n.get(p),m=/(?:^|\s)--no-gates(?:\s|$)/.test(r)?r:`${r} --no-gates`;a.push(A({id:h,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:typeof i.label=="string"&&i.label.trim()?i.label.trim():`Run ${u} for ${p}`,order:e.startOrder+a.length,phase:"fleet-run",blocker:typeof i.message=="string"&&i.message.trim()?i.message.trim():`${u} evidence is not current for ${p}.`,summary:`Produce fresh ${u} evidence for ${p} without re-entering the blocked aggregate gates.`,mode:"run-command",risk:u==="start"?"guarded":"safe",status:"ready",command:m,verifyCommand:e.ciMode?"npx workspai workspace verify --strict --json":"npx workspai workspace verify --json",scope:"project",projectName:p,projectPath:p,sourceStepId:s,...y?{dependsOn:[y]}:{},cwd:"workspace",notes:[`Source Workspace Verify step: ${s}`,"Aggregate verification must run only after this project evidence producer completes."]})),n.set(p,h);}return a}function Q(e){let t=j(e.blockers.flatMap(n=>{let o=n.match(/(?:project runtimes?|workspace)\s*\(([^)]+)\)\s+(?:is|are) not pinned/i);return o?.[1]?o[1].split(",").map(i=>i.trim().toLowerCase()).filter(i=>/^(python|node|go|java|dotnet|rust|php)$/.test(i)):[]})),a=[];for(let n of t){let o=`readiness.toolchain.${n}.setup`,i=e.blockers.find(c=>c.toLowerCase().includes(`(${n})`))??`The ${n} runtime is not pinned in the canonical workspace toolchain.`;a.push(A({id:o,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Pin ${n} in the workspace toolchain`,order:e.startOrder+a.length,phase:"toolchain-reconciliation",blocker:i,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."]})),a.push(A({id:`readiness.toolchain.${n}.bootstrap`,artifactKind:e.report.artifactKind,cardId:e.report.cardId,title:`Reconcile the ${n} workspace foundation`,order:e.startOrder+a.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:[o]}));}return a}function X(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 a={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:a.title,order:e.order,phase:a.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:a.command,verifyCommand:a.verify,notes:e.report.artifactKind==="doctor-workspace"?["Read doctor-remediation-plan-last-run.json for ordered file-level steps."]:[]})}async function Y(e){let t=[a(e,".workspai/reports"),b(e,".workspai/reports")],a$1=[],n=new Set;for(let o of z)for(let i of o.fileNames){let c=(await Promise.all(t.map(s=>w.join(s,i)))).find(s=>existsSync(s));if(!(!c||n.has(`${o.artifactKind}:${i}`))){n.add(`${o.artifactKind}:${i}`);try{let s=await V.readJSON(c),p=g(s);if(!p)continue;a$1.push({artifactKind:o.artifactKind,cardId:o.cardId,fileName:i,absolutePath:c,payload:p});break}catch{a$1.push({artifactKind:o.artifactKind,cardId:o.cardId,fileName:i,absolutePath:c,payload:{blockers:[`${o.artifactKind}: report exists but could not be parsed.`]}});break}}}return a$1}async function de(e){let t=w.resolve(e.workspacePath),a$2=e.includeAbsolutePaths===true,n=e.ciMode===true,o=new Date().toISOString(),i=a(t,".workspai/reports"),c=await Y(t),s=[],p=1;for(let r of c){if(r.artifactKind==="doctor-workspace"){let d=Array.isArray(r.payload.steps)?J({report:r,workspacePath:t,includeAbsolutePaths:a$2,startOrder:p}):H({report:r,workspacePath:t,includeAbsolutePaths:a$2,startOrder:p});s.push(...d),p+=d.length;continue}let l=W(r);if(l.length===0)continue;if(r.artifactKind==="bootstrap-compliance"){s.push(...Z({blockers:l,generatedAt:o})),p=s.length+1;continue}if(r.artifactKind==="workspace-verify"){let d=G({report:r,startOrder:p,ciMode:n});if(d.length>0){s.push(...d),p+=d.length;continue}}if(r.artifactKind==="readiness"){let d=Q({report:r,blockers:l,startOrder:p,ciMode:n});if(d.length>0){s.push(...d),p+=d.length;continue}}let u=s.some(d=>d.transaction?.kind==="dependency-security"),h=r.artifactKind==="readiness"&&l.some(d=>/dependenc(?:y|ies).*vulnerabil|vulnerabil.*dependenc(?:y|ies)|security audit/i.test(d));if(u&&h)continue;let y=l[0],m=X({report:r,blocker:y,order:p,ciMode:n}),R={readiness:new Set(["bootstrap","doctor"]),pipeline:new Set(["bootstrap","doctor","analyze","readiness"]),workspaceVerify:new Set(["bootstrap","doctor","readiness","workspaceRun"])}[r.cardId];if(r.cardId==="pipeline"){let d=["doctor","analyze","readiness"].find(b=>y.toLowerCase().includes(b));d&&(R=new Set([d]));}if(R){let d=s.filter(b=>R.has(b.cardId)&&b.risk!=="invasive"&&b.status!=="blocked"&&b.status!=="guidance-only").map(b=>b.id);d.length>0&&(m.dependsOn=j([...m.dependsOn??[],...d]),m.notes.push("This aggregate gate must run after its contract-owned upstream remediation actions."));}l.length>1&&m.notes.push(...l.slice(1,8).map(d=>`Related blocker: ${d}`)),s.push(m),p+=1;}let f={safe:s.filter(r=>r.risk==="safe").length,guarded:s.filter(r=>r.risk==="guarded").length,invasive:s.filter(r=>r.risk==="invasive").length};return {schemaVersion:a$1,generatedAt:o,workspace:{name:w.basename(t),...a$2?{path:t}:{}},source:{command:"workspace remediation-plan",reportsDir:C(t,i,a$2),includeAbsolutePaths:a$2,ciMode:n},summary:{artifactsScanned:c.length,cardsCovered:j(s.map(r=>r.cardId)).length,totalActions:s.length,executableActions:s.filter(r=>r.status==="ready").length,risk:f},actions:s}}async function pe(e$2,t){return e(t,e$1.artifactRemediationPlan,e$2)}export{de as a,pe as b};
|
package/dist/chunk-ZTKIBREF.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import t from'path';function o(e){return `"${e.replace(/"/g,'\\"')}"`}function n(e){let r=`scripts.${e.scriptName}=${e.scriptValue}`;return `cd ${o(e.projectPath)} && npm pkg set ${o(r)}`}function s(e){return `workspai:doctor:repair ${Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}`}function d(e){let r=t.join(e.projectPath,e.relativePath),i={type:"file-create",path:r,content:e.content,overwrite:false};return {id:`${e.issueId}.file-create`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-create",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function g(e){let r=t.join(e.projectPath,e.relativePath),i={type:"file-append",path:r,lines:e.lines,ensureNewline:true};return {id:`${e.issueId}.file-append`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-append",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function m(e){let r=t.join(e.projectPath,e.sourceRelativePath),i=t.join(e.projectPath,e.targetRelativePath),a={type:"file-copy",sourcePath:r,path:i,overwrite:false};return {id:`${e.issueId}.file-copy`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-copy",risk:e.risk??"safe",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r,i],command:s(a),operation:a,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function u(e){return e.lint&&e.lint.trim().length>0?"npm run lint":e.build&&e.build.trim().length>0?"npm run build":null}function f(e){let r=`frontend-script-${e.scriptName}`,i=t.join(e.projectPath,"package.json"),a=["npx workspai doctor project --json","npx workspai workspace verify --json"];return e.scriptValue?{id:`${r}.package-json-script`,issueId:r,title:`Add package.json ${e.scriptName} script`,status:"available",fixKind:"package-json-script",risk:"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:false,files:[i],command:n({projectPath:e.projectPath,scriptName:e.scriptName,scriptValue:e.scriptValue}),operation:{type:"package-json-script",path:i,scriptName:e.scriptName,scriptValue:e.scriptValue},verifyCommand:"npx workspai doctor project --json",refreshCommands:a,reason:`Reuse the existing ${e.scriptValue} validation path as the ${e.scriptName} gate for ${e.frameworkDisplayName}.`}:{id:`${r}.manual`,issueId:r,title:`Define ${e.scriptName} script`,status:"manual",fixKind:"manual",risk:"guarded",canAutoFix:false,canEditFiles:false,requiresApproval:true,requiresReview:true,files:[i],refreshCommands:a,reason:`No safe ${e.frameworkDisplayName} fallback script could be inferred from existing package.json scripts.`,limitations:["Add a real test/lint/build command that matches the project quality gate before release."]}}function k(e){let r=t.join(e.projectPath,"package.json");return {id:`${e.issueId}.package-json-script`,issueId:e.issueId,title:e.title,status:"available",fixKind:"package-json-script",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??false,files:[r],command:n({projectPath:e.projectPath,scriptName:e.scriptName,scriptValue:e.scriptValue}),operation:{type:"package-json-script",path:r,scriptName:e.scriptName,scriptValue:e.scriptValue},verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function y(e){let r=t.join(e.projectPath,"Makefile"),i={type:"makefile-target",path:r,target:e.targetName,command:e.command,phony:true};return {id:`${e.issueId}.makefile-target`,issueId:e.issueId,title:e.title,status:"available",fixKind:"file-append",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:true,requiresApproval:true,requiresReview:e.requiresReview??true,files:[r],command:s(i),operation:i,verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}function v(e){return {id:`${e.issueId}.command`,issueId:e.issueId,title:e.title,status:"available",fixKind:e.fixKind??"command",risk:e.risk??"guarded",canAutoFix:true,canEditFiles:false,requiresApproval:true,requiresReview:e.requiresReview??true,files:e.files.map(r=>t.join(e.projectPath,r)),command:`cd ${o(e.projectPath)} && ${e.command}`,...e.invocation?{invocation:{cwd:e.projectPath,executable:e.invocation.executable,args:[...e.invocation.args]}}:{},...e.strategy?{strategy:e.strategy.map(r=>({...r}))}:{},...e.transaction?{transaction:structuredClone(e.transaction)}:{},verifyCommand:"npx workspai doctor project --json",refreshCommands:["npx workspai doctor project --json","npx workspai workspace verify --json"],reason:e.reason,limitations:e.limitations}}export{s as a,d as b,g as c,m as d,u as e,f,k as g,y as h,v as i};
|