workspai 0.60.1 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +92 -33
  2. package/contracts/analyze-last-run.v1.json +7 -1
  3. package/contracts/extension-cli-compatibility.v1.json +1 -1
  4. package/contracts/studio-card-repair-capabilities.v1.json +1 -1
  5. package/contracts/workspace-intelligence/agent-bootstrap-receipt.v1.json +31 -3
  6. package/contracts/workspace-intelligence/agent-customization-pack-report.v1.json +5 -1
  7. package/contracts/workspace-intelligence/agent-reports-index.v1.json +5 -1
  8. package/contracts/workspace-intelligence/project-agent-entry.v1.json +32 -4
  9. package/contracts/workspace-intelligence/project-context-agent.v1.json +34 -2
  10. package/contracts/workspace-intelligence/workspace-context.v1.json +4 -1
  11. package/contracts/workspace-intelligence/workspace-repair-transaction.v1.json +1 -0
  12. package/contracts/workspace-intelligence-chain.v1.json +4 -5
  13. package/dist/analyze-K6JDMF5C.js +1 -0
  14. package/dist/autopilot-release-GNTOXKIL.js +1 -0
  15. package/dist/{chunk-KNTPDRZB.js → chunk-3VU7ROHY.js} +1 -1
  16. package/dist/chunk-46USUSIK.js +49 -0
  17. package/dist/{chunk-S4CWUZ4K.js → chunk-BQCGULHR.js} +1 -1
  18. package/dist/{chunk-TYQMO36U.js → chunk-JNPXLZA6.js} +1 -1
  19. package/dist/{chunk-WQX3JYEP.js → chunk-LNXIMF3O.js} +1 -1
  20. package/dist/{chunk-AJ535F22.js → chunk-MWCKJOOU.js} +14 -12
  21. package/dist/{chunk-WUB6QGC7.js → chunk-PKKP5H3T.js} +1 -1
  22. package/dist/{chunk-WLFJHRB3.js → chunk-PPQL5UTI.js} +1 -1
  23. package/dist/{chunk-MDF2FBLS.js → chunk-SS7NJMFL.js} +1 -1
  24. package/dist/{chunk-KTW4EN47.js → chunk-TR6OFSJM.js} +1 -1
  25. package/dist/chunk-TVCJKE2U.js +2 -0
  26. package/dist/chunk-UZNACYV7.js +2 -0
  27. package/dist/{chunk-VV55EAWO.js → chunk-VDEFHP6I.js} +1 -1
  28. package/dist/chunk-VRQLHCE2.js +8 -0
  29. package/dist/chunk-YUGKQ44M.js +1 -0
  30. package/dist/{create-ZLDOBXG4.js → create-CKUQRSJF.js} +1 -1
  31. package/dist/{goal-lifecycle-OV6NZDD6.js → goal-lifecycle-7L5JFYOI.js} +1 -1
  32. package/dist/{goal-pack-Q3O2Z7R5.js → goal-pack-SGHXUPMU.js} +1 -1
  33. package/dist/index.js +19 -19
  34. package/dist/{pipeline-NICVJLZF.js → pipeline-W2CKUZBS.js} +1 -1
  35. package/dist/{project-agent-entry-DVPKQST7.js → project-agent-entry-66GTQQPX.js} +1 -1
  36. package/dist/{project-intelligence-lens-RLYSPJB2.js → project-intelligence-lens-NWNWLJMB.js} +1 -1
  37. package/dist/{verified-goal-2BRQZQBL.js → verified-goal-AY5VU6LG.js} +1 -1
  38. package/dist/{workspace-LQ77WAHC.js → workspace-FSOLFNAJ.js} +1 -1
  39. package/dist/workspace-agent-sync-ZURWHL3H.js +1 -0
  40. package/dist/{workspace-context-YAK5XX27.js → workspace-context-DPDGFTWJ.js} +1 -1
  41. package/dist/workspace-explain-OU2PEVYO.js +1 -0
  42. package/dist/{workspace-explain-contract-ZL4NMLZI.js → workspace-explain-contract-V2IVSROX.js} +1 -1
  43. package/dist/{workspace-foundation-G4KPT5CN.js → workspace-foundation-PPZKC36U.js} +1 -1
  44. package/dist/{workspace-intelligence-runner-T6CVJIQQ.js → workspace-intelligence-runner-7RIOUCCM.js} +1 -1
  45. package/dist/{workspace-mcp-serve-ALIZV72K.js → workspace-mcp-serve-PYKYJIE6.js} +1 -1
  46. package/dist/{workspace-onboarding-46BE3EQD.js → workspace-onboarding-RP3RZ3CC.js} +1 -1
  47. package/dist/{workspace-readme-56YZ4EAZ.js → workspace-readme-G7TZ3V5T.js} +1 -1
  48. package/dist/workspace-repair-engine-L47XZXYZ.js +3 -0
  49. package/dist/workspace-run-QV5ER2VW.js +1 -0
  50. package/docs/README.md +16 -14
  51. package/docs/agent-entry.md +32 -2
  52. package/docs/ci-workflows.md +1 -1
  53. package/docs/workspace-repair-engine.md +48 -2
  54. package/package.json +1 -1
  55. package/dist/analyze-FYNMI5KT.js +0 -1
  56. package/dist/autopilot-release-IRXB2VOH.js +0 -1
  57. package/dist/chunk-7ITSLGPZ.js +0 -8
  58. package/dist/chunk-I2O6AC2Z.js +0 -2
  59. package/dist/chunk-KBR4Y4RW.js +0 -1
  60. package/dist/chunk-NRVSDL4J.js +0 -39
  61. package/dist/chunk-OU7DF6MP.js +0 -2
  62. package/dist/workspace-agent-sync-YLP75OWF.js +0 -1
  63. package/dist/workspace-explain-QH4FXQW5.js +0 -1
  64. package/dist/workspace-repair-engine-SZZKV3JF.js +0 -3
  65. package/dist/workspace-run-JTEFCQYQ.js +0 -1
  66. /package/dist/{chunk-HQWDW2BV.js → chunk-GGOQHTZV.js} +0 -0
@@ -1,4 +1,4 @@
1
- import {c}from'./chunk-TYQMO36U.js';import {r}from'./chunk-VDFHUYAQ.js';import {a as a$2}from'./chunk-7ITSLGPZ.js';import {c as c$1}from'./chunk-LPCWROQ3.js';import {a as a$3}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-WUB6QGC7.js';import {f,e as e$1}from'./chunk-ILIBOMYL.js';import {a}from'./chunk-QJCCZLOF.js';import {c as c$3}from'./chunk-X7FYEKLI.js';import {d as d$1,a as a$1,e as e$2}from'./chunk-CCDGHPEJ.js';import {e,i,h}from'./chunk-NZ3WZYD5.js';import c$2 from'chalk';import d from'path';import G from'fs-extra';function L(s){return s===0?"pass":s===2?"warn":"fail"}async function _(s){try{let a=G.readJsonSync(s),i=a.policyProfile,t=c$3(a).filter(n=>n.status==="blocking").map(n=>`${n.projectName}: ${n.message}`);return {policyProfile:typeof i?.name=="string"?i.name:void 0,blockers:[...new Set(t)].slice(0,12)}}catch{return {blockers:[]}}}function j(s){return s.some(a=>a.status==="fail")?"blocked":s.some(a=>a.status==="warn")?"needs-attention":"ready"}function V(s,a){if(a)return 3;let i=s.some(n=>n.status==="fail"),t=s.some(n=>n.status==="warn");return i?1:t?2:0}function K(s,a){return s===2&&!a?0:s}async function J(s){let a=await g(s,true),i=false;try{let{syncWorkspaceContract:t}=await import('./workspace-contract-3BWIRSVQ.js');await t({workspacePath:s}),i=true;}catch{i=false;}return {sync:a,contractSynced:i}}async function U(s={}){let a$4=d.resolve(s.workspacePath??process.cwd()),i$1=a(a$4);if(!i$1)throw new Error("No Workspai workspace found in current directory or parents");let t=[],n=[],u=false,m,w,g,h$1=Date.now();try{let{sync:e,contractSynced:r}=await J(i$1),o=e.workspaceFound&&(e.added.length>0||e.skipped>=0)||e.workspaceFound?"pass":"warn";t.push({name:"sync",status:o,durationMs:Date.now()-h$1,summary:e.workspaceFound?`registry sync complete (${e.added.length} added, ${e.skipped} existing)${r?", contract synced":""}`:"workspace not registered in global registry; contract sync attempted"}),e.workspaceFound||n.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()-h$1,summary:`sync failed: ${e instanceof Error?e.message:String(e)}`}),n.push("workspace sync stage failed");}let P=Date.now();try{let e$1=await r({workspace:true,json:true,quiet:true,strict:s.strict===true,ci:s.strict!==true}),r$1=L(e$1),o=await d$1(i$1,e.doctor)??a$1(i$1,e.doctor),l=await _(o);t.push({name:"doctor",status:r$1,durationMs:Date.now()-P,summary:r$1==="pass"?"doctor workspace passed":r$1==="warn"?"doctor workspace reported warnings":"doctor workspace did not pass",exitCode:e$1,evidencePath:o,policyProfile:l.policyProfile,blockers:l.blockers}),r$1==="fail"?n.push(...l.blockers.length>0?l.blockers.map(O=>`doctor: ${O}`):["doctor workspace gate failed"]):r$1==="warn"&&n.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)}`}),n.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 r=await a$2({workspacePath:i$1,json:true,strict:s.strict===true});m=d.isAbsolute(r.enterpriseControls.evidencePath)?r.enterpriseControls.evidencePath:d.join(i$1,r.enterpriseControls.evidencePath);let o=r.summary.verdict==="blocked"?"fail":r.summary.verdict==="needs-attention"?"warn":"pass";t.push({name:"analyze",status:o,durationMs:Date.now()-e,summary:`analyze verdict: ${r.summary.verdict} (score ${r.summary.score}/100)`,evidencePath:m}),o==="fail"?n.push("analyze reported blocked verdict"):o==="warn"&&n.push("analyze reported needs-attention verdict");}catch(r){u=true,t.push({name:"analyze",status:"fail",durationMs:Date.now()-e,summary:`analyze failed: ${r instanceof Error?r.message:String(r)}`}),n.push("analyze stage failed");}}let k=Date.now();try{let e=await a$3({startPath:i$1,writeReport:true,skipVerify:s.skipVerify===true});w=e.evidencePath;let r=e.overallStatus==="pass"?"pass":e.overallStatus==="warn"?"warn":"fail";t.push({name:"readiness",status:r,durationMs:Date.now()-k,summary:`readiness overall: ${e.overallStatus}`,evidencePath:e.evidencePath}),r==="fail"?n.push(...e.blockingReasons.map(o=>`readiness: ${o}`)):r==="warn"&&n.push(...e.gates.filter(o=>o.status==="warn").map(o=>`readiness warn: ${o.gate}: ${o.summary}`));}catch(e){u=true,t.push({name:"readiness",status:"fail",durationMs:Date.now()-k,summary:`readiness failed: ${e instanceof Error?e.message:String(e)}`}),n.push("readiness stage failed");}if(s.skipAutopilot)t.push({name:"autopilot",status:"skipped",durationMs:0,summary:"autopilot stage skipped"});else {let e=Date.now(),r=s.autopilotMode??"audit";try{let o=await c({workspacePath:i$1,mode:r,json:true,skipPipelineStages:true});g=o.artifacts.reportPath;let l=o.summary.verdict==="approved"?"pass":o.summary.verdict==="partial"?"warn":"fail";t.push({name:"autopilot",status:l,durationMs:Date.now()-e,summary:`autopilot ${r}: ${o.summary.verdict}`,exitCode:o.summary.exitCode,evidencePath:g}),l!=="pass"&&n.push(...o.blockingReasons.slice(0,5));}catch(o){u=true,t.push({name:"autopilot",status:"fail",durationMs:Date.now()-e,summary:`autopilot failed: ${o instanceof Error?o.message:String(o)}`}),n.push("autopilot release stage failed");}}let N=j(t),S=V(t,u),I=d.join(i$1,i.pipelineLastRun),p={schemaVersion:h.pipelineLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:i$1,summary:{verdict:N,exitCode:S,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(n)],artifacts:{reportPath:I,analyzeEvidencePath:m,readinessEvidencePath:w,autopilotEvidencePath:g}};if(s.writeReport!==false){let e=f(p,{commandId:"workspacePipeline",exitCode:S,generatedAt:p.generatedAt,blockers:p.blockingReasons,runId:e$1()});await e$2(i$1,i.pipelineLastRun,e);}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-YLP75OWF.js'),r=await e({workspacePath:i$1,write:true,refreshContext:true,strict:false});p.agentGrounding={indexPath:r.indexPath,writtenFiles:r.writtenFiles,blockers:r.blockers};}catch{}return p}async function ue(s){let a;try{a=await U(s);}catch(t){let n=t instanceof Error?t.message:String(t);s.json?console.log(JSON.stringify(c$1({operation:"pipeline",code:"pipeline.failed",message:n}),null,2)):console.log(c$2.red(`Pipeline failed: ${n}`)),process.exit(1);}if(s.json)console.log(JSON.stringify(a,null,2));else {console.log(c$2.bold.cyan(`
1
+ import {c}from'./chunk-JNPXLZA6.js';import {r}from'./chunk-VDFHUYAQ.js';import {a as a$2}from'./chunk-VRQLHCE2.js';import {c as c$1}from'./chunk-LPCWROQ3.js';import {a as a$3}from'./chunk-GPGEJVVO.js';import {g}from'./chunk-PKKP5H3T.js';import {f,e as e$1}from'./chunk-ILIBOMYL.js';import {a}from'./chunk-QJCCZLOF.js';import {c as c$3}from'./chunk-X7FYEKLI.js';import {d as d$1,a as a$1,e as e$2}from'./chunk-CCDGHPEJ.js';import {e,i,h}from'./chunk-NZ3WZYD5.js';import c$2 from'chalk';import d from'path';import G from'fs-extra';function L(s){return s===0?"pass":s===2?"warn":"fail"}async function _(s){try{let a=G.readJsonSync(s),i=a.policyProfile,t=c$3(a).filter(n=>n.status==="blocking").map(n=>`${n.projectName}: ${n.message}`);return {policyProfile:typeof i?.name=="string"?i.name:void 0,blockers:[...new Set(t)].slice(0,12)}}catch{return {blockers:[]}}}function j(s){return s.some(a=>a.status==="fail")?"blocked":s.some(a=>a.status==="warn")?"needs-attention":"ready"}function V(s,a){if(a)return 3;let i=s.some(n=>n.status==="fail"),t=s.some(n=>n.status==="warn");return i?1:t?2:0}function K(s,a){return s===2&&!a?0:s}async function J(s){let a=await g(s,true),i=false;try{let{syncWorkspaceContract:t}=await import('./workspace-contract-3BWIRSVQ.js');await t({workspacePath:s}),i=true;}catch{i=false;}return {sync:a,contractSynced:i}}async function U(s={}){let a$4=d.resolve(s.workspacePath??process.cwd()),i$1=a(a$4);if(!i$1)throw new Error("No Workspai workspace found in current directory or parents");let t=[],n=[],u=false,m,w,g,h$1=Date.now();try{let{sync:e,contractSynced:r}=await J(i$1),o=e.workspaceFound&&(e.added.length>0||e.skipped>=0)||e.workspaceFound?"pass":"warn";t.push({name:"sync",status:o,durationMs:Date.now()-h$1,summary:e.workspaceFound?`registry sync complete (${e.added.length} added, ${e.skipped} existing)${r?", contract synced":""}`:"workspace not registered in global registry; contract sync attempted"}),e.workspaceFound||n.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()-h$1,summary:`sync failed: ${e instanceof Error?e.message:String(e)}`}),n.push("workspace sync stage failed");}let P=Date.now();try{let e$1=await r({workspace:true,json:true,quiet:true,strict:s.strict===true,ci:s.strict!==true}),r$1=L(e$1),o=await d$1(i$1,e.doctor)??a$1(i$1,e.doctor),l=await _(o);t.push({name:"doctor",status:r$1,durationMs:Date.now()-P,summary:r$1==="pass"?"doctor workspace passed":r$1==="warn"?"doctor workspace reported warnings":"doctor workspace did not pass",exitCode:e$1,evidencePath:o,policyProfile:l.policyProfile,blockers:l.blockers}),r$1==="fail"?n.push(...l.blockers.length>0?l.blockers.map(O=>`doctor: ${O}`):["doctor workspace gate failed"]):r$1==="warn"&&n.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)}`}),n.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 r=await a$2({workspacePath:i$1,json:true,strict:s.strict===true});m=d.isAbsolute(r.enterpriseControls.evidencePath)?r.enterpriseControls.evidencePath:d.join(i$1,r.enterpriseControls.evidencePath);let o=r.summary.verdict==="blocked"?"fail":r.summary.verdict==="needs-attention"?"warn":"pass";t.push({name:"analyze",status:o,durationMs:Date.now()-e,summary:`analyze verdict: ${r.summary.verdict} (score ${r.summary.score}/100)`,evidencePath:m}),o==="fail"?n.push("analyze reported blocked verdict"):o==="warn"&&n.push("analyze reported needs-attention verdict");}catch(r){u=true,t.push({name:"analyze",status:"fail",durationMs:Date.now()-e,summary:`analyze failed: ${r instanceof Error?r.message:String(r)}`}),n.push("analyze stage failed");}}let k=Date.now();try{let e=await a$3({startPath:i$1,writeReport:true,skipVerify:s.skipVerify===true});w=e.evidencePath;let r=e.overallStatus==="pass"?"pass":e.overallStatus==="warn"?"warn":"fail";t.push({name:"readiness",status:r,durationMs:Date.now()-k,summary:`readiness overall: ${e.overallStatus}`,evidencePath:e.evidencePath}),r==="fail"?n.push(...e.blockingReasons.map(o=>`readiness: ${o}`)):r==="warn"&&n.push(...e.gates.filter(o=>o.status==="warn").map(o=>`readiness warn: ${o.gate}: ${o.summary}`));}catch(e){u=true,t.push({name:"readiness",status:"fail",durationMs:Date.now()-k,summary:`readiness failed: ${e instanceof Error?e.message:String(e)}`}),n.push("readiness stage failed");}if(s.skipAutopilot)t.push({name:"autopilot",status:"skipped",durationMs:0,summary:"autopilot stage skipped"});else {let e=Date.now(),r=s.autopilotMode??"audit";try{let o=await c({workspacePath:i$1,mode:r,json:true,skipPipelineStages:true});g=o.artifacts.reportPath;let l=o.summary.verdict==="approved"?"pass":o.summary.verdict==="partial"?"warn":"fail";t.push({name:"autopilot",status:l,durationMs:Date.now()-e,summary:`autopilot ${r}: ${o.summary.verdict}`,exitCode:o.summary.exitCode,evidencePath:g}),l!=="pass"&&n.push(...o.blockingReasons.slice(0,5));}catch(o){u=true,t.push({name:"autopilot",status:"fail",durationMs:Date.now()-e,summary:`autopilot failed: ${o instanceof Error?o.message:String(o)}`}),n.push("autopilot release stage failed");}}let N=j(t),S=V(t,u),I=d.join(i$1,i.pipelineLastRun),p={schemaVersion:h.pipelineLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:i$1,summary:{verdict:N,exitCode:S,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(n)],artifacts:{reportPath:I,analyzeEvidencePath:m,readinessEvidencePath:w,autopilotEvidencePath:g}};if(s.writeReport!==false){let e=f(p,{commandId:"workspacePipeline",exitCode:S,generatedAt:p.generatedAt,blockers:p.blockingReasons,runId:e$1()});await e$2(i$1,i.pipelineLastRun,e);}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-ZURWHL3H.js'),r=await e({workspacePath:i$1,write:true,refreshContext:true,strict:false});p.agentGrounding={indexPath:r.indexPath,writtenFiles:r.writtenFiles,blockers:r.blockers};}catch{}return p}async function ue(s){let a;try{a=await U(s);}catch(t){let n=t instanceof Error?t.message:String(t);s.json?console.log(JSON.stringify(c$1({operation:"pipeline",code:"pipeline.failed",message:n}),null,2)):console.log(c$2.red(`Pipeline failed: ${n}`)),process.exit(1);}if(s.json)console.log(JSON.stringify(a,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(d.basename(a.workspacePath))}`)),console.log(c$2.gray(`Path: ${a.workspacePath}`)),console.log(c$2.white(`Verdict: ${a.summary.verdict} Exit: ${a.summary.exitCode} (${a.summary.stagesPassed} pass / ${a.summary.stagesWarn} warn / ${a.summary.stagesFailed} fail)`));for(let t of a.stages){let n=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}: ${n} ${t.summary}`);}if(a.blockingReasons.length>0){console.log(c$2.bold(`
4
4
  Blocking reasons:`));for(let t of a.blockingReasons.slice(0,8))console.log(c$2.gray(` \u2022 ${t}`));}console.log(c$2.gray(`
@@ -1 +1 @@
1
- export{c as AGENT_BOOTSTRAP_RECEIPT_SCHEMA_VERSION,f as AGENT_ENTRY_HOST_IDS,g as PROJECT_AGENT_ADAPTER_ENTRY_FILES,b as PROJECT_AGENT_ENTRY_RELATIVE_PATH,a as PROJECT_AGENT_ENTRY_SCHEMA_VERSION,e as WORKSPAI_AGENT_ENTRY_END,d as WORKSPAI_AGENT_ENTRY_START,j as buildAgentBootstrapReceipt,i as buildProjectAgentEntryManifest,h as normalizeAgentEntryHost}from'./chunk-I2O6AC2Z.js';
1
+ export{c as AGENT_BOOTSTRAP_RECEIPT_SCHEMA_VERSION,f as AGENT_ENTRY_HOST_IDS,g as PROJECT_AGENT_ADAPTER_ENTRY_FILES,b as PROJECT_AGENT_ENTRY_RELATIVE_PATH,a as PROJECT_AGENT_ENTRY_SCHEMA_VERSION,e as WORKSPAI_AGENT_ENTRY_END,d as WORKSPAI_AGENT_ENTRY_START,j as buildAgentBootstrapReceipt,i as buildProjectAgentEntryManifest,h as normalizeAgentEntryHost}from'./chunk-UZNACYV7.js';
@@ -1 +1 @@
1
- export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-AJ535F22.js';
1
+ export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-MWCKJOOU.js';
@@ -1 +1 @@
1
- import {d as d$1}from'./chunk-DIJGQUEV.js';import {a as a$2}from'./chunk-HQWDW2BV.js';import {c}from'./chunk-MDF2FBLS.js';import {a as a$1}from'./chunk-GPGEJVVO.js';import {p}from'./chunk-NA2NXX5P.js';import {a as a$3}from'./chunk-GR6442P7.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {a}from'./chunk-AFIFZTOY.js';import {e,f}from'./chunk-NZ3WZYD5.js';import {createHash}from'crypto';import u from'path';import v from'fs-extra';var W="workspai.verified-goal.v1",A=f.verifiedGoalStatus,V=e.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",$="contracts/workspace-intelligence/verified-goal-status.v1.json";function H(e,t,a){if(t.kind==="workspace")return true;let r=u.resolve(e,a.path);return t.kind==="project"?a.name===t.projectName||r===u.resolve(t.projectPath):t.projects.some(i=>i.projectName===a.name||u.resolve(i.projectPath)===r)}function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${x(a)}`).join(",")}}`:JSON.stringify(e)}function K(e){return createHash("sha256").update(x(e)).digest("hex")}var ae=["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"],re=new Set(ae.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 re.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function ie(e){let t=[e],a=[],r=0;for(;t.length>0;){let i=t.shift();if(i===void 0)break;let o=await v.readdir(i,{withFileTypes:true});if(o.sort((n,s)=>n.name.localeCompare(s.name)),r+=o.length,r>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 o){let s=u.join(i,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$3(n.name)&&t.push(s);continue}n.isFile()&&ne(n.name)&&a.push(s);}}return a}function oe(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 z(e){try{let t=JSON.parse(e),a={};for(let r of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=t[r];if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,n]of Object.entries(i))typeof n=="string"&&(a[`${r}:${o}`]=n);}return a}catch{return}}async function U(e,t){let r=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(o=>H(e,t,o)),i=new Map;for(let o of r){let n=u.resolve(e,o.path),s=await ie(n);for(let c of s){let g=u.basename(c),f=await v.readFile(c,"utf8"),p=u.relative(e,c).split(u.sep).join("/");i.set(p,{path:p,ecosystem:oe(g),sha256:createHash("sha256").update(f).digest("hex"),...g==="package.json"?{dependencies:z(f)??{}}:{}});}}return {manifests:[...i.values()].sort((o,n)=>o.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 ce(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=[],r=await U(e.workspace.path,e.scope),i=new Map(r.manifests.map(s=>[s.path,s])),o=new Map(t.manifests.map(s=>[s.path,s])),n=new Set;for(let s of t.manifests){let c=i.get(s.path);(!c||c.sha256!==s.sha256)&&n.add(s.path);}for(let s of r.manifests)o.has(s.path)||n.add(s.path);for(let s of r.manifests)!o.has(s.path)&&!S(s.path)&&a.push(`${s.path} was added after the safety baseline`);for(let s of t.manifests){let c=i.get(s.path);if(!c){a.push(`${s.path} was removed`);continue}if(c.sha256===s.sha256)continue;if(s.dependencies){let p=await v.readFile(u.join(e.workspace.path,s.path),"utf8"),m=z(p);if(!m){a.push(`${s.path} is not valid dependency JSON`);continue}for(let[d,l]of Object.entries(s.dependencies)){let h=m[d];if(!h){a.push(`${d.replace(/^[^:]+:/,"")} was removed`);continue}if(h===l)continue;let G=O(l),R=O(h);(G===null||R===null||G!==R||/(?:latest|\*)/i.test(h))&&a.push(`${d.replace(/^[^:]+:/,"")} changed outside its proven major range (${l} \u2192 ${h})`);}continue}if(S(s.path))continue;let g=u.posix.dirname(s.path);[...i.values()].some(p=>{let m=u.posix.dirname(p.path);return p.ecosystem===s.ecosystem&&(m===g||g.startsWith(`${m}/`))&&S(p.path)&&n.has(p.path)})||a.push(`${s.path} changed without a matching reconciled ${s.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=u.join(e,".workspai","goals",t);return {directory:a,goal:u.join(a,"goal.json"),status:u.join(a,"status.json"),latestReport:u.join(e,V)}}function le(e){return {workspacePath:u.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,...e.criteria.kind==="test-coverage"&&e.criteria.runtime?{runtime:e.criteria.runtime}:{},constraints:e.constraints}}async function C(e,t){await v.ensureDir(u.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await v.writeJson(a,t,{spaces:2}),await v.rename(a,e);}async function ue(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let r=a.startsWith("projects:")?"projects:":a.startsWith("project:")&&a.slice(8).includes(",")?"project:":null,i=a.startsWith("project:")?a.slice(8).trim():r?a.slice(r.length).trim():a;if(!i)throw new Error("Project goal scope must name a project.");let o=await p({workspacePath:e,includeAbsolutePaths:true});if(r){let g=i.split(",").map(p=>p.trim()).filter(Boolean);if(g.length<2||new Set(g).size!==g.length)throw new Error("A project-set goal scope must name at least two unique projects.");return {scope:{kind:"project-set",projects:g.map(p=>{let m=o.projects.filter(d=>d.name===p||d.path===p);if(m.length!==1)throw new Error(m.length===0?`Project goal scope was not found: ${p}`:`Project goal scope is ambiguous: ${p}`);return m[0]}).map(p=>({projectName:p.name,projectPath:u.resolve(e,p.path)})).sort((p,m)=>p.projectName.localeCompare(m.projectName))}}}let n=o.projects.filter(g=>{let f=u.resolve(e,g.path);return g.name===i||g.path===i||f===u.resolve(i)});if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found: ${i}`:`Project goal scope is ambiguous: ${i}`);let s=n[0],c=u.resolve(e,s.path);return {project:s,scope:{kind:"project",projectName:s.name,projectPath:c}}}function Y(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function X(e){if(!e)return null;try{let t=await v.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 pe(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function Q(e$1,t){let a=await d(e$1,e.doctor),r=await X(a);if(!r)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let i=de(r).filter(c=>{if(t.kind==="workspace")return true;let g=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?u.resolve(c.path):typeof c.projectPath=="string"?u.resolve(c.projectPath):"";return t.kind==="project"?g===t.projectName||f===u.resolve(t.projectPath):t.projects.some(p=>p.projectName===g||u.resolve(p.projectPath)===f)}),o=i.map(pe).filter(c=>c!==null),n=o.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),s=i.length>0&&n.length===i.length?n.reduce((c,g)=>c+g,0):null;return {measuredAt:(()=>{let c=o.map(g=>g.generatedAt).filter(g=>typeof g=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:s,target:0,unit:"blocking-vulnerabilities",status:Y(s,0,"maximum"),evidencePaths:a?[a]:[],message:s===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${s} blocking dependency vulnerability finding(s) remain.`}}async function Z(e){let t=await a$1({startPath:e,writeReport:false}),a=t.gates.filter(i=>i.status==="pass").length,r=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:r,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(i=>i.evidencePath).filter(i=>typeof i=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${r-a} release readiness gate(s) still require work.`}}async function B(e){let t=await d$1({projectPath:e.projectPath,target:e.target,run:e.run,runtime:e.runtime}),r=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:r,target:e.target,unit:"percent",status:Y(r,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":r===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${r}% (target ${e.target}%).`}}}async function ee(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,runtime:e.runtime})}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=t.projects.filter(l=>H(e.workspacePath,e.scope,l)),r=e.runtime,i=r?a.filter(l=>l.runtimeCandidates.includes(r)):a;if(i.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:`The selected scope does not contain the ${e.runtime} coverage runtime.`}};let o=[];for(let l of i)o.push({projectName:l.name,result:await B({projectPath:u.resolve(e.workspacePath,l.path),target:e.target,run:e.run,runtime:e.runtime})});let n=o.filter(l=>l.result.executionStatus==="failed"),s=o.filter(l=>l.result.measurement.status==="unavailable"),c=o.filter(l=>l.result.measurement.status==="unsatisfied"),g=o.map(l=>l.result.measurement.value).filter(l=>l!==null),f=g.length===o.length&&g.length>0?Math.min(...g):null,p$1=n.length>0?"failed":s.length>0?"unavailable":c.length>0?"below-target":"passed",m=o.map(l=>l.result.measurement.measuredAt).sort(),d=[...n.map(l=>`${l.projectName}: coverage command failed`),...s.map(l=>`${l.projectName}: coverage unavailable`),...c.map(l=>`${l.projectName}: ${l.result.measurement.value??"unknown"}%`)];return {executionStatus:p$1,measurement:{measuredAt:m[m.length-1]??new Date().toISOString(),value:f,target:e.target,unit:"percent",status:p$1==="passed"?"satisfied":p$1==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(o.flatMap(l=>l.result.measurement.evidencePaths))],message:p$1==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${d.join("; ")}.`}}}function ge(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:e.scope.kind==="project-set"?`projects ${e.scope.projects.map(a=>a.projectName).join(", ")}`:"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 ${e.runtime?`${e.runtime} `:""}${t} test coverage to ${e.target??80}% without breaking its build.`}function me(e,t,a){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,...a?{runtime:a}:{}}}async function fe(e){return e.kind==="release-readiness"?Z(e.workspacePath):e.kind==="dependency-security"?Q(e.workspacePath,e.scope):(await ee({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false,runtime:e.runtime})).measurement}async function Ee(e){let t=u.resolve(e.workspacePath),a$1=Math.max(0,Math.min(100,Math.round(e.target??80))),{scope:r}=await ue(t,e.scope),i={workspacePath:u.resolve(t),kind:e.kind,scope:r,target:e.kind==="test-coverage"?a$1:null,...e.kind==="test-coverage"&&e.runtime?{runtime:e.runtime}:{},constraints:{allowBreakingChanges:e.allowBreakingChanges===true,allowForce:e.allowForce===true,requireBuild:e.requireBuild!==false,requireTests:e.requireTests!==false}},o=K(i),n=`goal-${e.kind}-${o.slice(0,16)}`,s=E(t,n);if(await v.pathExists(s.goal)){let{goal:m,status:d}=await te(t,n);if(m.fingerprint===o)return {goal:m,status:d,resumed:d.state!=="verified"}}let c=new Date().toISOString(),g=await fe({workspacePath:t,kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),f={schemaVersion:W,id:n,fingerprint:o,createdAt:c,updatedAt:c,workspace:{name:u.basename(t),path:t},scope:r,kind:e.kind,summary:ge({kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),constraints:i.constraints,criteria:me(e.kind,a$1,e.runtime),baseline:g,...e.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,r)}:{},artifactPaths:{goal:s.goal,status:s.status,latestReport:s.latestReport}},p={schemaVersion:A,goalId:n,goalFingerprint:o,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:g,checks:[],blockingReasons:[],evidencePaths:g.evidencePaths,nextActions:e.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e.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:s.status};return a(f,J,"Verified goal"),a(p,$,"Verified goal status"),await C(s.goal,f),await C(s.status,p),await e$1(t,V,p),{goal:f,status:p,resumed:false}}async function te(e,t){let a$1=E(u.resolve(e),t),r=await v.readJson(a$1.goal),i=await v.readJson(a$1.status);a(r,J,"Verified goal"),a(i,$,"Verified goal status");let o=u.resolve(e),n=u.resolve(r.artifactPaths.goal)===u.resolve(a$1.goal)&&u.resolve(r.artifactPaths.status)===u.resolve(a$1.status)&&u.resolve(r.artifactPaths.latestReport)===u.resolve(a$1.latestReport);if(r.schemaVersion!==W||i.schemaVersion!==A||r.id!==i.goalId||r.fingerprint!==i.goalFingerprint||r.fingerprint!==K(le(r))||u.resolve(r.workspace.path)!==o||u.resolve(i.workspacePath)!==o||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:r,status:i}}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"?[`project:${e.goal.scope.projectName}`]:e.goal.scope.kind==="project-set"?e.goal.scope.projects.map(r=>`project:${r.projectName}`):[void 0];for(let r of ["test","build"]){if(r==="test"&&e.includeTests===false)continue;if(!(r==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:r,label:`${r} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:r,label:`${r} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let o=false;for(let n of a){let s=await a$2({workspacePath:e.goal.workspace.path,stage:r,scope:n,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false}),c=n?.replace(/^project:/,"");if(t.push(k({id:c?`${r}:${c}`:r,label:c?`${r} validation \xB7 ${c}`:`${r} validation`,status:s.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${s.summary.exitCode}`,evidencePath:u.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),s.summary.exitCode!==0){o=true;break}}if(o)break}return t}async function Ge(e$2){let t=u.resolve(e$2.workspacePath),{goal:a$1,status:r}=await te(t,e$2.goalId),i=e$2.run!==false,o=[],n;if(i&&e$2.runIntelligence!==false){let d=await c({workspacePath:t,strict:true,agent:"generic"}),l=d.exitCode===0||d.exitCode===2,h=a$1.kind==="release-readiness";o.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:d.exitCode===0||d.exitCode===2&&!h?"passed":d.exitCode===2?"blocked":"failed",expected:"passed",actual:d.exitCode===2&&l&&!h?`${d.status}; canonical evidence refreshed for goal-scoped verification`:d.status,evidencePath:u.join(t,e.intelligenceRun)}));}if(a$1.kind==="release-readiness"){n=await Z(t),o.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:u.join(t,e.readiness)}));let d$1=await d(t,e.verify),l=await X(d$1),h=l?.summary&&typeof l.summary=="object"&&!Array.isArray(l.summary)?String(l.summary.verdict??"missing"):"missing";o.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:u.join(t,e.verify)}));}else if(a$1.kind==="dependency-security")n=await Q(t,a$1.scope),o.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]})),o.push(a$1.constraints.allowBreakingChanges||a$1.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$1.constraints.allowBreakingChanges}, allowForce=${a$1.constraints.allowForce}`}):await ce(a$1)),n.status==="satisfied"&&o.push(...await q({goal:a$1,run:i}));else {let d=a$1.criteria.kind==="test-coverage"?a$1.criteria.minimumPercent:a$1.baseline.target;if(d===null)throw new Error("Coverage goal does not have a valid target.");let l=await ee({workspacePath:t,scope:a$1.scope,target:d,run:i,runtime:a$1.criteria.kind==="test-coverage"?a$1.criteria.runtime:void 0});n=l.measurement,o.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${d}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),o.push(k({id:"test",label:"Coverage test execution",status:l.executionStatus==="failed"?"failed":l.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:l.executionStatus==="failed"?"coverage test command failed":l.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&o.push(...await q({goal:a$1,run:i,includeTests:false}));}let s=o.filter(d=>d.status==="blocked"||d.status==="failed"||d.status==="missing").map(d=>d.message),c$1=[...new Set([...n.evidencePaths,...o.map(d=>d.evidencePath).filter(d=>typeof d=="string")])],g=n.status==="satisfied"&&o.every(d=>d.status==="passed"||d.status==="skipped"),f=E(t,a$1.id),p=g?[]:a$1.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$1.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:A,goalId:a$1.id,goalFingerprint:a$1.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:g?"verified":o.some(d=>d.status==="failed")?"failed":"blocked",attempt:r.attempt+1,progress:n,checks:o,blockingReasons:s,evidencePaths:c$1,nextActions:p,artifactPath:f.status};return a(m,$,"Verified goal status"),await C(f.status,m),await e$1(t,V,m),m}export{V as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,A as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ee as planVerifiedGoal,te as readVerifiedGoal,Ge as verifyVerifiedGoal};
1
+ import {d as d$1}from'./chunk-DIJGQUEV.js';import {a as a$2}from'./chunk-GGOQHTZV.js';import {c}from'./chunk-SS7NJMFL.js';import {a as a$1}from'./chunk-GPGEJVVO.js';import {p}from'./chunk-NA2NXX5P.js';import {a as a$3}from'./chunk-GR6442P7.js';import {e as e$1,d}from'./chunk-CCDGHPEJ.js';import {a}from'./chunk-AFIFZTOY.js';import {e,f}from'./chunk-NZ3WZYD5.js';import {createHash}from'crypto';import u from'path';import v from'fs-extra';var W="workspai.verified-goal.v1",A=f.verifiedGoalStatus,V=e.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",$="contracts/workspace-intelligence/verified-goal-status.v1.json";function H(e,t,a){if(t.kind==="workspace")return true;let r=u.resolve(e,a.path);return t.kind==="project"?a.name===t.projectName||r===u.resolve(t.projectPath):t.projects.some(i=>i.projectName===a.name||u.resolve(i.projectPath)===r)}function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${x(a)}`).join(",")}}`:JSON.stringify(e)}function K(e){return createHash("sha256").update(x(e)).digest("hex")}var ae=["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"],re=new Set(ae.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 re.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function ie(e){let t=[e],a=[],r=0;for(;t.length>0;){let i=t.shift();if(i===void 0)break;let o=await v.readdir(i,{withFileTypes:true});if(o.sort((n,s)=>n.name.localeCompare(s.name)),r+=o.length,r>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 o){let s=u.join(i,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$3(n.name)&&t.push(s);continue}n.isFile()&&ne(n.name)&&a.push(s);}}return a}function oe(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 z(e){try{let t=JSON.parse(e),a={};for(let r of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=t[r];if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,n]of Object.entries(i))typeof n=="string"&&(a[`${r}:${o}`]=n);}return a}catch{return}}async function U(e,t){let r=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(o=>H(e,t,o)),i=new Map;for(let o of r){let n=u.resolve(e,o.path),s=await ie(n);for(let c of s){let g=u.basename(c),f=await v.readFile(c,"utf8"),p=u.relative(e,c).split(u.sep).join("/");i.set(p,{path:p,ecosystem:oe(g),sha256:createHash("sha256").update(f).digest("hex"),...g==="package.json"?{dependencies:z(f)??{}}:{}});}}return {manifests:[...i.values()].sort((o,n)=>o.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 ce(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=[],r=await U(e.workspace.path,e.scope),i=new Map(r.manifests.map(s=>[s.path,s])),o=new Map(t.manifests.map(s=>[s.path,s])),n=new Set;for(let s of t.manifests){let c=i.get(s.path);(!c||c.sha256!==s.sha256)&&n.add(s.path);}for(let s of r.manifests)o.has(s.path)||n.add(s.path);for(let s of r.manifests)!o.has(s.path)&&!S(s.path)&&a.push(`${s.path} was added after the safety baseline`);for(let s of t.manifests){let c=i.get(s.path);if(!c){a.push(`${s.path} was removed`);continue}if(c.sha256===s.sha256)continue;if(s.dependencies){let p=await v.readFile(u.join(e.workspace.path,s.path),"utf8"),m=z(p);if(!m){a.push(`${s.path} is not valid dependency JSON`);continue}for(let[d,l]of Object.entries(s.dependencies)){let h=m[d];if(!h){a.push(`${d.replace(/^[^:]+:/,"")} was removed`);continue}if(h===l)continue;let G=O(l),R=O(h);(G===null||R===null||G!==R||/(?:latest|\*)/i.test(h))&&a.push(`${d.replace(/^[^:]+:/,"")} changed outside its proven major range (${l} \u2192 ${h})`);}continue}if(S(s.path))continue;let g=u.posix.dirname(s.path);[...i.values()].some(p=>{let m=u.posix.dirname(p.path);return p.ecosystem===s.ecosystem&&(m===g||g.startsWith(`${m}/`))&&S(p.path)&&n.has(p.path)})||a.push(`${s.path} changed without a matching reconciled ${s.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=u.join(e,".workspai","goals",t);return {directory:a,goal:u.join(a,"goal.json"),status:u.join(a,"status.json"),latestReport:u.join(e,V)}}function le(e){return {workspacePath:u.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,...e.criteria.kind==="test-coverage"&&e.criteria.runtime?{runtime:e.criteria.runtime}:{},constraints:e.constraints}}async function C(e,t){await v.ensureDir(u.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await v.writeJson(a,t,{spaces:2}),await v.rename(a,e);}async function ue(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let r=a.startsWith("projects:")?"projects:":a.startsWith("project:")&&a.slice(8).includes(",")?"project:":null,i=a.startsWith("project:")?a.slice(8).trim():r?a.slice(r.length).trim():a;if(!i)throw new Error("Project goal scope must name a project.");let o=await p({workspacePath:e,includeAbsolutePaths:true});if(r){let g=i.split(",").map(p=>p.trim()).filter(Boolean);if(g.length<2||new Set(g).size!==g.length)throw new Error("A project-set goal scope must name at least two unique projects.");return {scope:{kind:"project-set",projects:g.map(p=>{let m=o.projects.filter(d=>d.name===p||d.path===p);if(m.length!==1)throw new Error(m.length===0?`Project goal scope was not found: ${p}`:`Project goal scope is ambiguous: ${p}`);return m[0]}).map(p=>({projectName:p.name,projectPath:u.resolve(e,p.path)})).sort((p,m)=>p.projectName.localeCompare(m.projectName))}}}let n=o.projects.filter(g=>{let f=u.resolve(e,g.path);return g.name===i||g.path===i||f===u.resolve(i)});if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found: ${i}`:`Project goal scope is ambiguous: ${i}`);let s=n[0],c=u.resolve(e,s.path);return {project:s,scope:{kind:"project",projectName:s.name,projectPath:c}}}function Y(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function X(e){if(!e)return null;try{let t=await v.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 pe(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function Q(e$1,t){let a=await d(e$1,e.doctor),r=await X(a);if(!r)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let i=de(r).filter(c=>{if(t.kind==="workspace")return true;let g=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?u.resolve(c.path):typeof c.projectPath=="string"?u.resolve(c.projectPath):"";return t.kind==="project"?g===t.projectName||f===u.resolve(t.projectPath):t.projects.some(p=>p.projectName===g||u.resolve(p.projectPath)===f)}),o=i.map(pe).filter(c=>c!==null),n=o.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),s=i.length>0&&n.length===i.length?n.reduce((c,g)=>c+g,0):null;return {measuredAt:(()=>{let c=o.map(g=>g.generatedAt).filter(g=>typeof g=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:s,target:0,unit:"blocking-vulnerabilities",status:Y(s,0,"maximum"),evidencePaths:a?[a]:[],message:s===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${s} blocking dependency vulnerability finding(s) remain.`}}async function Z(e){let t=await a$1({startPath:e,writeReport:false}),a=t.gates.filter(i=>i.status==="pass").length,r=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:r,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(i=>i.evidencePath).filter(i=>typeof i=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${r-a} release readiness gate(s) still require work.`}}async function B(e){let t=await d$1({projectPath:e.projectPath,target:e.target,run:e.run,runtime:e.runtime}),r=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:r,target:e.target,unit:"percent",status:Y(r,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":r===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${r}% (target ${e.target}%).`}}}async function ee(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,runtime:e.runtime})}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=t.projects.filter(l=>H(e.workspacePath,e.scope,l)),r=e.runtime,i=r?a.filter(l=>l.runtimeCandidates.includes(r)):a;if(i.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:`The selected scope does not contain the ${e.runtime} coverage runtime.`}};let o=[];for(let l of i)o.push({projectName:l.name,result:await B({projectPath:u.resolve(e.workspacePath,l.path),target:e.target,run:e.run,runtime:e.runtime})});let n=o.filter(l=>l.result.executionStatus==="failed"),s=o.filter(l=>l.result.measurement.status==="unavailable"),c=o.filter(l=>l.result.measurement.status==="unsatisfied"),g=o.map(l=>l.result.measurement.value).filter(l=>l!==null),f=g.length===o.length&&g.length>0?Math.min(...g):null,p$1=n.length>0?"failed":s.length>0?"unavailable":c.length>0?"below-target":"passed",m=o.map(l=>l.result.measurement.measuredAt).sort(),d=[...n.map(l=>`${l.projectName}: coverage command failed`),...s.map(l=>`${l.projectName}: coverage unavailable`),...c.map(l=>`${l.projectName}: ${l.result.measurement.value??"unknown"}%`)];return {executionStatus:p$1,measurement:{measuredAt:m[m.length-1]??new Date().toISOString(),value:f,target:e.target,unit:"percent",status:p$1==="passed"?"satisfied":p$1==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(o.flatMap(l=>l.result.measurement.evidencePaths))],message:p$1==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${d.join("; ")}.`}}}function ge(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:e.scope.kind==="project-set"?`projects ${e.scope.projects.map(a=>a.projectName).join(", ")}`:"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 ${e.runtime?`${e.runtime} `:""}${t} test coverage to ${e.target??80}% without breaking its build.`}function me(e,t,a){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,...a?{runtime:a}:{}}}async function fe(e){return e.kind==="release-readiness"?Z(e.workspacePath):e.kind==="dependency-security"?Q(e.workspacePath,e.scope):(await ee({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false,runtime:e.runtime})).measurement}async function Ee(e){let t=u.resolve(e.workspacePath),a$1=Math.max(0,Math.min(100,Math.round(e.target??80))),{scope:r}=await ue(t,e.scope),i={workspacePath:u.resolve(t),kind:e.kind,scope:r,target:e.kind==="test-coverage"?a$1:null,...e.kind==="test-coverage"&&e.runtime?{runtime:e.runtime}:{},constraints:{allowBreakingChanges:e.allowBreakingChanges===true,allowForce:e.allowForce===true,requireBuild:e.requireBuild!==false,requireTests:e.requireTests!==false}},o=K(i),n=`goal-${e.kind}-${o.slice(0,16)}`,s=E(t,n);if(await v.pathExists(s.goal)){let{goal:m,status:d}=await te(t,n);if(m.fingerprint===o)return {goal:m,status:d,resumed:d.state!=="verified"}}let c=new Date().toISOString(),g=await fe({workspacePath:t,kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),f={schemaVersion:W,id:n,fingerprint:o,createdAt:c,updatedAt:c,workspace:{name:u.basename(t),path:t},scope:r,kind:e.kind,summary:ge({kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),constraints:i.constraints,criteria:me(e.kind,a$1,e.runtime),baseline:g,...e.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,r)}:{},artifactPaths:{goal:s.goal,status:s.status,latestReport:s.latestReport}},p={schemaVersion:A,goalId:n,goalFingerprint:o,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:g,checks:[],blockingReasons:[],evidencePaths:g.evidencePaths,nextActions:e.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e.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:s.status};return a(f,J,"Verified goal"),a(p,$,"Verified goal status"),await C(s.goal,f),await C(s.status,p),await e$1(t,V,p),{goal:f,status:p,resumed:false}}async function te(e,t){let a$1=E(u.resolve(e),t),r=await v.readJson(a$1.goal),i=await v.readJson(a$1.status);a(r,J,"Verified goal"),a(i,$,"Verified goal status");let o=u.resolve(e),n=u.resolve(r.artifactPaths.goal)===u.resolve(a$1.goal)&&u.resolve(r.artifactPaths.status)===u.resolve(a$1.status)&&u.resolve(r.artifactPaths.latestReport)===u.resolve(a$1.latestReport);if(r.schemaVersion!==W||i.schemaVersion!==A||r.id!==i.goalId||r.fingerprint!==i.goalFingerprint||r.fingerprint!==K(le(r))||u.resolve(r.workspace.path)!==o||u.resolve(i.workspacePath)!==o||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:r,status:i}}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"?[`project:${e.goal.scope.projectName}`]:e.goal.scope.kind==="project-set"?e.goal.scope.projects.map(r=>`project:${r.projectName}`):[void 0];for(let r of ["test","build"]){if(r==="test"&&e.includeTests===false)continue;if(!(r==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:r,label:`${r} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:r,label:`${r} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let o=false;for(let n of a){let s=await a$2({workspacePath:e.goal.workspace.path,stage:r,scope:n,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false}),c=n?.replace(/^project:/,"");if(t.push(k({id:c?`${r}:${c}`:r,label:c?`${r} validation \xB7 ${c}`:`${r} validation`,status:s.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${s.summary.exitCode}`,evidencePath:u.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),s.summary.exitCode!==0){o=true;break}}if(o)break}return t}async function Ge(e$2){let t=u.resolve(e$2.workspacePath),{goal:a$1,status:r}=await te(t,e$2.goalId),i=e$2.run!==false,o=[],n;if(i&&e$2.runIntelligence!==false){let d=await c({workspacePath:t,strict:true,agent:"generic"}),l=d.exitCode===0||d.exitCode===2,h=a$1.kind==="release-readiness";o.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:d.exitCode===0||d.exitCode===2&&!h?"passed":d.exitCode===2?"blocked":"failed",expected:"passed",actual:d.exitCode===2&&l&&!h?`${d.status}; canonical evidence refreshed for goal-scoped verification`:d.status,evidencePath:u.join(t,e.intelligenceRun)}));}if(a$1.kind==="release-readiness"){n=await Z(t),o.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:u.join(t,e.readiness)}));let d$1=await d(t,e.verify),l=await X(d$1),h=l?.summary&&typeof l.summary=="object"&&!Array.isArray(l.summary)?String(l.summary.verdict??"missing"):"missing";o.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:u.join(t,e.verify)}));}else if(a$1.kind==="dependency-security")n=await Q(t,a$1.scope),o.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]})),o.push(a$1.constraints.allowBreakingChanges||a$1.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$1.constraints.allowBreakingChanges}, allowForce=${a$1.constraints.allowForce}`}):await ce(a$1)),n.status==="satisfied"&&o.push(...await q({goal:a$1,run:i}));else {let d=a$1.criteria.kind==="test-coverage"?a$1.criteria.minimumPercent:a$1.baseline.target;if(d===null)throw new Error("Coverage goal does not have a valid target.");let l=await ee({workspacePath:t,scope:a$1.scope,target:d,run:i,runtime:a$1.criteria.kind==="test-coverage"?a$1.criteria.runtime:void 0});n=l.measurement,o.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${d}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),o.push(k({id:"test",label:"Coverage test execution",status:l.executionStatus==="failed"?"failed":l.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:l.executionStatus==="failed"?"coverage test command failed":l.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&o.push(...await q({goal:a$1,run:i,includeTests:false}));}let s=o.filter(d=>d.status==="blocked"||d.status==="failed"||d.status==="missing").map(d=>d.message),c$1=[...new Set([...n.evidencePaths,...o.map(d=>d.evidencePath).filter(d=>typeof d=="string")])],g=n.status==="satisfied"&&o.every(d=>d.status==="passed"||d.status==="skipped"),f=E(t,a$1.id),p=g?[]:a$1.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$1.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:A,goalId:a$1.id,goalFingerprint:a$1.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:g?"verified":o.some(d=>d.status==="failed")?"failed":"blocked",attempt:r.attempt+1,progress:n,checks:o,blockingReasons:s,evidencePaths:c$1,nextActions:p,artifactPath:f.status};return a(m,$,"Verified goal status"),await C(f.status,m),await e$1(t,V,m),m}export{V as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,A as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ee as planVerifiedGoal,te as readVerifiedGoal,Ge as verifyVerifiedGoal};
@@ -1 +1 @@
1
- export{c as captureWorkspaceRegistrationStrict,k as createProject,j as createWorkspace,m as createWorkspaceShareBundle,l as listWorkspaces,a as normalizeWorkspaceEntry,i as registerProjectInWorkspace,h as registerProjectInWorkspaceStrict,f as registerWorkspace,b as registerWorkspaceStrict,d as restoreWorkspaceRegistrationStrict,g as syncWorkspaceProjects,e as unregisterWorkspaceStrict}from'./chunk-WUB6QGC7.js';
1
+ export{c as captureWorkspaceRegistrationStrict,k as createProject,j as createWorkspace,m as createWorkspaceShareBundle,l as listWorkspaces,a as normalizeWorkspaceEntry,i as registerProjectInWorkspace,h as registerProjectInWorkspaceStrict,f as registerWorkspace,b as registerWorkspaceStrict,d as restoreWorkspaceRegistrationStrict,g as syncWorkspaceProjects,e as unregisterWorkspaceStrict}from'./chunk-PKKP5H3T.js';
@@ -0,0 +1 @@
1
+ export{g as AGENT_CUSTOMIZATION_PACK_REPORT_PATH,e as AGENT_CUSTOMIZATION_PACK_SCHEMA,f as AGENT_REPORTS_INDEX_PATH,d as AGENT_REPORTS_INDEX_SCHEMA,h as AGENT_REPORT_CATALOG,i as buildCanonicalAgentReportReadOrder,j as buildWorkspaceAgentReportsIndex,k as parseAgentGroundingTargets,l as syncWorkspaceAgentGrounding}from'./chunk-46USUSIK.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,L as LEGACY_COPILOT_GROUNDING_SKILL_PATH,x as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,N as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,m as LEGACY_CURSOR_GROUNDING_RULE_PATH,T as LEGACY_MCP_DESIGN_REPORT_PATH,V as LEGACY_VSCODE_AGENT_HOOKS_PATH,K as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,w as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,M as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,j as WORKSPAI_CURSOR_DIAGNOSE_RULE_PATH,i as WORKSPAI_CURSOR_EVIDENCE_RULE_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,l as WORKSPAI_CURSOR_RELEASE_RULE_PATH,k as WORKSPAI_CURSOR_REPAIR_RULE_PATH,S as WORKSPAI_MCP_DESIGN_REPORT_PATH,U as WORKSPAI_VSCODE_AGENT_HOOKS_PATH,n as WORKSPAI_WINDSURF_RULES_PATH}from'./chunk-YUGKQ44M.js';
@@ -1 +1 @@
1
- export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-OU7DF6MP.js';
1
+ export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-TVCJKE2U.js';
@@ -0,0 +1 @@
1
+ export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-PPQL5UTI.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-YUGKQ44M.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-NBJ6AP7K.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_EXPLAIN_SCHEMA_VERSION,b as WORKSPACE_EXPLAIN_TARGETS,e as isWorkspaceExplainReport,c as parseWorkspaceExplainTarget,d as resolveWorkspaceTraceTarget}from'./chunk-PXWKMPPI.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-KBR4Y4RW.js';
1
+ export{a as WORKSPACE_EXPLAIN_SCHEMA_VERSION,b as WORKSPACE_EXPLAIN_TARGETS,e as isWorkspaceExplainReport,c as parseWorkspaceExplainTarget,d as resolveWorkspaceTraceTarget}from'./chunk-PXWKMPPI.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-YUGKQ44M.js';
@@ -1 +1 @@
1
- import {b}from'./chunk-KTW4EN47.js';import {a}from'./chunk-Y5YAP4F3.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await b(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-VSOBKAJG.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
1
+ import {b}from'./chunk-TR6OFSJM.js';import {a}from'./chunk-Y5YAP4F3.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await b(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-VSOBKAJG.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
@@ -1 +1 @@
1
- export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-MDF2FBLS.js';
1
+ export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-SS7NJMFL.js';
@@ -1,3 +1,3 @@
1
- import {b}from'./chunk-WLFJHRB3.js';import {d,c as c$1,f,e as e$2}from'./chunk-4PUJVYRM.js';import {c,e as e$1}from'./chunk-PXWKMPPI.js';import {c as c$3,b as b$2}from'./chunk-KBR4Y4RW.js';import {b as b$1}from'./chunk-OU7DF6MP.js';import {d as d$2}from'./chunk-O6R7SE6Y.js';import {c as c$2}from'./chunk-TFOOSYGO.js';import {k}from'./chunk-NA2NXX5P.js';import {e as e$3}from'./chunk-KG3TUTXU.js';import {d as d$1}from'./chunk-CCDGHPEJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,g}from'./chunk-NZ3WZYD5.js';import {v}from'./chunk-MOSXTVPU.js';import u from'path';import N from'readline';import g$1 from'fs-extra';var L=e.agentIndex,q=new Map(Object.keys(e).flatMap(e$1=>{let t=g[e$1];return t?[[e[e$1],t]]:[]}));function M(e,t){return e.kind!==t.kind?false:e.kind==="project"&&t.kind==="project"?e.project.toLowerCase()===t.project.toLowerCase():e.kind==="blocker"&&t.kind==="blocker"?e.blockerId===t.blockerId:e.kind==="trace"&&t.kind==="trace"?e.diffRef===t.diffRef:true}var J=[{name:"getWorkspaceModel",description:"Read workspace-model.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceKnowledgeGraph",description:"Read the current proof-backed workspace knowledge graph artifact",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceEvaluation",description:"Read the live or finalized provenance-aware model usage and verified-outcome report",inputSchema:{type:"object",properties:{live:{type:"boolean",description:"Read the live report instead of the finalized last-run report"}}}},{name:"queryWorkspaceEntities",description:"List workspace knowledge entities, optionally filtered by kind",inputSchema:{type:"object",properties:{kind:{type:"string",description:"Optional entity kind"}}}},{name:"searchWorkspaceGraph",description:"Return bounded, proof-carrying workspace context matching a text query",inputSchema:{type:"object",properties:{query:{type:"string",description:"Text, path, symbol, service, or concept to find"},kind:{type:"string",description:"Optional entity kind filter"},projectId:{type:"string",description:"Optional canonical project id filter"},limit:{type:"integer",minimum:1,maximum:100,default:12}},required:["query"]}},{name:"getWorkspaceGraphEvidence",description:"Resolve portable evidence for a knowledge graph entity or relation",inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]}},{name:"findWorkspaceGraphPath",description:"Find a shortest proof-carrying path between two workspace entities",inputSchema:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"]}},{name:"getEvidenceIndex",description:"Read agent reports INDEX.json",inputSchema:{type:"object",properties:{}}},{name:"getBlockers",description:"Aggregate blocking reasons from verify, explain, and contract-verify reports",inputSchema:{type:"object",properties:{}}},{name:"getSafeCommands",description:"Read safe commands from workspace-context-agent.json",inputSchema:{type:"object",properties:{}}},{name:"getProjectContext",description:"Read scoped project context from workspace-context-agent.json",inputSchema:{type:"object",properties:{project:{type:"string",description:"Optional project name; defaults to active scope"}}}},{name:"getArtifact",description:"Read one workspace-relative artifact path",inputSchema:{type:"object",properties:{relativePath:{type:"string"}},required:["relativePath"]}},{name:"listOperationalSkills",description:"Read workspace-skills-index.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceExplain",description:"Build or read workspace explain report",inputSchema:{type:"object",properties:{target:{type:"string",description:"release-blocked | project:<name> | blocker:<id> | trace:<diffRef> | <project>"}}}}];function H(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!u.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function a(e$1,t){if(!H(t))throw new Error(`Unsafe artifact path: ${t}`);let r=await d$1(e$1,t)??u.join(e$1,t);if(!await g$1.pathExists(r))return null;let n=await g$1.readJson(r),o=v(t),c=q.get(o);if(c&&a$1(n,c,`MCP artifact ${o}`),o===e.knowledgeGraph){let p=u.join(e$1,k);if(!await g$1.pathExists(p))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let l=await g$1.readJson(p);c$2(n,l);}return n}async function F(e){let t=[],r=new Set,o=((await a(e,d$2))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$2,reasons:o});for(let i of o)r.add(i);}let c=await a(e,c$3);if(e$1(c)){let i=(c.blockingReasons??[]).filter(s=>typeof s=="string"&&s.trim().length>0);if(i.length>0){t.push({artifact:c$3,reasons:i});for(let s of i)r.add(s);}}let p=await a(e,e$3),l=(p?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(l.length>0||String(p?.status??"").toLowerCase()==="failed"){let i=l.length>0?l:["Workspace contract verification failed"];t.push({artifact:e$3,reasons:i});for(let s of i)r.add(s);}return {blockingReasons:[...r],sources:t}}async function G(e$3,t,r){switch(t){case "getWorkspaceModel":return a(e$3,k);case "getWorkspaceKnowledgeGraph":return a(e$3,e.knowledgeGraph);case "getWorkspaceEvaluation":return a(e$3,r.live===true?e.evaluationLive:e.evaluationLastRun);case "queryWorkspaceEntities":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=String(r.kind??"").trim();return {schemaVersion:n.schemaVersion,generatedAt:n.generatedAt,entities:e$2(n,o||void 0)}}case "searchWorkspaceGraph":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=typeof r.limit=="number"?r.limit:Number(r.limit??12);return f(n,{query:String(r.query??""),...typeof r.kind=="string"&&r.kind.trim()?{kind:r.kind.trim()}:{},...typeof r.projectId=="string"&&r.projectId.trim()?{projectId:r.projectId.trim()}:{},limit:Number.isFinite(o)?o:12,projection:"agent"})}case "getWorkspaceGraphEvidence":{let n=await a(e$3,e.knowledgeGraph);return n?c$1(n,String(r.query??"")):null}case "findWorkspaceGraphPath":{let n=await a(e$3,e.knowledgeGraph);return n?d(n,String(r.from??""),String(r.to??"")):null}case "getEvidenceIndex":return a(e$3,L);case "getBlockers":return F(e$3);case "getSafeCommands":return {safeCommands:(await a(e$3,b$1))?.safeCommands??[]};case "getProjectContext":{let n=await a(e$3,b$1);if(!n)return null;let o=String(r.project??"").trim(),c=n.scope?.activeProject??void 0,p=o||c,l=Array.isArray(n.projects)?n.projects:[],i=p&&l.find(s=>typeof s.name=="string"&&s.name.toLowerCase()===p.toLowerCase());return {workspace:n.workspace??null,scope:n.scope??null,validation:n.validation??null,project:i??null,safeCommands:n.safeCommands??[]}}case "getArtifact":{let n=String(r.relativePath??"").trim();return a(e$3,n)}case "listOperationalSkills":return a(e$3,b$2);case "getWorkspaceExplain":{let n=String(r.target??"release-blocked").trim(),o=c(n);if(!o)throw new Error(`Invalid explain target: ${n}`);let c$1=await a(e$3,c$3);return e$1(c$1)&&M(c$1.target,o)?c$1:b({workspacePath:e$3,target:o})}default:throw new Error(`Unknown tool: ${t}`)}}function R(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:t})}
1
+ import {b}from'./chunk-PPQL5UTI.js';import {d,c as c$1,f,e as e$2}from'./chunk-4PUJVYRM.js';import {c,e as e$1}from'./chunk-PXWKMPPI.js';import {c as c$3,b as b$2}from'./chunk-YUGKQ44M.js';import {b as b$1}from'./chunk-TVCJKE2U.js';import {d as d$2}from'./chunk-O6R7SE6Y.js';import {c as c$2}from'./chunk-TFOOSYGO.js';import {k}from'./chunk-NA2NXX5P.js';import {e as e$3}from'./chunk-KG3TUTXU.js';import {d as d$1}from'./chunk-CCDGHPEJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,g}from'./chunk-NZ3WZYD5.js';import {v}from'./chunk-MOSXTVPU.js';import u from'path';import N from'readline';import g$1 from'fs-extra';var L=e.agentIndex,q=new Map(Object.keys(e).flatMap(e$1=>{let t=g[e$1];return t?[[e[e$1],t]]:[]}));function M(e,t){return e.kind!==t.kind?false:e.kind==="project"&&t.kind==="project"?e.project.toLowerCase()===t.project.toLowerCase():e.kind==="blocker"&&t.kind==="blocker"?e.blockerId===t.blockerId:e.kind==="trace"&&t.kind==="trace"?e.diffRef===t.diffRef:true}var J=[{name:"getWorkspaceModel",description:"Read workspace-model.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceKnowledgeGraph",description:"Read the current proof-backed workspace knowledge graph artifact",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceEvaluation",description:"Read the live or finalized provenance-aware model usage and verified-outcome report",inputSchema:{type:"object",properties:{live:{type:"boolean",description:"Read the live report instead of the finalized last-run report"}}}},{name:"queryWorkspaceEntities",description:"List workspace knowledge entities, optionally filtered by kind",inputSchema:{type:"object",properties:{kind:{type:"string",description:"Optional entity kind"}}}},{name:"searchWorkspaceGraph",description:"Return bounded, proof-carrying workspace context matching a text query",inputSchema:{type:"object",properties:{query:{type:"string",description:"Text, path, symbol, service, or concept to find"},kind:{type:"string",description:"Optional entity kind filter"},projectId:{type:"string",description:"Optional canonical project id filter"},limit:{type:"integer",minimum:1,maximum:100,default:12}},required:["query"]}},{name:"getWorkspaceGraphEvidence",description:"Resolve portable evidence for a knowledge graph entity or relation",inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]}},{name:"findWorkspaceGraphPath",description:"Find a shortest proof-carrying path between two workspace entities",inputSchema:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"]}},{name:"getEvidenceIndex",description:"Read agent reports INDEX.json",inputSchema:{type:"object",properties:{}}},{name:"getBlockers",description:"Aggregate blocking reasons from verify, explain, and contract-verify reports",inputSchema:{type:"object",properties:{}}},{name:"getSafeCommands",description:"Read safe commands from workspace-context-agent.json",inputSchema:{type:"object",properties:{}}},{name:"getProjectContext",description:"Read scoped project context from workspace-context-agent.json",inputSchema:{type:"object",properties:{project:{type:"string",description:"Optional project name; defaults to active scope"}}}},{name:"getArtifact",description:"Read one workspace-relative artifact path",inputSchema:{type:"object",properties:{relativePath:{type:"string"}},required:["relativePath"]}},{name:"listOperationalSkills",description:"Read workspace-skills-index.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceExplain",description:"Build or read workspace explain report",inputSchema:{type:"object",properties:{target:{type:"string",description:"release-blocked | project:<name> | blocker:<id> | trace:<diffRef> | <project>"}}}}];function H(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!u.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function a(e$1,t){if(!H(t))throw new Error(`Unsafe artifact path: ${t}`);let r=await d$1(e$1,t)??u.join(e$1,t);if(!await g$1.pathExists(r))return null;let n=await g$1.readJson(r),o=v(t),c=q.get(o);if(c&&a$1(n,c,`MCP artifact ${o}`),o===e.knowledgeGraph){let p=u.join(e$1,k);if(!await g$1.pathExists(p))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let l=await g$1.readJson(p);c$2(n,l);}return n}async function F(e){let t=[],r=new Set,o=((await a(e,d$2))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$2,reasons:o});for(let i of o)r.add(i);}let c=await a(e,c$3);if(e$1(c)){let i=(c.blockingReasons??[]).filter(s=>typeof s=="string"&&s.trim().length>0);if(i.length>0){t.push({artifact:c$3,reasons:i});for(let s of i)r.add(s);}}let p=await a(e,e$3),l=(p?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(l.length>0||String(p?.status??"").toLowerCase()==="failed"){let i=l.length>0?l:["Workspace contract verification failed"];t.push({artifact:e$3,reasons:i});for(let s of i)r.add(s);}return {blockingReasons:[...r],sources:t}}async function G(e$3,t,r){switch(t){case "getWorkspaceModel":return a(e$3,k);case "getWorkspaceKnowledgeGraph":return a(e$3,e.knowledgeGraph);case "getWorkspaceEvaluation":return a(e$3,r.live===true?e.evaluationLive:e.evaluationLastRun);case "queryWorkspaceEntities":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=String(r.kind??"").trim();return {schemaVersion:n.schemaVersion,generatedAt:n.generatedAt,entities:e$2(n,o||void 0)}}case "searchWorkspaceGraph":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=typeof r.limit=="number"?r.limit:Number(r.limit??12);return f(n,{query:String(r.query??""),...typeof r.kind=="string"&&r.kind.trim()?{kind:r.kind.trim()}:{},...typeof r.projectId=="string"&&r.projectId.trim()?{projectId:r.projectId.trim()}:{},limit:Number.isFinite(o)?o:12,projection:"agent"})}case "getWorkspaceGraphEvidence":{let n=await a(e$3,e.knowledgeGraph);return n?c$1(n,String(r.query??"")):null}case "findWorkspaceGraphPath":{let n=await a(e$3,e.knowledgeGraph);return n?d(n,String(r.from??""),String(r.to??"")):null}case "getEvidenceIndex":return a(e$3,L);case "getBlockers":return F(e$3);case "getSafeCommands":return {safeCommands:(await a(e$3,b$1))?.safeCommands??[]};case "getProjectContext":{let n=await a(e$3,b$1);if(!n)return null;let o=String(r.project??"").trim(),c=n.scope?.activeProject??void 0,p=o||c,l=Array.isArray(n.projects)?n.projects:[],i=p&&l.find(s=>typeof s.name=="string"&&s.name.toLowerCase()===p.toLowerCase());return {workspace:n.workspace??null,scope:n.scope??null,validation:n.validation??null,project:i??null,safeCommands:n.safeCommands??[]}}case "getArtifact":{let n=String(r.relativePath??"").trim();return a(e$3,n)}case "listOperationalSkills":return a(e$3,b$2);case "getWorkspaceExplain":{let n=String(r.target??"release-blocked").trim(),o=c(n);if(!o)throw new Error(`Invalid explain target: ${n}`);let c$1=await a(e$3,c$3);return e$1(c$1)&&M(c$1.target,o)?c$1:b({workspacePath:e$3,target:o})}default:throw new Error(`Unknown tool: ${t}`)}}function R(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:t})}
2
2
  `);}function E(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,error:{code:-32e3,message:t}})}
3
3
  `);}async function ce(e){let t=u.resolve(e.workspacePath),r=N.createInterface({input:process.stdin,terminal:false});for await(let n of r){let o=n.trim();if(!o)continue;let c;try{c=JSON.parse(o);}catch{E(null,"Invalid JSON-RPC request");continue}let{id:p,method:l,params:i}=c;try{if(l==="initialize"){R(p,{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"workspai-workspace-mcp",version:"0.1.0"}});continue}if(l==="notifications/initialized")continue;if(l==="tools/list"){R(p,{tools:J.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema}))});continue}if(l==="tools/call"){let s=String(i?.name??""),K=i?.arguments&&typeof i.arguments=="object"?i.arguments:{},S=await G(t,s,K);R(p,{content:[{type:"text",text:JSON.stringify(S,null,2)}],isError:S==null});continue}E(p,`Unsupported method: ${l??"unknown"}`);}catch(s){E(p,s instanceof Error?s.message:String(s));}}}async function pe(e,t,r={}){return G(u.resolve(e),t,r)}export{J as WORKSPACE_MCP_READ_TOOLS,pe as invokeMcpToolForTest,ce as runWorkspaceMcpServe};
@@ -1 +1 @@
1
- export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-VV55EAWO.js';
1
+ export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-VDEFHP6I.js';
@@ -1,4 +1,4 @@
1
- import {b as b$1}from'./chunk-WQX3JYEP.js';import {g as g$1}from'./chunk-CCDGHPEJ.js';import g from'path';import i from'fs-extra';var l="README.md",h="<!-- workspai:workspace-intelligence:start -->",c="<!-- workspai:workspace-intelligence:end -->",m={minimal:"A lightweight workspace boundary that adds runtimes only when you need them.","node-only":"A Node.js-focused workspace with shared evidence and agent grounding.","python-only":"A Python-focused workspace with shared evidence and agent grounding.","go-only":"A Go-focused workspace with shared evidence and agent grounding.","java-only":"A Java-focused workspace with shared evidence and agent grounding.","dotnet-only":"A .NET-focused workspace with shared evidence and agent grounding.",polyglot:"A multi-runtime workspace for projects that share contracts, evidence, and agents.",enterprise:"A governed multi-runtime workspace with the complete evidence, policy, and agent surface."};function w(e){return e?.trim()||"minimal"}async function u(e){let n=g.join(e,".workspai","workspace.json");return await i.pathExists(n)?await i.readJson(n).catch(()=>({})):{}}function f(e){let n=e.engine;if(!n)return;if(n.python_core?.status==="skipped")return "Optional Python engine: not installed";if(n.python_version)return `Optional Python engine: Python ${n.python_version} via ${n.install_method||"local environment"}`}function y(e){let n=w(e.profile),r=b$1().presentations.standard.nodes.map(s=>s.label).join(" \u2192 "),a=e.projectCount===1?"project":"projects",t=m[n]??"A governed workspace with shared evidence for developers, tools, CI, IDEs, and AI agents.";return `${h}
1
+ import {b as b$1}from'./chunk-LNXIMF3O.js';import {g as g$1}from'./chunk-CCDGHPEJ.js';import g from'path';import i from'fs-extra';var l="README.md",h="<!-- workspai:workspace-intelligence:start -->",c="<!-- workspai:workspace-intelligence:end -->",m={minimal:"A lightweight workspace boundary that adds runtimes only when you need them.","node-only":"A Node.js-focused workspace with shared evidence and agent grounding.","python-only":"A Python-focused workspace with shared evidence and agent grounding.","go-only":"A Go-focused workspace with shared evidence and agent grounding.","java-only":"A Java-focused workspace with shared evidence and agent grounding.","dotnet-only":"A .NET-focused workspace with shared evidence and agent grounding.",polyglot:"A multi-runtime workspace for projects that share contracts, evidence, and agents.",enterprise:"A governed multi-runtime workspace with the complete evidence, policy, and agent surface."};function w(e){return e?.trim()||"minimal"}async function u(e){let n=g.join(e,".workspai","workspace.json");return await i.pathExists(n)?await i.readJson(n).catch(()=>({})):{}}function f(e){let n=e.engine;if(!n)return;if(n.python_core?.status==="skipped")return "Optional Python engine: not installed";if(n.python_version)return `Optional Python engine: Python ${n.python_version} via ${n.install_method||"local environment"}`}function y(e){let n=w(e.profile),r=b$1().presentations.standard.nodes.map(s=>s.label).join(" \u2192 "),a=e.projectCount===1?"project":"projects",t=m[n]??"A governed workspace with shared evidence for developers, tools, CI, IDEs, and AI agents.";return `${h}
2
2
  # ${e.workspaceName}
3
3
 
4
4
  This is a **Workspai Workspace Intelligence** workspace. It gives every registered project one shared, evidence-backed view for developers, CI, IDEs, and AI agents.
@@ -0,0 +1,3 @@
1
+ import {c as c$3}from'./chunk-SS7NJMFL.js';import {d as d$2,i,j as j$1,k as k$1,h as h$2,m as m$1,n,o}from'./chunk-VDFHUYAQ.js';import {a as a$2}from'./chunk-7DSYI7YN.js';import {a,c,h,b,e,j,g,d as d$1}from'./chunk-BQCGULHR.js';import {h as h$1}from'./chunk-MWCKJOOU.js';import {l,p}from'./chunk-3VU7ROHY.js';import {a as a$3}from'./chunk-A4BK7C7M.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {c as c$4,d}from'./chunk-EWZZUQBR.js';import {m}from'./chunk-KG3TUTXU.js';import {c as c$2}from'./chunk-CCDGHPEJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e as e$1}from'./chunk-NZ3WZYD5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import k from'fs-extra';var Ne=".workspai/repair",$a="transaction.json",Sa="source-plan.json",ia="checkpoint",Ca="engine.lock",fa=5*1024*1024,Wa=25*1024*1024,Ta=25*1024*1024,ka=4*1024*1024,Na=900*1e3,qa=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"]),Da=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"]),O={safe:0,guarded:1,invasive:2},Fa=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 Oa(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function D(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${S(e).slice(0,16)}`,message:r.message??e}]}}function ma(e){let a=new Map,r=t=>a.set(Oa(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=xe(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),O[t.risk]>O[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(s=>s.invocation&&`tool:${s.invocation.cwd}:${s.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${S(t).slice(0,16)}`,message:t});}return [...a.values()]}function F(e){return (e?.()??new Date).toISOString()}function S(e){return createHash("sha256").update(e).digest("hex")}function G(e){return Array.isArray(e)?`[${e.map(G).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)}:${G(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function na(e){return S(G({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function wa(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=na(a),t=(await lt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&na(o)===r);if(t)return await U(c$1.join(e,b),t),t}var Ce="causal-action-integrity:";function ba(e){return S(G([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function va(e){if(e.length===0)return;let a=ba(e);return {id:`${Ce}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function E(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 H(e,a){let r=await k.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await k.pathExists(t);){let s=c$1.dirname(t);if(s===t)return false;t=s;}let o=await k.realpath(t).catch(()=>c$1.resolve(t));return E(r,o)}function M(e,a,r){let t=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!E(e,t)&&!(r&&E(c$1.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,t).split(c$1.sep).join("/")||"."}function ca(e,a,r){return M(e,a,r)}async function Ha(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;if(a&&E(e.workspacePath,a))return a;let{contract:r}=await m({workspacePath:e.workspacePath}),t=r.projects.find(o=>{let s=o.externalPath?c$1.resolve(o.externalPath):c$1.resolve(e.workspacePath,o.relativePath);return (!e.proposal.projectName||o.slug===e.proposal.projectName)&&(!a||s===a)});if(!t)throw new Error("Repair proposal project must match one canonical registered project.");return t.externalPath?c$1.resolve(t.externalPath):c$1.resolve(e.workspacePath,t.relativePath)}function se(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,Ne,"transactions",a)}function ve(e,a){return a.target.projectPath?c$1.resolve(e,a.target.projectPath):void 0}function Pe(e,a){return c$1.join(se(e,a),$a)}function qe(e,a){return c$1.join(se(e,a),Sa)}async function U(e,a){await k.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await k.writeJson(r,a,{spaces:2}),await k.move(r,e,{overwrite:true});}function I(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:F(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function P(e,a,r){a.revision+=1,a.updatedAt=F(r),a$1(a,c,"Workspace repair transaction"),await U(Pe(e,a.transactionId),a),await U(c$1.join(e,b),a);}async function ie(e){let a$2=await k.readJson(Pe(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 Re(e,a){return await k.readJson(qe(e,a))}function oe(e){return e.schemaVersion===d$1}function ke(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=c$1.isAbsolute(t)?c$1.resolve(t):c$1.resolve(e,t);if(!E(e,o)&&!(r&&c$1.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:M(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Se(e){return k.readFile(e,"utf8").catch(()=>"")}async function Ma(e){return k.readJson(e).catch(()=>({}))}function da(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function Ba(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(t=>r?[c$1.join(t,e)]:a.map(o=>c$1.join(t,`${e}${o}`)))}function pa(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function la(e,a){try{let r=await execa(e,["--version"],{cwd:a,shell:false,reject:false,timeout:5e3,maxBuffer:65536,stdin:"ignore"});return r.exitCode!==void 0&&r.exitCode!==null}catch{return false}}async function ya(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(c$1.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=c$1.isAbsolute(r)?r:c$1.resolve(a,r),o=await k.stat(t).catch(()=>{});return pa(o)&&la(t,a)}for(let t of Ba(r)){let o=await k.stat(t).catch(()=>{});if(pa(o)&&await la(t,a))return true}return false}async function De(e){let a=new Set;for(let s of e.stages){if(s.kind!=="repair"||!s.invocation)continue;let d=je(s.invocation.executable);!["python","python3","py"].includes(d)||!s.invocation.args.includes("venv")||!s.invocation.args.includes(".venv")||a.add(c$1.normalize(c$1.join(c$1.resolve(e.workspacePath,s.invocation.cwd),".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),t=new Map;for(let s of r)t.set(`${s.cwd}\0${s.executable}`,s);let o=[];for(let s of t.values()){let d=c$1.isAbsolute(s.executable)?c$1.normalize(s.executable):c$1.normalize(c$1.resolve(e.workspacePath,s.cwd,s.executable));if(a.has(d)){o.push({id:`tool:${s.cwd}:${s.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${s.executable} (${s.cwd}).`});continue}let i=await ya({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});o.push({id:`tool:${s.cwd}:${s.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${s.executable} (${s.cwd}).`:`Required repair executable is unavailable: ${s.executable} (${s.cwd}). Install or configure it, then create a fresh plan.`});}return o}function Q(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function y(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 _a(e,a,r){let t=r.strategy?.find(o=>o.kind==="verify"&&o.invocation)?.invocation;if(t)return v({workspacePath:e,projectPath:a,executable:t.executable,args:t.args,purpose:"audit"})}async function La(e){let a=ke(e.workspacePath,e.action,e.authorizedProjectRoot),r=M(e.workspacePath,a,a),t=async u=>k.pathExists(c$1.join(a,u)),o=new Set,s=[],d=[],i=u=>`${r}:${e.adapterId}:${u}`,g$1=u=>u.forEach(h=>o.add(M(e.workspacePath,c$1.join(a,h),a))),n=u=>{s.push(u),u.required&&u.status==="blocked"&&d.push(u.summary);},f=_a(e.workspacePath,a,e.action),m=()=>{let u=g.find(h=>h.id===e.adapterId);if(!u)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:s,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:u.id,ecosystem:u.ecosystem,projectPath:r,manifests:u.manifests,support:u.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(s.filter(h=>h.required&&h.invocation).map(h=>h.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${u.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let u=await Ma(c$1.join(a,"package.json")),h=u.scripts&&typeof u.scripts=="object"&&!Array.isArray(u.scripts)?u.scripts:{},w=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",W=w==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":w==="pnpm"?"pnpm-lock.yaml":w==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";g$1(["package.json",W]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${w} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:["install"],purpose:"reconcile"})}));let V=v(w==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return n(y({id:i("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:f??V})),n(typeof h.test=="string"&&h.test.trim()?y({id:i("test"),kind:"test",summary:"Run the declared project test contract.",invocation:da({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"test",purpose:"test"})}):Q(i("test"),"test","No test script is declared.")),n(typeof h.build=="string"&&h.build.trim()?y({id:i("build"),kind:"build",summary:"Run the declared project build contract.",invocation:da({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"build",purpose:"build"})}):Q(i("build"),"build","No build script is declared.")),m()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){g$1(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let u=e.action.transaction?.ecosystem.toLowerCase(),h=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),w=h==="uv"||u==="uv"||await t("uv.lock"),W=!w&&(h==="poetry"||u==="poetry"||await t("poetry.lock")),V=!w&&!W&&["python","python3","py"].includes(h)&&(e.action.invocation?.args??[]).some(te=>te==="venv")&&(e.action.invocation?.args??[]).some(te=>te===".venv"),j=process.platform==="win32"?"python":"python3",C=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await k.pathExists(C)||V)&&(j=C);let ee=w?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):W?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&E(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&E(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:ee})),n(y({id:i("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:f}));let B=await Se(c$1.join(a,"pyproject.toml")),K=await t("tests")||/\[tool\.pytest/i.test(B),ae=v(W?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pytest"],purpose:"test"}),_=v(W?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","build"],purpose:"build"});return n(K?y({id:i("test"),kind:"test",summary:"Run the Python test contract.",invocation:ae}):Q(i("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(B)?y({id:i("build"),kind:"build",summary:"Build the declared Python package.",invocation:_}):Q(i("build"),"build","No Python build contract is declared.")),m()}let b=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let u of b){if(u.adapterId!==e.adapterId)continue;let h=await t(u.manifest)?u.manifest:u.alternateManifest&&await t(u.alternateManifest)?u.alternateManifest:void 0;if(!h)continue;g$1(u.files),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${h} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u.reconcile[0],args:u.reconcile[1],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:f??(u.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:u.audit[0],args:u.audit[1],purpose:"audit"}):void 0)}));let w=await Se(c$1.join(a,h)),W=u.manifest==="composer.json"||u.adapterId==="deno"?/["']test["']\s*:/.test(w):u.manifest==="Gemfile"?await t("Rakefile"):true,V=u.manifest==="composer.json"||u.manifest==="deno.json"?/["']build["']\s*:/.test(w):u.manifest==="Gemfile"?(await k.readdir(a)).some(j=>j.endsWith(".gemspec")):true;return n(W?y({id:i("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u.test[0],args:u.test[1],purpose:"test"})}):Q(i("test"),"test","No test contract is declared.")),n(V?y({id:i("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u.build[0],args:u.build[1],purpose:"build"})}):Q(i("build"),"build","No build contract is declared.")),m()}let R=await k.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&R.some(u=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(u)))return g$1(["Directory.Packages.props","packages.lock.json",...R.filter(u=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(u))]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:f??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(y({id:i("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),m();let x=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return g$1(["pom.xml"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["dependency:resolve"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:x,args:["package","-DskipTests"],purpose:"build"})})),m();let $=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&$){let u=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g$1([$,"gradle.lockfile","gradle/libs.versions.toml"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u,args:["dependencies"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u,args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:u,args:["build","-x","test"],purpose:"build"})})),m()}let N=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&N){let u=N==="deps.edn",h=await Se(c$1.join(a,N)),w=u?"clojure":"lein";g$1([N]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${N} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:u?["-P"]:["deps"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:f}));let W=!u||/:test\b/.test(h);return n(W?y({id:i("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:u?["-M:test"]:["test"],purpose:"test"})}):Q(i("test"),"test","No Clojure :test alias is declared.")),n(u?Q(i("build"),"build","No portable Clojure CLI build entrypoint is declared."):y({id:i("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),m()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(g$1(["build.sbt"]),n(y({id:i("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),n(y({id:i("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:f})),n(y({id:i("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(y({id:i("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({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(y({id:i("reconcile"),kind:"reconcile",required:true,summary:d[0]})),m())}async function Pa(e){let a=s=>k.pathExists(c$1.join(e,s)),r=await k.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(s=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(g.map((s,d)=>[s.id,d]));return [...new Set(t)].sort((s,d)=>(o.get(s)??999)-(o.get(d)??999))}function Ga(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 Ra(e,a={}){let r=ke(e.workspacePath,e.action,e.authorizedProjectRoot),t=M(e.workspacePath,r,r),o=await Pa(r),s=Ga(e.action.transaction?.ecosystem),d=s?[s]:o;if(s&&!o.includes(s)){let n=`Doctor declared the ${s} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[y({id:`${t}:${s}:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:s,ecosystem:g.find(f=>f.id===s)?.ecosystem??s,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:n}]}}if(d.length===0){let n=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[y({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:n}]}}let i={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let n of d){let f=await La({...e,adapterId:n});i.stages.push(...f.stages),i.checkpointFiles.push(...f.checkpointFiles),i.blockers.push(...f.blockers),i.adapters.push(...f.adapters);}i.stages=[...new Map(i.stages.map(n=>[n.id,n])).values()],i.checkpointFiles=[...new Set(i.checkpointFiles)].sort(),i.blockers=[...new Set(i.blockers)];let g$1=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let n=new Set(e.action.transaction.requiredStages),f=je(e.action.invocation?.executable??""),m=e.action.invocation?.args??[],b=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(f)&&m.includes("venv")&&m.includes(".venv");b&&g$1.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),i.stages=i.stages.filter(R=>R.kind==="reconcile"?b&&n.has("reconcile"):n.has(R.kind)),i.blockers=i.stages.filter(R=>R.required&&R.status==="blocked").map(R=>R.summary);}for(let n of i.adapters){let f=i.stages.filter(b=>b.id.startsWith(`${n.projectPath}:${n.adapterId}:`)),m=[];n.requiredExecutables=[...new Set(f.filter(b=>b.required&&b.invocation).map(b=>b.invocation.executable))];for(let b of f){if(!b.required||!b.invocation)continue;let R=c$1.isAbsolute(b.invocation.executable)?c$1.normalize(b.invocation.executable):c$1.normalize(c$1.resolve(e.workspacePath,b.invocation.cwd,b.invocation.executable));g$1.has(R)||await ya({workspacePath:e.workspacePath,invocation:b.invocation,toolAvailable:a.toolAvailable})||m.push(b.invocation.executable);}n.missingExecutables=[...new Set(m)],n.missingExecutables.length>0&&(n.status="partial",n.message=`Required executable(s) unavailable: ${n.missingExecutables.join(", ")}.`);}if(d.length===1){let n=`:${d[0]}:`;for(let f of i.stages)f.id=f.id.replace(n,":");}return i}async function qt(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let s=e.project.trim(),d=await h$1(r),i=s.replace(/\\/g,"/").replace(/^\.\//,""),g=c$1.resolve(r,s),n=d.resolved.filter(f=>{let m=E(r,f.projectPath)?M(r,f.projectPath):void 0;return f.name===s||m===i||c$1.resolve(f.projectPath)===g});if(n.length===0){let f=d.skipped.find(m=>m.name===s);throw f?new Error(`Registered project is unavailable for repair capability inspection: ${s} (${f.reason}).`):new Error(`Registered project not found for repair capability inspection: ${s}.`)}if(n.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${s}.`);t=c$1.resolve(n[0].projectPath),o=n[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!E(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=M(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Pa(t)}}}function xe(e){if(e.command){let a=d$2(e.command);if(a)return a}return a$4(e.operation)??void 0}async function Va(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){let t=ke(e.workspacePath,r);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);for(let d of r.files){let i=c$1.isAbsolute(d)?c$1.resolve(d):c$1.resolve(e.workspacePath,d);if(!await H(e.workspacePath,i))throw new Error(`Repair checkpoint path escapes workspace through a symbolic link: ${d}`);a.add(M(e.workspacePath,d));}let o=xe(r);if(!o)continue;let s="path"in o?o.path:void 0;if(s){let d=c$1.resolve(t,s);if(!await H(e.workspacePath,d))throw new Error(`Repair operation target escapes workspace through a symbolic link: ${s}`);a.add(M(e.workspacePath,d));}}return [...a].filter(r=>r!==".").sort()}function Ka(e,a){if(!a.invocation)return;let r=ke(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Fe(e){return S(G({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 Oe(e){return Fe({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function xa(e){return S(G({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Dt(e){let a=c$1.resolve(e.workspacePath),r=await ie({workspacePath:a,transactionId:e.transactionId}),t=await Re(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Oe(r)!==r.integrity.planHash||!r.integrity.closureHash||xa(r)!==r.integrity.closureHash||S(G(t))!==r.integrity.sourceEvidenceHash||!oe(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=ve(a,r);for(let s of r.checkpoint.files){let d=c$1.resolve(a,s.path);if(!E(a,d)&&!(o&&E(o,d)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${s.path}`);let i=await k.lstat(d).catch(()=>{});if(!i){if(s.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${s.path}`);continue}if(!i.isFile()||i.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${s.path}`);let g=await k.readFile(d);if(s.afterHash!==S(g))throw new Error(`Goal repair output changed after transaction closure: ${s.path}`);if(s.mode!==void 0&&i.mode!==s.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${s.path}`)}return r.verification.sourceBinding}async function ye(e,a,r){let t=[],o=[],s=0;for(let d of a){let i=c$1.resolve(e,d),g=r&&E(c$1.resolve(r),i)?c$1.resolve(r):e;if(!E(g,i)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${d}`);continue}if(!await H(g,i)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${d}`);continue}let n=await k.lstat(i).catch(()=>{});if(n?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${d}`);continue}if(n&&!n.isFile()){o.push(`Checkpoint target is not a regular file: ${d}`);continue}if(n&&n.size>fa){o.push(`Checkpoint file exceeds 5 MiB: ${d}`);continue}if(s+=n?.size??0,s>Wa){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let f=n?await k.readFile(i):void 0;t.push({path:d,existed:!!n,beforeHash:f?S(f):null,...n?{mode:n.mode}:{}});}return {entries:t,errors:o}}function ja(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}function za(e,a){if(!(!/\.json$/i.test(e)||a===void 0))try{JSON.parse(a);return}catch{return `${e} must contain valid JSON; comments and trailing syntax are not allowed.`}}async function Ja(e){let a=await k.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function Ua(e){return qa.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Ya(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;E(e,t);){if((await k.readdir(t).catch(()=>[])).some(Ua))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function Xa(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!E(a,o))return false;let s=c$1.basename(o);return Da.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function Za(e){let a=M(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function Qa(e,a){let r=je(a.executable),[t="",o=""]=a.args;if(a.args.some(i=>/^(?:-e|--eval|-c|--command|-command)$/i.test(i)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let s=["npm","pnpm","yarn","bun"].includes(r);if(!(s&&e.kind==="audit"&&a.args.some(i=>/audit/i.test(i))||s&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(i=>/^(?:test|build|check|verify|package)$/i.test(i))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function et(e){let a=[],r=new Set,t=[],o=[],s=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let i of e.proposal.validation??[]){let g=c$1.resolve(e.workspacePath,i.cwd),n=M(e.workspacePath,g,d),f=await k.lstat(g).catch(()=>{});if(!f?.isDirectory()||f.isSymbolicLink()||!await H(d??e.workspacePath,g)){t.push(`Validation ${i.id} requires a real directory inside the workspace.`);continue}if(d&&!E(d,g)){t.push(`Validation ${i.id} escapes the declared project scope.`);continue}if(O[i.risk]>O[e.maxRisk]){t.push(`Validation ${i.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let m=v({workspacePath:e.workspacePath,projectPath:g,executable:i.executable,args:i.args,purpose:i.kind,timeoutMs:i.timeoutMs});try{He(e.workspacePath,m,e.policy,e.projectRoots),Qa(i,m);}catch(b){t.push(b instanceof Error?b.message:String(b));continue}a.push(y({id:`validation:${i.id}`,kind:i.kind,risk:i.risk,required:i.required,summary:i.summary,invocation:m})),s.add(`${n}:${i.kind}`);}for(let i of e.projectRoots){let g=Za({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await Ra({workspacePath:e.workspacePath,action:g,authorizedProjectRoot:i},e.dependencies);o.push(...n.adapters);let f=Xa(e.workspacePath,i,e.proposal.changes);if(f){for(let b of n.checkpointFiles)r.add(b);t.push(...n.blockers);}let m=M(e.workspacePath,i,i);for(let b of n.stages)!f&&!["test","build"].includes(b.kind)||s.has(`${m}:${b.kind}`)||a.push(b);}return {stages:[...new Map(a.map(i=>[i.id,i])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(i=>[`${i.projectPath}:${i.adapterId}`,i])).values()]}}async function at(e,a$3={}){let r=c$1.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(l=>l.cardId===e.cardId).filter(l=>!e.projectName||l.projectName===e.projectName).sort((l,A)=>l.order-A.order||l.id.localeCompare(A.id)),s=e.actionId?o.filter(l=>l.id===e.actionId):o,d=t.actions.filter(l=>!e.projectName||!l.projectName||l.projectName===e.projectName).sort((l,A)=>l.order-A.order||l.id.localeCompare(A.id)),i=new Map(d.map(l=>[l.id,l])),g=l=>{let A=new Set(l.map(L=>L.id)),q=[...l];for(;q.length>0;){let L=q.pop();for(let T of L?.dependsOn??[]){let Z=i.get(T);!Z||A.has(Z.id)||(A.add(Z.id),q.push(Z));}}return d.filter(L=>A.has(L.id))},n=s.filter(l=>l.findingStatus==="blocking"||l.notes.includes("Doctor finding status: blocking")),f=n.length>0?n:s.filter(l=>l.findingStatus!=="advisory"&&l.findingStatus!=="informational"),m=e.actionId?s.filter(l=>l.id===e.actionId):[],b$1=f[0],R=b$1?f.filter(l=>l.cardId===b$1.cardId&&l.findingId===b$1.findingId):[],x=g(e.actionId?m:R),$=e.maxRisk??"guarded",N={maxRisk:$,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},u=[{id:"workspace-root",status:await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:x.length>0?"passed":"failed",message:x.length>0?`${x.length} governed action(s) selected.`:"No governed remediation action matches this target."}],h=va(x);h&&u.push(h);let w=[],W=[],V=[],j=[],C=new Set(["replan","manual-repair","cancel"]);for(let l of x){let A=xe(l),q=Ka(r,l);if(O[l.risk]<=O[$]||(j.push(`${l.id} exceeds the approved ${$} risk ceiling.`),C.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),(l.status==="blocked"||l.status==="guidance-only")&&j.push(`${l.id} is ${l.status}: ${l.blocker}`),!A&&!q&&j.push(`${l.id} has no typed operation or structured invocation.`),q)try{He(r,q,N);}catch(T){let Z=T instanceof Error?T.message:String(T);j.push(Z),/Force-based/.test(Z)&&C.add("allow-force"),/Breaking dependency/.test(Z)&&C.add("allow-breaking");}if(w.push({id:`action:${l.id}`,kind:"repair",status:A||q?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,...q?{invocation:q}:{}}),l.transaction){let T=await Ra({workspacePath:r,action:l},a$3);w.push(...T.stages),W.push(...T.checkpointFiles),j.push(...T.blockers),V.push(...T.adapters);}}let ee=[...new Map(w.map(l=>[l.id,l])).values()];w.splice(0,w.length,...ee),w.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),w.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),w.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),u.push(...await De({workspacePath:r,stages:w,toolAvailable:a$3.toolAvailable}));let B=await Va({workspacePath:r,actions:x,dependencyFiles:W}),K=await ye(r,B);u.push({id:"rollback-coverage",status:x.some(l=>l.mode==="edit-file"||l.mode==="run-command")&&B.length===0?"failed":"passed",message:B.length>0?`${B.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),u.push({id:"structured-execution",status:w.some(l=>l.required&&l.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),u.push({id:"checkpoint-boundary",status:K.errors.length===0?"passed":"failed",message:K.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":K.errors.join(" ")});let ae=S(G(t)),_=[...new Set(x.map(l=>l.projectPath).filter(Boolean))],te={cardId:e.cardId,scope:e.projectName||_.length===1?"project":"workspace",...e.projectName?{projectName:e.projectName}:{},..._.length===1?{projectPath:_[0]}:{},actionIds:x.map(l=>l.id)},ne=F(a$3.now),re=`repair_${randomUUID().replaceAll("-","")}`,Y=u.some(l=>l.status==="failed")||j.length>0,pe=[...j,...u.filter(l=>l.status==="failed").map(l=>l.message)],le=[...new Map(V.map(l=>[`${l.projectPath}:${l.adapterId}`,l])).values()],X=ma({actions:x,adapters:le,preconditions:u,stages:w,decisionOptions:C,maxRisk:$,fallbackReasons:pe}),J={schemaVersion:a,transactionId:re,revision:1,createdAt:ne,updatedAt:ne,workspace:{name:t.workspace.name,rootRef:"."},target:te,state:Y?"decision-required":"awaiting-approval",policy:N,approval:{required:true,status:"pending"},preconditions:u,adapterEvaluations:le,checkpoint:{status:B.length>0?"pending":"unavailable",files:K.entries},stages:w,...Y?{decision:{reason:[...new Set(pe)].join(" "),options:[...C],causes:X}}:{},events:[],integrity:{sourceEvidenceHash:ae,planHash:Fe({sourceEvidenceHash:ae,target:te,policy:N,preconditions:u,adapterEvaluations:le,stages:w,checkpointFiles:K.entries})}};I(J,"planned",Y?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(J,c,"Workspace repair transaction");let me=await wa(r,J);if(me)return me;let p=se(r,re);return await k.ensureDir(p),await U(qe(r,re),t),await U(Pe(r,re),J),await U(c$1.join(r,b),J),J}async function tt(e,a={}){let r=e.proposal.goalId;if(!r)return ua(e,a);let t=c$1.resolve(e.workspacePath);return c$2(t,`.workspai/goals/${r}/repair-proposal`,()=>ua({...e,workspacePath:t},a))}async function ua(e$1,a$3={}){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));if(t.goalId){let p=await l({workspacePath:r,goalId:t.goalId});if(!p.active||p.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(p.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${p.goalPack?.state??"missing"}`);if((p.active.repairTransactionIds??(p.active.repairTransactionId?[p.active.repairTransactionId]:[])).length>=p.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${p.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(p.goalPack.scope.kind==="project"||p.goalPack.scope.kind==="project-set"){let A=p.goalPack.scope.projects;if(!t.projectName||!A.includes(t.projectName))throw new Error(p.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${A[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${A.join(", ")}).`)}}let o=e$1.maxRisk??"guarded",s={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d=[],i=[],g=new Set(["replan","manual-repair","cancel"]),n=await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"));d.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let f;try{f=await Ha({workspacePath:r,proposal:t});}catch(p){i.push(p instanceof Error?p.message:String(p));}if(f&&(t.projectName||t.projectPath)&&(t.projectPath=c$1.relative(r,f).split(c$1.sep).join("/")),t.projectPath){let p=f??c$1.resolve(r,t.projectPath),l=await k.lstat(p).catch(()=>{});(!l?.isDirectory()||l.isSymbolicLink())&&i.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(p=>({...p,cwd:ca(r,p.cwd,f)}));let m=new Set,b$1=new Set,R=0;for(let p of t.changes){p.path=ca(r,p.path,f),p.path==="."&&i.push(`${p.id} cannot replace the workspace root.`),m.has(p.id)&&i.push(`Duplicate proposal change id: ${p.id}.`),b$1.has(p.path)&&i.push(`Multiple proposal changes target ${p.path}.`),m.add(p.id),b$1.add(p.path),R+=Buffer.byteLength(p.content??"","utf8"),R>Ta&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let l=ja(p.path);if(l&&i.push(`${p.path}: ${l}`),p.operation==="write"){let A=za(p.path,p.content);A&&i.push(A);}if(O[p.risk]>O[o]&&(i.push(`${p.id} exceeds the approved ${o} risk ceiling.`),g.add(p.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let A=c$1.resolve(r,t.projectPath),q=c$1.resolve(r,p.path);E(A,q)||i.push(`${p.path} escapes the declared project scope.`);}}let x=[...b$1].sort(),$=await ye(r,x,f);i.push(...$.errors);let N=new Map($.entries.map(p=>[p.path,p]));for(let p of t.changes){let l=N.get(p.path);if(!l||l.beforeHash!==p.expectedBeforeHash){i.push(`${p.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}p.operation==="delete"&&!l.existed&&i.push(`${p.path} cannot be deleted because it does not exist.`),p.operation==="write"&&l.beforeHash!==null&&S(p.content??"")===l.beforeHash&&i.push(`${p.path} is a no-op and cannot prove source progress.`);}d.push({id:"proposal-boundary",status:i.length===0?"passed":"failed",message:i.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(i)].join(" ")});let u=new Set;if(t.projectPath)u.add(f??c$1.resolve(r,t.projectPath));else for(let p of t.changes)u.add(await Ya(r,p.path));let h=await et({workspacePath:r,proposal:t,projectRoots:[...u].sort(),maxRisk:o,policy:s,dependencies:a$3});i.push(...h.blockers);let w=h.stages,W=w.some(p=>p.status!=="skipped"&&["audit","test","build"].includes(p.kind));d.push({id:"validation-coverage",status:W?"passed":"unknown",message:W?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let V=[...new Set([...x,...h.checkpointFiles])].sort(),j=await ye(r,V,f);i.push(...j.errors),d.push({id:"checkpoint-boundary",status:j.errors.length===0?"passed":"failed",message:j.errors.length===0?`${j.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:j.errors.join(" ")});let C=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(p=>({id:`proposal:${p.id}`,kind:"repair",status:O[p.risk]<=O[o]?"pending":"blocked",required:true,risk:p.risk,summary:p.summary,changedPaths:[p.path]})),...w,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d.push(...await De({workspacePath:r,stages:C,toolAvailable:a$3.toolAvailable}));let ee=new Set(C.map(p=>p.id));ee.size!==C.length&&i.push("Repair proposal stage ids must be unique."),d.push({id:"stage-identity",status:ee.size===C.length?"passed":"failed",message:ee.size===C.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let p=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true});if(!t.targetActionIds?.length){let L=p.actions.filter(T=>T.cardId===t.cardId&&(!t.projectName||T.projectName===t.projectName)&&(!t.projectPath||T.projectPath===t.projectPath)).map(T=>T.id).sort();L.length>0&&(t.targetActionIds=L);}let l=new Set(t.targetActionIds??[]),A=p.actions.filter(L=>l.has(L.id)),q=va(A);q&&d.push(q);}catch{}let B=S(G(t)),K={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(p=>`proposal:${p.id}`)},ae=F(a$3.now),_=`repair_${randomUUID().replaceAll("-","")}`,ne=d.some(p=>p.status==="failed")||i.length>0,re=[...i,...d.filter(p=>p.status==="failed"&&p.id!=="proposal-boundary").map(p=>p.message)],Y=ma({adapters:h.adapters,preconditions:d,stages:C,decisionOptions:g,maxRisk:o,fallbackReasons:re});for(let p of t.changes)O[p.risk]<=O[o]||Y.push({kind:"risk-approval",id:`risk:${p.id}`,message:`${p.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let pe=Y.length>0&&Y.every(p=>p.kind==="failed-precondition")&&d.some(p=>p.id==="proposal-boundary"&&p.status==="failed"),le=pe?["replan","cancel"]:[...g],X={schemaVersion:a,transactionId:_,revision:1,createdAt:ae,updatedAt:ae,workspace:{name:await Ja(r),rootRef:"."},target:K,state:ne?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d,adapterEvaluations:h.adapters,checkpoint:{status:"pending",files:j.entries},stages:C,...ne?{decision:{reason:[...new Set(re)].join(" "),options:le,causes:Y}}:{},events:[],integrity:{sourceEvidenceHash:B,planHash:Fe({sourceEvidenceHash:B,target:K,policy:s,preconditions:d,adapterEvaluations:h.adapters,stages:C,checkpointFiles:j.entries})}};I(X,"planned",ne?pe?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(X,c,"Workspace repair transaction");let J=await wa(r,X);if(J)return J;let me=se(r,_);return await k.ensureDir(me),await U(qe(r,_),t),await U(Pe(r,_),X),await U(c$1.join(r,b),X),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:_}),X}async function Ft(e,a={}){let r=await ie(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Oe(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=D("The compiled repair plan changed after planning.",["cancel"]),await P(e.workspacePath,r,a.now),r;let t=await Re(e.workspacePath,e.transactionId);return S(G(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=D("The persisted source plan changed after planning.",["cancel"]),await P(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:F(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",I(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await P(e.workspacePath,r,a.now),r)}async function Ia(e,a){let r=c$1.join(e,Ne,Ca);await k.ensureDir(c$1.dirname(r));try{let t=await k.stat(r),o=await k.readJson(r).catch(()=>({})),s=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,i=false;if((!s||s===hostname())&&d)try{process.kill(d,0),i=true;}catch(n){i=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let g=!!(s&&s!==hostname());!i&&!g&&Date.now()-t.mtimeMs>Na&&await k.remove(r);}catch{}try{await k.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
2
+ `,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await k.readJson(r).catch(async()=>{let o=await k.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await k.remove(r);}}async function Ea(e){let a=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):void 0,r=await ye(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let s=t.get(o.path);if(!s||o.existed!==s.existed||o.beforeHash!==s.beforeHash||o.mode!==s.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function rt(e){if(e.transaction.checkpoint.status==="captured")return;await Ea(e);let a=c$1.join(se(e.workspacePath,e.transaction.transactionId),ia);await k.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=c$1.resolve(e.workspacePath,t.path),s=t.existed?await k.readFile(o):void 0;if(s&&S(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${ia}/${String(r).padStart(4,"0")}.bin`;if(s){let i=c$1.join(se(e.workspacePath,e.transaction.transactionId),d),g=`${i}.${process.pid}.${randomUUID()}.tmp`;await k.writeFile(g,s,{flag:"wx"});let n=await k.readFile(g);if(S(n)!==t.beforeHash)throw await k.remove(g),new Error(`Checkpoint backup verification failed for ${t.path}.`);await k.move(g,i,{overwrite:true}),t.backupRef=d;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=F(e.now),e.transaction.state="checkpointed",I(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function ha(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),o=await k.readFile(t).catch(()=>{});r.afterHash=o?S(o):null;}}function je(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function He(e,a,r,t=[]){let o=c$1.resolve(e,a.cwd);if(!(E(e,o)||t.some(n=>E(n,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(n=>!n||/[\0\r\n]/.test(n)))throw new Error("Invocation contains invalid arguments.");let d=je(a.executable),i=c$1.isAbsolute(a.executable),g=/^\.{1,2}[\\/]/.test(a.executable);if(i&&!E(e,a.executable)&&!t.some(n=>E(n,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!i&&!g&&!Fa.has(d))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(n=>/^(?:--force|-f)$/i.test(n)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(n=>/(?:breaking|legacy-peer-deps)/i.test(n)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(d)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${d} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function We(e){let a=e.projectBoundary?[c$1.resolve(e.projectBoundary)]:[],r=He(e.workspacePath,e.invocation,e.policy,a),t=await k.lstat(r.cwd).catch(()=>{});if(!t?.isDirectory()||t.isSymbolicLink()||!await H(e.projectBoundary??e.workspacePath,r.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(r.executable)||/^\.{1,2}[\\/]/.test(r.executable)){let d=c$1.isAbsolute(r.executable)?r.executable:c$1.resolve(r.cwd,r.executable);if(!await H(e.projectBoundary??e.workspacePath,d))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(r.executable,e.invocation.args,{cwd:r.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ka,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}function ot(e){let a=j.find(t=>t.cardId===e);if(!a)throw new Error(`No canonical producer is registered for repair card ${e}.`);let r=a.verifyCommand.trim().split(/\s+/);if(r[0]!=="npx"||r[1]!=="workspai"||r.length<3)throw new Error(`Repair card ${e} publishes an invalid canonical producer command.`);return r.slice(2)}async function st(e){let a=j.find(n=>n.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await k.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);if(!await H(e.workspacePath,t))throw new Error("The target producer working directory escapes the workspace boundary.");let o=c$1.resolve(t,a.producerArtifact);if(!E(t,o)||!await H(t,c$1.dirname(o)))throw new Error("The target producer artifact escapes its canonical scope.");let s=await k.stat(o).catch(()=>{}),d=Object.fromEntries(Object.entries(process.env).filter(([n])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(n))),i=await execa(process.execPath,[r,...ot(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:ka,stdin:"ignore",extendEnv:false,env:{...d,NO_COLOR:"1",CI:process.env.CI??"1"}}),g=await k.stat(o).catch(()=>{});return {exitCode:i.exitCode??null,stdout:i.stdout??"",stderr:i.stderr??"",evidenceProduced:!!(g?.isFile()&&(!s||g.mtimeMs!==s.mtimeMs||g.ctimeMs!==s.ctimeMs||g.size!==s.size))}}async function it(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=oe(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=oe(e.sourcePlan)?a.actions.filter(s=>t?r.has(s.id):s.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||s.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||s.projectPath===e.transaction.target.projectPath)):a.actions.filter(s=>r.has(s.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function nt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(g=>!g.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(g=>g.id)),o=a.filter(g=>!t.has(g)),s=e.transaction.preconditions.map(g=>g.id).find(g=>g.startsWith(Ce))?.slice(Ce.length),d=r.actions.filter(g=>t.has(g.id)&&a.includes(g.id)),i=o.length===0&&!!s&&ba(d)!==s;return {current:o.length===0&&!i,missingActionIds:o,semanticDrift:i}}function z(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function ct(e,a){if(a.type==="file-create")return i({projectPath:e,operation:a});if(a.type==="file-append")return j$1({projectPath:e,operation:a});if(a.type==="file-copy")return k$1({projectPath:e,operation:a});if(a.type==="package-json-script")return h$2({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m$1({projectPath:e,operation:a});if(a.type==="env-key-add")return n({projectPath:e,operation:a});if(a.type==="makefile-target")return o({projectPath:e,operation:a})}async function dt(e){let a=c$1.resolve(e.workspacePath,e.change.path),r=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):e.workspacePath;if(!E(r,a)||!await H(r,a))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=ja(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(m=>m.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let s=await k.readFile(a).catch(()=>{}),d=s?S(s):null;if(d!==o.beforeHash||d!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let i=await k.lstat(a).catch(()=>{});if(i?.isSymbolicLink()||i&&!i.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!i)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await k.remove(a);return}let g=e.change.content??"";if(Buffer.byteLength(g,"utf8")>fa)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await k.ensureDir(c$1.dirname(a));let n=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await k.writeFile(n,g,{encoding:"utf8",flag:"wx"}),await k.move(n,a,{overwrite:true});let f=await k.readFile(a);if(S(f)!==S(g))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function ga(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=F(e.dependencies.now),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):st))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=z(r.stdout),e.stage.stderrTail=z(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=z(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await nt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let s=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${s} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await dt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=xe(a.action);if(r){let t=ke(e.workspacePath,a.action);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);await ct(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??We)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:ve(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=z(t.stdout),e.stage.stderrTail=z(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??We)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:ve(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=z(a.stdout),e.stage.stderrTail=z(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=F(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await ha(e.workspacePath,e.transaction),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=F(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ha(e.workspacePath,e.transaction),I(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false}}async function fe(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",I(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);let r=async s=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=D(s,["manual-repair","cancel"]),I(e.transaction,"decision",s,{status:"conflicted",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let s of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,s.path),i=e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):e.workspacePath;if(!E(i,d)||!await H(i,d))return r(`Rollback refused because ${s.path} escaped the canonical repair boundary.`);let g=await k.lstat(d).catch(()=>{});if(g?.isSymbolicLink()||g&&!g.isFile())return r(`Rollback refused because ${s.path} is no longer a regular file.`);let n=g?await k.readFile(d):void 0,f=n?S(n):null,m=s.afterHash!==void 0&&f===s.afterHash,b=a&&f===s.beforeHash;if(!m&&!b)return r(`Rollback refused because ${s.path} changed outside this transaction.`);if(!s.existed){t.push({entry:s,absolute:d});continue}if(!s.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${s.path}.`);let R=c$1.join(se(e.workspacePath,e.transaction.transactionId),s.backupRef),x=await k.lstat(R).catch(()=>{});if(!x?.isFile()||x.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${s.path}.`);let $=await k.readFile(R);if(S($)!==s.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${s.path}.`);t.push({entry:s,absolute:d,backup:$});}for(let s of t){if(!s.entry.existed){await k.remove(s.absolute);continue}let d=s.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${s.entry.path}.`);let i=c$1.join(c$1.dirname(s.absolute),`.${c$1.basename(s.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await k.ensureDir(c$1.dirname(s.absolute)),await k.writeFile(i,d,{flag:"wx"}),s.entry.mode!==void 0&&await k.chmod(i,s.entry.mode),await k.move(i,s.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=F(e.dependencies.now);let o=e.transaction.stages.filter(s=>s.kind==="reconcile"&&s.invocation);for(let s of o){let d=s.invocation;if(!d)continue;let i=`rollback:${s.id}`,g=e.transaction.stages.find(m=>m.id===i&&m.kind==="rollback"),n=g??{id:i,kind:"rollback",status:"pending",required:true,risk:s.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};g||e.transaction.stages.push(n),n.status="running",n.startedAt=F(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,I(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now);let f;try{f=await(e.dependencies.runInvocation??We)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy,projectBoundary:ve(e.workspacePath,e.transaction)});}catch(m){f={exitCode:null,stdout:"",stderr:m instanceof Error?m.message:String(m)};}if(n.exitCode=f.exitCode,n.stdoutTail=z(f.stdout),n.stderrTail=z(f.stderr),n.completedAt=F(e.dependencies.now),f.exitCode!==0)return n.status="failed",n.summary=f.stderr||f.stdout||`Rollback reconciliation exited with ${f.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=D(`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,["manual-repair","cancel"]),I(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",I(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,I(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await P(e.workspacePath,e.transaction,e.dependencies.now),true}async function Ot(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Ia(r,e.transactionId);try{let o=await ie({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(Oe(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=D("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),I(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await P(r,o,a.now),o;let s=await Re(r,e.transactionId);if(S(G(s))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=D("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),I(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await P(r,o,a.now),o;if(o.state==="approved"&&oe(s)&&s.goalId){let h=await l({workspacePath:r,goalId:s.goalId}),w=h.active?.repairTransactionIds??(h.active?.repairTransactionId?[h.active.repairTransactionId]:[]);if(h.index.activeGoalId!==s.goalId||!w.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let i=(await De({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(h=>h.status==="failed");if(i){let h=o.stages.find(w=>w.invocation&&`tool:${w.invocation.cwd}:${w.invocation.executable}`===i.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=D(`${i.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:i.id,message:i.message,...h?{executable:h}:{}}),I(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await P(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await fe({workspacePath:r,transaction:o,dependencies:a}),o}let g=new Map(oe(s)?s.changes.map(h=>[`proposal:${h.id}`,{kind:"proposal",change:h}]):s.actions.map(h=>[`action:${h.id}`,{kind:"canonical",action:h}]));try{await Ea({workspacePath:r,transaction:o});}catch(h){return o.approval.status="expired",o.state="decision-required",o.decision=D(h instanceof Error?h.message:String(h),["cancel"]),I(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await P(r,o,a.now),o}let n=o.stages.find(h=>h.id==="target-precondition");if(!n)return o.approval.status="expired",o.state="decision-required",o.decision=D("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await P(r,o,a.now),o;if(!await ga({workspacePath:r,transaction:o,stage:n,actions:g,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=D(`Target precondition failed before checkpoint: ${n.summary}`,["cancel"]),I(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await P(r,o,a.now),o;try{await rt({workspacePath:r,transaction:o,now:a.now});}catch(h){return o.approval.status="expired",o.state="decision-required",o.decision=D(h instanceof Error?h.message:String(h),["cancel"]),I(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await P(r,o,a.now),o}o.state="executing",await P(r,o,a.now);for(let h of o.stages.filter(w=>w.id!=="target-precondition"&&w.id!=="canonical-verify"&&w.kind!=="rollback"))if(!await ga({workspacePath:r,transaction:o,stage:h,actions:g,dependencies:a})&&h.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D(`Required stage ${h.id} failed: ${h.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await fe({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let m=o.stages.find(h=>h.id==="canonical-verify");if(!m)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await fe({workspacePath:r,transaction:o,dependencies:a}),o;m.status="running",m.startedAt=F(a.now),I(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:m.id,status:"running",now:a.now}),await P(r,o,a.now);let b;try{b=a.verify?await a.verify(r):await c$3({workspacePath:r,strict:true,agent:"generic"});}catch(h){b={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},m.stderrTail=z(h instanceof Error?h.message:String(h));}let R=b.status==="passed"&&b.exitCode===0?"passed":b.status==="failed"||b.exitCode===1?"failed":"blocked",x=await it({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:R}),$=x.status==="passed"&&R!=="failed",N,u;if($&&oe(s)&&s.goalId){let h=await a$3(r);if(h.status==="miss")$=false,u=`Goal-bound repair could not seal its post-repair Model/Graph source state (${h.reason}).`;else {let w=h.graph.source.inputs?.hash;w?N={modelHash:d(h.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$4(h.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:w}:($=false,u="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return m.status=$?"passed":"failed",m.completedAt=F(a.now),m.exitCode=b.exitCode,m.summary=$&&R==="passed"?"Selected repair target and canonical workspace verification passed.":$?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":u||(x.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${R}.`),o.verification={status:$?"passed":"failed",targetStatus:x.status,workspaceStatus:R,remainingActionIds:x.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:b.exitCode,summary:m.summary,...N?{sourceBinding:N}:{}},I(o,"verification",m.summary,{stageId:m.id,status:m.status,now:a.now}),$?(o.state="closed",delete o.decision,I(o,"closed",m.summary,{status:"passed",now:a.now}),o.integrity.closureHash=xa(o),await P(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=D(m.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await P(r,o,a.now),o.policy.autoRollback&&await fe({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function pt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Ia(r,e.transactionId);try{let o=await ie({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await fe({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function Ht(e,a={}){let r=await ie(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,I(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await P(e.workspacePath,r,a.now),r}async function Mt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ie({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 pt({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,I(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 P(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Re(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,I(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await P(r,t,a.now);let s={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(oe(o))return tt({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return at({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function lt(e){let a=c$1.join(e,Ne,"transactions"),r=await k.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>ie({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}export{Ft as approveWorkspaceRepair,Dt as assertClosedGoalRepairTransactionCurrent,Ht as cancelWorkspaceRepair,Mt as decideWorkspaceRepair,ot as exactCardProducerArgs,Ot as executeWorkspaceRepair,qt as inspectWorkspaceRepairCapabilities,lt as listWorkspaceRepairTransactions,at as planWorkspaceRepair,tt as planWorkspaceRepairProposal,ie as readWorkspaceRepairTransaction,pt as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-GGOQHTZV.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-W6FHVXNL.js';
package/docs/README.md CHANGED
@@ -8,28 +8,30 @@ Start with the [main README](../README.md) for the product overview, or use the
8
8
  quickstart below. `workspai` is the main package and command; `wspai` is only a
9
9
  shorter optional name.
10
10
 
11
- ## Quickstart: connect an existing project
11
+ ## Quickstart: from zero to value in 60 seconds
12
12
 
13
- Connect an existing project without moving it, then create one saved,
14
- checkable view for developers, CI, IDEs, MCP clients, and AI agents:
13
+ You have an existing project. You want AI agents (and your team) to understand
14
+ it as a system—not just a pile of files. Three commands:
15
15
 
16
16
  ```bash
17
- cd /absolute/path/to/project
17
+ # Step 1: Adopt the project (it stays where it is)
18
+ cd /path/to/your/project
18
19
  npx workspai adopt .
19
- ```
20
-
21
- `adopt` keeps the project in place and creates or reuses the minimal default
22
- workspace. Continue from the same project terminal:
23
20
 
24
- ```bash
25
- npx workspai project workspace status --json
21
+ # Step 2: Build the full workspace intelligence
26
22
  npx workspai workspace intelligence run --for-agent generic --strict --json
27
- npx workspai agent bootstrap --for-agent generic --json
23
+
24
+ # Step 3: Check what agents will see
25
+ cat .workspai/reports/workspace-context-agent.json | head -30
28
26
  ```
29
27
 
30
- The first command proves which canonical workspace owns the project. Workspai
31
- uses a gitignored machine-local binding and portable project grounding, so
32
- workspace commands and compatible agents do not need a manual `cd`.
28
+ That is it. Your project now has:
29
+ - A **Workspace Model** describing every project, runtime, and dependency
30
+ - A **Knowledge Graph** with searchable, proof-backed relationships
31
+ - **Agent grounding** files (`AGENTS.md`, Cursor rules, Claude rules, etc.)
32
+ - **Health checks** that name what is broken and why
33
+
34
+ Continue from the same project terminal for any Workspai command—no `cd` needed.
33
35
 
34
36
  Use `generic` for a vendor-neutral context pack, or select a published host
35
37
  target such as `codex`, `claude`, `gemini`, `qwen`, `kimi`, `grok`, `copilot`,