workspai 0.64.0 → 0.65.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 (116) hide show
  1. package/README.md +37 -44
  2. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +4 -0
  3. package/contracts/runtime-command-surface.v1.json +12 -1
  4. package/contracts/workspace-contract.v1.json +51 -6
  5. package/contracts/workspace-intelligence/project-context-agent.v1.json +29 -0
  6. package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +11 -1
  7. package/contracts/workspace-intelligence/workspace-model.v1.json +28 -1
  8. package/contracts/workspace-model-cache.v1.json +4 -0
  9. package/contracts/workspace-repair-capabilities.v1.json +66 -0
  10. package/dist/analyze-5PDVWECJ.js +1 -0
  11. package/dist/autopilot-release-JVIJCTKX.js +1 -0
  12. package/dist/chunk-2C5ZBVBI.js +2 -0
  13. package/dist/{chunk-VB6I52ZT.js → chunk-2RL6RRT2.js} +2 -2
  14. package/dist/{chunk-FQSBOLM7.js → chunk-6JWNDWOA.js} +1 -1
  15. package/dist/chunk-D5YJOQYK.js +1 -0
  16. package/dist/{chunk-2VJUAKMS.js → chunk-DFG33SBR.js} +2 -2
  17. package/dist/chunk-FY4IIAIF.js +1 -0
  18. package/dist/{chunk-KJXMLBSY.js → chunk-HDNATYW7.js} +1 -1
  19. package/dist/chunk-HEZZ72V4.js +94 -0
  20. package/dist/{chunk-KANAJH65.js → chunk-HN7P4T3B.js} +1 -1
  21. package/dist/chunk-J7QYANXK.js +8 -0
  22. package/dist/{chunk-DK6JNE6K.js → chunk-JD3A5QM6.js} +1 -1
  23. package/dist/chunk-KLSSPJTV.js +1 -0
  24. package/dist/{chunk-DOXNVBX6.js → chunk-MDTI3UEB.js} +1 -1
  25. package/dist/chunk-MYJQGGIU.js +5 -0
  26. package/dist/chunk-NOV6723U.js +1 -0
  27. package/dist/chunk-NYEAMMUL.js +1 -0
  28. package/dist/chunk-O5B2L3R2.js +1 -0
  29. package/dist/chunk-OWB5KWSS.js +13 -0
  30. package/dist/chunk-P5PSZQPB.js +2 -0
  31. package/dist/chunk-QI3HG6IG.js +144 -0
  32. package/dist/chunk-SWGSFLTC.js +1 -0
  33. package/dist/chunk-U5FCQTVL.js +4 -0
  34. package/dist/chunk-VVJK5NFY.js +2 -0
  35. package/dist/chunk-VXKWWX7S.js +8 -0
  36. package/dist/chunk-W322YDHS.js +49 -0
  37. package/dist/chunk-WCJU3CFG.js +1 -0
  38. package/dist/chunk-WPRLXKWC.js +8 -0
  39. package/dist/{chunk-ZGS5NKEO.js → chunk-XGE2FDI4.js} +1 -1
  40. package/dist/{chunk-5SFCBZOH.js → chunk-YN5X2FTP.js} +1 -1
  41. package/dist/chunk-YOCN7GF4.js +1 -0
  42. package/dist/chunk-YYQEWAES.js +1 -0
  43. package/dist/chunk-ZEEV5J4I.js +1 -0
  44. package/dist/{create-PWJDTKDN.js → create-ALT2ME6H.js} +1 -1
  45. package/dist/{doctor-CGXY4IDE.js → doctor-RW4R3O5C.js} +1 -1
  46. package/dist/{goal-lifecycle-BRFFTIU2.js → goal-lifecycle-VYOKS6E6.js} +1 -1
  47. package/dist/goal-pack-YWPI43QL.js +1 -0
  48. package/dist/index.js +144 -144
  49. package/dist/{pipeline-DF4UIHAD.js → pipeline-U4N2DVD7.js} +1 -1
  50. package/dist/{project-agent-entry-IWUCV72J.js → project-agent-entry-YAQCHIMP.js} +1 -1
  51. package/dist/project-intelligence-lens-MRQR2LQW.js +1 -0
  52. package/dist/verified-goal-WM34TTGE.js +1 -0
  53. package/dist/{workspace-35Q2IXAR.js → workspace-HGUZWNAB.js} +1 -1
  54. package/dist/{workspace-agent-sync-FFNSW2PD.js → workspace-agent-sync-GEN3KBAX.js} +1 -1
  55. package/dist/{workspace-context-IJ36ZP6G.js → workspace-context-4WIWFW26.js} +1 -1
  56. package/dist/workspace-contract-7DXK4GF5.js +1 -0
  57. package/dist/{workspace-explain-TITIT5XN.js → workspace-explain-TE2LGOAV.js} +1 -1
  58. package/dist/{workspace-foundation-GMGDUMPR.js → workspace-foundation-J3NNRMI3.js} +1 -1
  59. package/dist/workspace-graph-stream-PQI7OGCE.js +1 -0
  60. package/dist/workspace-graph-token-efficiency-2I4X374C.js +1 -0
  61. package/dist/{workspace-intelligence-5NO4K5SC.js → workspace-intelligence-6FS26JOQ.js} +1 -1
  62. package/dist/{workspace-intelligence-runner-FGEBFVVM.js → workspace-intelligence-runner-XYUPCSLN.js} +1 -1
  63. package/dist/workspace-knowledge-graph-SWCKDTPF.js +1 -0
  64. package/dist/workspace-knowledge-graph-contract-L3CLAM2M.js +1 -0
  65. package/dist/{workspace-knowledge-graph-query-ON45H6Y7.js → workspace-knowledge-graph-query-FZXSPWGK.js} +1 -1
  66. package/dist/workspace-knowledge-graph-snapshot-M572JRB4.js +1 -0
  67. package/dist/workspace-mcp-serve-IBMTFQDY.js +3 -0
  68. package/dist/workspace-model-ZL6WCICX.js +1 -0
  69. package/dist/{workspace-onboarding-VS3YYNGK.js → workspace-onboarding-X3PWRIIS.js} +1 -1
  70. package/dist/{workspace-registry-summary-MIDFG6EC.js → workspace-registry-summary-LJN4WHIZ.js} +1 -1
  71. package/dist/workspace-repair-engine-NX7I632M.js +3 -0
  72. package/dist/workspace-run-6GT5OBQ5.js +1 -0
  73. package/dist/{workspace-verify-4R7QHUPO.js → workspace-verify-USRRIM2F.js} +1 -1
  74. package/dist/workspace-watch-43YZPLF7.js +1 -0
  75. package/docs/ci-workflows.md +1 -1
  76. package/docs/commands-reference.md +3 -1
  77. package/docs/workspace-knowledge-graph.md +36 -0
  78. package/docs/workspace-operations.md +22 -0
  79. package/docs/workspace-repair-engine.md +17 -0
  80. package/package.json +1 -1
  81. package/dist/analyze-NUGNB256.js +0 -1
  82. package/dist/autopilot-release-TWJWSVVF.js +0 -1
  83. package/dist/chunk-3A23KJAQ.js +0 -1
  84. package/dist/chunk-4PUJVYRM.js +0 -1
  85. package/dist/chunk-5B2GAZAC.js +0 -5
  86. package/dist/chunk-6DAQ7PYT.js +0 -13
  87. package/dist/chunk-CCAXADKP.js +0 -49
  88. package/dist/chunk-CJHWKXDN.js +0 -1
  89. package/dist/chunk-CT4IODPG.js +0 -2
  90. package/dist/chunk-DWB2RRF4.js +0 -1
  91. package/dist/chunk-ISOOENLW.js +0 -8
  92. package/dist/chunk-J7RU5WR5.js +0 -2
  93. package/dist/chunk-KV6PS54A.js +0 -8
  94. package/dist/chunk-NHTDPXTW.js +0 -4
  95. package/dist/chunk-Q2WF7D5U.js +0 -2
  96. package/dist/chunk-RSG2GJXT.js +0 -2
  97. package/dist/chunk-SFO5GVRT.js +0 -1
  98. package/dist/chunk-T5YRFRJV.js +0 -1
  99. package/dist/chunk-TOYN76K4.js +0 -144
  100. package/dist/chunk-U5WVR74V.js +0 -1
  101. package/dist/chunk-WY4DOMEA.js +0 -1
  102. package/dist/chunk-XKDR5BGS.js +0 -6
  103. package/dist/chunk-ZH7CXQH3.js +0 -94
  104. package/dist/goal-pack-FG3QDNQH.js +0 -1
  105. package/dist/project-intelligence-lens-PZPPSCUW.js +0 -1
  106. package/dist/verified-goal-BBHZRYYH.js +0 -1
  107. package/dist/workspace-contract-JS4LZZQZ.js +0 -1
  108. package/dist/workspace-graph-stream-7UU2YVHC.js +0 -1
  109. package/dist/workspace-graph-token-efficiency-D7CUT6NX.js +0 -1
  110. package/dist/workspace-knowledge-graph-RSDP2E36.js +0 -1
  111. package/dist/workspace-knowledge-graph-snapshot-3FJHH5IK.js +0 -1
  112. package/dist/workspace-mcp-serve-WUIQ2AE6.js +0 -3
  113. package/dist/workspace-model-OKY4CQ3X.js +0 -1
  114. package/dist/workspace-repair-engine-VUBT77Y7.js +0 -3
  115. package/dist/workspace-run-SSF6Z26G.js +0 -1
  116. package/dist/workspace-watch-IOPSHQS5.js +0 -1
@@ -1,4 +1,4 @@
1
- import {c}from'./chunk-KJXMLBSY.js';import {r}from'./chunk-ZH7CXQH3.js';import {a as a$2}from'./chunk-KV6PS54A.js';import {c as c$1}from'./chunk-LPCWROQ3.js';import {a as a$3}from'./chunk-NHTDPXTW.js';import {g}from'./chunk-VB6I52ZT.js';import {f,e as e$1}from'./chunk-ILIBOMYL.js';import {a}from'./chunk-VRGEPPUB.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-JS4LZZQZ.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-FFNSW2PD.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-HDNATYW7.js';import {r}from'./chunk-HEZZ72V4.js';import {a as a$2}from'./chunk-WPRLXKWC.js';import {c as c$1}from'./chunk-LPCWROQ3.js';import {a as a$3}from'./chunk-U5FCQTVL.js';import {g}from'./chunk-2RL6RRT2.js';import {f,e as e$1}from'./chunk-ILIBOMYL.js';import {a}from'./chunk-VRGEPPUB.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-7DXK4GF5.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-GEN3KBAX.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-DK6JNE6K.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-JD3A5QM6.js';
@@ -0,0 +1 @@
1
+ export{b as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,c as PROJECT_GROUNDING_MODE_VALUES,e as WORKSPAI_PROJECT_GROUNDING_END,d as WORKSPAI_PROJECT_GROUNDING_START,f as buildProjectContextAgent,i as resolveWorkspaceProjectLensTargets,g as syncProjectIntelligenceLens,h as syncWorkspaceProjectLenses}from'./chunk-QI3HG6IG.js';
@@ -0,0 +1 @@
1
+ import {c}from'./chunk-NYEAMMUL.js';import {d as d$1}from'./chunk-JQLJBK5N.js';import {a as a$2}from'./chunk-MYJQGGIU.js';import {a as a$1}from'./chunk-U5FCQTVL.js';import {n}from'./chunk-FY4IIAIF.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 n({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 n({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$1=o.projects.filter(g=>{let f=u.resolve(e,g.path);return g.name===i||g.path===i||f===u.resolve(i)});if(n$1.length!==1)throw new Error(n$1.length===0?`Project goal scope was not found: ${i}`:`Project goal scope is ambiguous: ${i}`);let s=n$1[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 n({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$1=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=n$1.length>0?"failed":s.length>0?"unavailable":c.length>0?"below-target":"passed",m=o.map(l=>l.result.measurement.measuredAt).sort(),d=[...n$1.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,measurement:{measuredAt:m[m.length-1]??new Date().toISOString(),value:f,target:e.target,unit:"percent",status:p==="passed"?"satisfied":p==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(o.flatMap(l=>l.result.measurement.evidencePaths))],message:p==="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-VB6I52ZT.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-2RL6RRT2.js';
@@ -1 +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-CCAXADKP.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
+ 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-W322YDHS.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-RSG2GJXT.js';
1
+ export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-2C5ZBVBI.js';
@@ -0,0 +1 @@
1
+ export{g as WORKSPACE_CONTRACT_PATH,i as WORKSPACE_CONTRACT_SCHEMA_VERSION,h as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,j as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,k as WorkspaceContractVerificationError,m as buildWorkspaceContract,q as buildWorkspaceContractGraph,l as discoverProjectJsonFiles,p as readWorkspaceContract,o as syncWorkspaceContract,r as verifyWorkspaceContract,n as writeWorkspaceContract,s as writeWorkspaceContractVerifyEvidence}from'./chunk-P5PSZQPB.js';
@@ -1 +1 @@
1
- export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-6DAQ7PYT.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-CT4IODPG.js';
1
+ export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-OWB5KWSS.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-VVJK5NFY.js';
@@ -1 +1 @@
1
- import {c as c$1}from'./chunk-KANAJH65.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 c$1(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-MIDFG6EC.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
1
+ import {c as c$1}from'./chunk-HN7P4T3B.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 c$1(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-LJN4WHIZ.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
@@ -0,0 +1 @@
1
+ import {b}from'./chunk-VXKWWX7S.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c}from'./chunk-EWZZUQBR.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c({...o,generatedAt:"<ignored>",proofs:o.proofs.map(s=>({...s,observedAt:"<ignored>"}))})}function f(o){return "observedAt"in o?{...o,observedAt:"<ignored>"}:o}function u(o,s){let e=new Map(o.map(r=>[r.id,r])),a=new Map(s.map(r=>[r.id,r])),i=s.filter(r=>!e.has(r.id)),p=s.filter(r=>{let t=e.get(r.id);return t?c(f(t))!==c(f(r)):false}),d=o.filter(r=>!a.has(r.id)).map(r=>r.id);return {added:i,updated:p,removed:d}}function E(o,s){let e=new Map(o.map(a=>[a.id,a]));return s.filter(a=>{let i=e.get(a.id);return !i||c(i)!==c(a)})}function I(o){return a(o,"contracts/workspace-intelligence/workspace-graph-stream.v1.json","Workspace graph stream event"),o}var R=class{previous=null;revision=0;generation=0;workspaceId;sessionId;now;nextCorrelationId;constructor(s){this.workspaceId=`workspace:${g.createHash("sha256").update(H.resolve(s.workspacePath)).digest("hex")}`,this.sessionId=s.sessionId??g.randomUUID(),this.now=s.now??(()=>new Date),this.nextCorrelationId=s.correlationId??(()=>g.randomUUID());}publish(s,e){b(e,s);let a=this.now().toISOString(),i=d(s),p=w(e),d$1=this.nextCorrelationId(),r={schemaVersion:M,workspaceId:this.workspaceId,sessionId:this.sessionId,generation:this.generation,modelHash:i,graphHash:p,generatedAt:a,causationId:d$1,correlationId:d$1};if(!this.previous){let S=I({...r,type:"graph.snapshot",revision:this.revision,payload:{graph:e,reason:"initial"}});return this.previous=e,S}let t=this.previous,W=this.revision,b$1=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$1=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c(t.quality)!==c(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b$1,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$1.added,entitiesUpdated:c$1.updated,entitiesRemoved:c$1.removed,relationsAdded:h.added,relationsUpdated:h.updated,relationsRemoved:h.removed,proofsAdded:l.added,proofsUpdated:l.updated,proofsRemoved:l.removed,providersUpdated:E(t.providers,e.providers),quality:G?e.quality:null,diagnostics:e.diagnostics}});return this.previous=e,A}};export{M as WORKSPACE_GRAPH_STREAM_SCHEMA_VERSION,R as WorkspaceGraphStreamPublisher};
@@ -0,0 +1 @@
1
+ export{a as WORKSPACE_GRAPH_TOKEN_EFFICIENCY_SCHEMA_VERSION,b as buildWorkspaceGraphTokenEfficiencyReport}from'./chunk-YN5X2FTP.js';
@@ -1 +1 @@
1
- export{g as WORKSPACE_IMPACT_REPORT_PATH,f as WORKSPACE_IMPACT_SCHEMA_VERSION,e as WORKSPACE_MODEL_DIFF_REPORT_PATH,c as WORKSPACE_MODEL_DIFF_SCHEMA_VERSION,d as WORKSPACE_MODEL_SNAPSHOT_REPORT_PATH,b as WORKSPACE_MODEL_SNAPSHOT_SCHEMA_VERSION,p as buildWorkspaceImpact,k as buildWorkspaceModelSnapshot,m as diffWorkspaceModel,i as isGitDiffSource,h as migrateLegacyWorkspaceModelSnapshot,j as parseGitDiffRef,o as workspaceVerificationPlan,q as writeWorkspaceImpact,n as writeWorkspaceModelDiff,l as writeWorkspaceModelSnapshot}from'./chunk-CT4IODPG.js';export{d as hashWorkspaceModel}from'./chunk-EWZZUQBR.js';
1
+ export{g as WORKSPACE_IMPACT_REPORT_PATH,f as WORKSPACE_IMPACT_SCHEMA_VERSION,e as WORKSPACE_MODEL_DIFF_REPORT_PATH,c as WORKSPACE_MODEL_DIFF_SCHEMA_VERSION,d as WORKSPACE_MODEL_SNAPSHOT_REPORT_PATH,b as WORKSPACE_MODEL_SNAPSHOT_SCHEMA_VERSION,p as buildWorkspaceImpact,k as buildWorkspaceModelSnapshot,m as diffWorkspaceModel,i as isGitDiffSource,h as migrateLegacyWorkspaceModelSnapshot,j as parseGitDiffRef,o as workspaceVerificationPlan,q as writeWorkspaceImpact,n as writeWorkspaceModelDiff,l as writeWorkspaceModelSnapshot}from'./chunk-VVJK5NFY.js';export{d as hashWorkspaceModel}from'./chunk-EWZZUQBR.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-WY4DOMEA.js';
1
+ export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-NYEAMMUL.js';
@@ -0,0 +1 @@
1
+ export{a as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,b as assertWorkspaceKnowledgeGraphSourceBinding,d as buildWorkspaceKnowledgeGraph,c as computeWorkspaceKnowledgeGraphInputFingerprint,e as knowledgeEntityId}from'./chunk-VXKWWX7S.js';
@@ -0,0 +1 @@
1
+ export{f as WORKSPACE_KNOWLEDGE_CONFIDENCE_LEVELS,d as WORKSPACE_KNOWLEDGE_DERIVATIONS,b as WORKSPACE_KNOWLEDGE_ENTITY_KINDS,g as WORKSPACE_KNOWLEDGE_FRESHNESS_LEVELS,a as WORKSPACE_KNOWLEDGE_GRAPH_SCHEMA_VERSION,c as WORKSPACE_KNOWLEDGE_RELATION_KINDS,e as WORKSPACE_KNOWLEDGE_TRUST_LEVELS}from'./chunk-D5YJOQYK.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_KNOWLEDGE_SEARCH_SCHEMA_VERSION,e as queryKnowledgeEntities,c as queryKnowledgeEvidence,d as queryKnowledgePath,b as resolveKnowledgeTarget,f as searchKnowledgeGraph}from'./chunk-4PUJVYRM.js';
1
+ export{a as WORKSPACE_KNOWLEDGE_SEARCH_SCHEMA_VERSION,e as queryKnowledgeEntities,c as queryKnowledgeEvidence,d as queryKnowledgePath,b as resolveKnowledgeTarget,f as searchKnowledgeGraph}from'./chunk-YOCN7GF4.js';
@@ -0,0 +1 @@
1
+ export{a as readWorkspaceKnowledgeGraphSnapshot}from'./chunk-O5B2L3R2.js';
@@ -0,0 +1,3 @@
1
+ import {b}from'./chunk-OWB5KWSS.js';import {d,c as c$1,f,e as e$2}from'./chunk-YOCN7GF4.js';import {c,e as e$1}from'./chunk-PXWKMPPI.js';import {c as c$2,b as b$3}from'./chunk-YUGKQ44M.js';import {b as b$2}from'./chunk-2C5ZBVBI.js';import {d as d$2}from'./chunk-NOV6723U.js';import {b as b$1}from'./chunk-VXKWWX7S.js';import {i}from'./chunk-FY4IIAIF.js';import {h}from'./chunk-P5PSZQPB.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,i);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);b$1(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$2);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$2,reasons:i});for(let s of i)r.add(s);}}let p=await a(e,h),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:h,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,i);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$2))?.safeCommands??[]};case "getProjectContext":{let n=await a(e$3,b$2);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$3);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$2);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
+ `);}function E(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,error:{code:-32e3,message:t}})}
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};
@@ -0,0 +1 @@
1
+ export{i as WORKSPACE_MODEL_REPORT_PATH,h as WORKSPACE_MODEL_SCHEMA_VERSION,n as buildWorkspaceModel,o as buildWorkspaceModelCached,m as buildWorkspaceModelFacts,p as buildWorkspaceModelIncremental,k as createWorkspaceModelBuildProvenance,l as validateWorkspaceModelStrict,j as workspaceModelProjectTopology,q as writeWorkspaceModel}from'./chunk-FY4IIAIF.js';
@@ -1 +1 @@
1
- export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-FQSBOLM7.js';
1
+ export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-6JWNDWOA.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,b as WORKSPACE_REGISTRY_SUMMARY_SCHEMA_VERSION,f as buildWorkspaceRegistrySummary,g as formatWorkspaceRegistrySyncSummary,e as publishWorkspaceRegistrySummary,d as readWorkspaceRegistrySummary,c as resolveWorkspaceRegisteredProjects}from'./chunk-SFO5GVRT.js';
1
+ export{a as WORKSPACE_REGISTRY_SUMMARY_RELATIVE_PATH,b as WORKSPACE_REGISTRY_SUMMARY_SCHEMA_VERSION,f as buildWorkspaceRegistrySummary,g as formatWorkspaceRegistrySyncSummary,e as publishWorkspaceRegistrySummary,d as readWorkspaceRegistrySummary,c as resolveWorkspaceRegisteredProjects}from'./chunk-KLSSPJTV.js';
@@ -0,0 +1,3 @@
1
+ import {c as c$2}from'./chunk-NYEAMMUL.js';import {d as d$3,i as i$1,j as j$1,k,h as h$1,m as m$1,n,o}from'./chunk-HEZZ72V4.js';import {a as a$2}from'./chunk-WRQWVSBJ.js';import {a,c,h,b,e,j,g,d as d$2}from'./chunk-YYQEWAES.js';import {i}from'./chunk-QI3HG6IG.js';import {l,p}from'./chunk-MDTI3UEB.js';import {a as a$3}from'./chunk-O5B2L3R2.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {p as p$1}from'./chunk-P5PSZQPB.js';import {c as c$1}from'./chunk-CCDGHPEJ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$3,d as d$1}from'./chunk-EWZZUQBR.js';import {e as e$1}from'./chunk-NZ3WZYD5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import d from'path';import {execa}from'execa';import m from'fs-extra';var Le=".workspai/repair",Oa="transaction.json",Ha="source-plan.json",fa="checkpoint",Ma="engine.lock",ja=5*1024*1024,_a=25*1024*1024,La=25*1024*1024,xa=4*1024*1024,Ga=900*1e3,za=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"]),Ka=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),G={safe:0,guarded:1,invasive:2},Va=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 Ja(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function O(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${C(e).slice(0,16)}`,message:r.message??e}]}}function Ia(e){let a=new Map,r=t=>a.set(Ja(t),t);for(let t of e.adapters){(t.support==="unsupported"||t.status==="unsupported")&&r({kind:"unsupported-adapter",id:`adapter:${t.projectPath}:${t.adapterId}`,message:t.message,projectPath:t.projectPath,adapterId:t.adapterId});for(let o of t.missingExecutables)r({kind:"missing-executable",id:`tool:${t.projectPath}:${t.adapterId}:${o}`,message:`Required repair executable is unavailable: ${o} (${t.projectPath}).`,projectPath:t.projectPath,adapterId:t.adapterId,executable:o});}for(let t of e.actions??[]){let o=We(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),G[t.risk]>G[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(i=>i.invocation&&`tool:${i.invocation.cwd}:${i.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${C(t).slice(0,16)}`,message:t});}return [...a.values()]}function H(e){return (e?.()??new Date).toISOString()}function C(e){return createHash("sha256").update(e).digest("hex")}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${K(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function ma(e){return C(K({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function Aa(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=ma(a),t=(await yt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&ma(o)===r);if(t)return await re(d.join(e,b),t),t}var He="causal-action-integrity:";function Ea(e){return C(K([...e].sort((a,r)=>a.id.localeCompare(r.id)).map(a=>({id:a.id,artifactKind:a.artifactKind,cardId:a.cardId,title:a.title,phase:a.phase,scope:a.scope,projectName:a.projectName,projectPath:a.projectPath,sourceStepId:a.sourceStepId,findingId:a.findingId,findingStatus:a.findingStatus,causalKey:a.causalKey,dependsOn:a.dependsOn,strategy:a.strategy,transaction:a.transaction,status:a.status,mode:a.mode,risk:a.risk,requiresApproval:a.requiresApproval,blocker:a.blocker,summary:a.summary,command:a.command,invocation:a.invocation,verifyCommand:a.verifyCommand,cwd:a.cwd,files:a.files,operation:a.operation,rollback:a.rollback,notes:a.notes}))))}function $a(e){if(e.length===0)return;let a=Ea(e);return {id:`${He}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Ua(e){return K({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function ka(e){return new Set(e.map(Ua))}function I(e,a){let r=d.relative(d.resolve(e),d.resolve(a));return r===""||!r.startsWith("..")&&!d.isAbsolute(r)}async function z(e,a){let r=await m.realpath(e).catch(()=>d.resolve(e)),t=d.resolve(a);for(;!await m.pathExists(t);){let i=d.dirname(t);if(i===t)return false;t=i;}let o=await m.realpath(t).catch(()=>d.resolve(t));return I(r,o)}function te(e,a,r){let t=d.isAbsolute(a)?d.resolve(a):d.resolve(e,a);if(!I(e,t)&&!(r&&I(d.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!I(e,t)&&r){let o=d.resolve(r),i=d.relative(o,t).split(d.sep).join("/"),n=`external/${d.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return d.relative(e,t).split(d.sep).join("/")||"."}function X(e){let a=e.replaceAll("\\","/").replace(/^\.\//,""),r=/^external\/([^/]+)(?:\/(.*))?$/.exec(a);if(!r)return;let t=r[2]??"";if(!t.split("/").some(o=>o===".."))return {root:`external/${r[1]}`,suffix:t}}async function T(e){if(d.isAbsolute(e.value))return d.resolve(e.value);let a=X(e.value);if(!a)return d.resolve(e.workspacePath,e.value);if(e.projectBoundary)return d.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$1({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&d.basename(d.resolve(o.externalPath))===a.root.slice(9)||e.projectName!==void 0&&o.slug===e.projectName);if(!t?.externalPath)throw new Error(`Portable external project reference is not canonically registered: ${a.root}`);return d.resolve(t.externalPath,a.suffix||".")}function je(e,a,r,t){let o=te(e,a,r),i=X(o);return !i||!t?o:i.suffix?`${t}/${i.suffix}`:t}async function Ya(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&I(e.workspacePath,a)&&!X(e.proposal.projectPath??""))return a;let{contract:t}=await p$1({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?d.resolve(i.externalPath):d.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,u=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&u});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?d.resolve(o.externalPath):d.resolve(e.workspacePath,o.relativePath)}function ce(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return d.join(e,Le,"transactions",a)}async function ae(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return d.join(ce(e,a),Oa)}function Ge(e,a){return d.join(ce(e,a),Ha)}async function re(e,a){await m.ensureDir(d.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await m.writeJson(r,a,{spaces:2}),await m.move(r,e,{overwrite:true});}function E(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:H(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function x(e,a,r){a.revision+=1,a.updatedAt=H(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(d.join(e,b),a);}async function le(e){let a$2=await m.readJson(Se(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function Ce(e,a){return await m.readJson(Ge(e,a))}function ne(e){return e.schemaVersion===d$2}async function de(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=await T({workspacePath:e,value:t,projectBoundary:r,projectName:a.projectName});if(!I(e,o)&&!X(t)&&!(r&&d.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:te(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Oe(e){return m.readFile(e,"utf8").catch(()=>"")}async function Xa(e){return m.readJson(e).catch(()=>({}))}function wa(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function Za(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=d.extname(e).length>0;return (process.env.PATH??"").split(d.delimiter).filter(Boolean).flatMap(t=>r?[d.join(t,e)]:a.map(o=>d.join(t,`${e}${o}`)))}function ba(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function va(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 Sa(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(d.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=d.isAbsolute(r)?r:d.resolve(a,r),o=await m.stat(t).catch(()=>{});return ba(o)&&va(t,a)}for(let t of Za(r)){let o=await m.stat(t).catch(()=>{});if(ba(o)&&await va(t,a))return true}return false}async function ze(e){let a=new Set;for(let i of e.stages){if(i.kind!=="repair"||!i.invocation)continue;let n=Te(i.invocation.executable);if(!["python","python3","py"].includes(n)||!i.invocation.args.includes("venv")||!i.invocation.args.includes(".venv"))continue;let s=await T({workspacePath:e.workspacePath,value:i.invocation.cwd});a.add(d.normalize(d.join(s,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(i=>i.required&&i.status!=="skipped"&&i.invocation).map(i=>i.invocation),t=new Map;for(let i of r)t.set(`${i.cwd}\0${i.executable}`,i);let o=[];for(let i of t.values()){let n=await T({workspacePath:e.workspacePath,value:i.cwd}),s=d.isAbsolute(i.executable)?d.normalize(i.executable):d.normalize(d.resolve(n,i.executable));if(a.has(s)){o.push({id:`tool:${i.cwd}:${i.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${i.executable} (${i.cwd}).`});continue}let u=await Sa({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:u?"passed":"failed",message:u?`Required repair executable is available: ${i.executable} (${i.cwd}).`:`Required repair executable is unavailable: ${i.executable} (${i.cwd}). Install or configure it, then create a fresh plan.`});}return o}function oe(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function P(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function Qa(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 et(e){let a=await de(e.workspacePath,e.action,e.authorizedProjectRoot),r=X(e.action.projectPath??"")?.root??te(e.workspacePath,a,a),t=async g=>m.pathExists(d.join(a,g)),o=new Set,i=[],n=[],s=g=>`${r}:${e.adapterId}:${g}`,u=g=>g.forEach(f=>o.add(te(e.workspacePath,d.join(a,f),a))),c=g=>{i.push(g),g.required&&g.status==="blocked"&&n.push(g.summary);},p=Qa(e.workspacePath,a,e.action),k=()=>{let g$1=g.find(f=>f.id===e.adapterId);if(!g$1)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:g$1.id,ecosystem:g$1.ecosystem,projectPath:r,manifests:g$1.manifests,support:g$1.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(f=>f.required&&f.invocation).map(f=>f.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${g$1.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let g=await Xa(d.join(a,"package.json")),f=g.scripts&&typeof g.scripts=="object"&&!Array.isArray(g.scripts)?g.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",B=b==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":b==="pnpm"?"pnpm-lock.yaml":b==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";u(["package.json",B]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${b} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:["install"],purpose:"reconcile"})}));let V=v(b==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:b==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return c(P({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:p??V})),c(typeof f.test=="string"&&f.test.trim()?P({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:wa({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):oe(s("test"),"test","No test script is declared.")),c(typeof f.build=="string"&&f.build.trim()?P({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:wa({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):oe(s("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){u(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let g=e.action.transaction?.ecosystem.toLowerCase(),f=d.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=f==="uv"||g==="uv"||await t("uv.lock"),B=!b&&(f==="poetry"||g==="poetry"||await t("poetry.lock")),V=!b&&!B&&["python","python3","py"].includes(f)&&(e.action.invocation?.args??[]).some(M=>M==="venv")&&(e.action.invocation?.args??[]).some(M=>M===".venv"),W=process.platform==="win32"?"python":"python3",D=d.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await m.pathExists(D)||V)&&(W=D);let _=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):B?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&I(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:_})),c(P({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:p}));let L=await Oe(d.join(a,"pyproject.toml")),pe=await t("tests")||/\[tool\.pytest/i.test(L),Z=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pytest"],purpose:"test"}),se=v(B?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:b?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","build"],purpose:"build"});return c(pe?P({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:Z}):oe(s("test"),"test","No Python test surface is declared.")),c(/\[build-system\]/i.test(L)?P({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:se}):oe(s("build"),"build","No Python build contract is declared.")),k()}let w=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let g of w){if(g.adapterId!==e.adapterId)continue;let f=await t(g.manifest)?g.manifest:g.alternateManifest&&await t(g.alternateManifest)?g.alternateManifest:void 0;if(!f)continue;u(g.files),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${f} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.reconcile[0],args:g.reconcile[1],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:p??(g.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:g.audit[0],args:g.audit[1],purpose:"audit"}):void 0)}));let b=await Oe(d.join(a,f)),B=g.manifest==="composer.json"||g.adapterId==="deno"?/["']test["']\s*:/.test(b):g.manifest==="Gemfile"?await t("Rakefile"):true,V=g.manifest==="composer.json"||g.manifest==="deno.json"?/["']build["']\s*:/.test(b):g.manifest==="Gemfile"?(await m.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return c(B?P({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.test[0],args:g.test[1],purpose:"test"})}):oe(s("test"),"test","No test contract is declared.")),c(V?P({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g.build[0],args:g.build[1],purpose:"build"})}):oe(s("build"),"build","No build contract is declared.")),k()}let j=await m.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&j.some(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g)))return u(["Directory.Packages.props","packages.lock.json",...j.filter(g=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(g))]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:p??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),c(P({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),k();let y=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return u(["pom.xml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["dependency:resolve"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:y,args:["package","-DskipTests"],purpose:"build"})})),k();let $=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&$){let g=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return u([$,"gradle.lockfile","gradle/libs.versions.toml"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["dependencies"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:g,args:["build","-x","test"],purpose:"build"})})),k()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let g=q==="deps.edn",f=await Oe(d.join(a,q)),b=g?"clojure":"lein";u([q]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-P"]:["deps"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:p}));let B=!g||/:test\b/.test(f);return c(B?P({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:g?["-M:test"]:["test"],purpose:"test"})}):oe(s("test"),"test","No Clojure :test alias is declared.")),c(g?oe(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):P({id:s("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),k()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(u(["build.sbt"]),c(P({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),c(P({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:p})),c(P({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),c(P({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),c(P({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),k())}async function Ca(e){let a=i=>m.pathExists(d.join(e,i)),r=await m.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(i=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(g.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function at(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 Wa(e,a={}){let r=await de(e.workspacePath,e.action,e.authorizedProjectRoot),t=X(e.action.projectPath??"")?.root??te(e.workspacePath,r,r),o=await Ca(r),i=at(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let c=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[P({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:i,ecosystem:g.find(p=>p.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:c}]}}if(n.length===0){let c=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[P({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:c})],checkpointFiles:[],blockers:[c],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:c}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let c of n){let p=await et({...e,adapterId:c});s.stages.push(...p.stages),s.checkpointFiles.push(...p.checkpointFiles),s.blockers.push(...p.blockers),s.adapters.push(...p.adapters);}s.stages=[...new Map(s.stages.map(c=>[c.id,c])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let u=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let c=new Set(e.action.transaction.requiredStages),p=Te(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],w=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(p)&&k.includes("venv")&&k.includes(".venv");w&&u.add(d.normalize(d.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(j=>j.kind==="reconcile"?w&&c.has("reconcile"):c.has(j.kind)),s.blockers=s.stages.filter(j=>j.required&&j.status==="blocked").map(j=>j.summary);}for(let c of s.adapters){let p=s.stages.filter(w=>w.id.startsWith(`${c.projectPath}:${c.adapterId}:`)),k=[];c.requiredExecutables=[...new Set(p.filter(w=>w.required&&w.invocation).map(w=>w.invocation.executable))];for(let w of p){if(!w.required||!w.invocation)continue;let j=await T({workspacePath:e.workspacePath,value:w.invocation.cwd,projectBoundary:r}),y=d.isAbsolute(w.invocation.executable)?d.normalize(w.invocation.executable):d.normalize(d.resolve(j,w.invocation.executable));u.has(y)||await Sa({workspacePath:e.workspacePath,invocation:w.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||k.push(w.invocation.executable);}c.missingExecutables=[...new Set(k)],c.missingExecutables.length>0&&(c.status="partial",c.message=`Required executable(s) unavailable: ${c.missingExecutables.join(", ")}.`);}if(n.length===1){let c=`:${n[0]}:`;for(let p of s.stages)p.id=p.id.replace(c,":");}return s}async function Jt(e={}){let a=h();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=d.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let i$1=e.project.trim(),n=await i(r),s=i$1.replace(/\\/g,"/").replace(/^\.\//,""),u=d.resolve(r,i$1),c=n.resolved.filter(p=>{let k=I(r,p.projectPath)?te(r,p.projectPath):void 0;return p.name===i$1||k===s||d.resolve(p.projectPath)===u});if(c.length===0){let p=n.skipped.find(k=>k.name===i$1);throw p?new Error(`Registered project is unavailable for repair capability inspection: ${i$1} (${p.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i$1}.`)}if(c.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i$1}.`);t=d.resolve(c[0].projectPath),o=c[0].name;}else {if(t=d.resolve(r,e.projectPath??"."),!I(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=te(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await Ca(t)}}}function We(e){if(e.command){let a=d$3(e.command);if(a)return a}return a$4(e.operation)??void 0}async function tt(e){let a=new Set,r=e.actions[0]?await de(e.workspacePath,e.actions[0]):void 0,t=X(e.actions[0]?.projectPath??"")?e.actions[0]?.projectPath:void 0;for(let o of e.dependencyFiles){let i=await T({workspacePath:e.workspacePath,value:o,projectBoundary:r,projectName:e.actions[0]?.projectName});a.add(je(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await de(e.workspacePath,o),n=X(o.projectPath??"")?i:e.workspacePath;if(!await z(n,i))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${i}`);let s=o.transaction?.kind==="dependency-materialization"&&o.transaction.sourceMutationRequired===false;for(let p of s?[]:o.files){let k=await T({workspacePath:e.workspacePath,value:p,projectBoundary:X(p)?i:void 0,projectName:o.projectName});if(!await z(n,k))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${p}`);a.add(je(e.workspacePath,k,i,X(o.projectPath??"")?o.projectPath:void 0));}let u=We(o);if(!u)continue;let c="path"in u?u.path:void 0;if(c){let p=d.resolve(i,c);if(!await z(n,p))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${c}`);a.add(je(e.workspacePath,p,i,X(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function rt(e,a){if(!a.invocation)return;let r=await de(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ke(e){return C(K({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function Ve(e){return Ke({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function Ta(e){return C(K({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Ut(e){let a=d.resolve(e.workspacePath),r=await le({workspacePath:a,transactionId:e.transactionId}),t=await Ce(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Ve(r)!==r.integrity.planHash||!r.integrity.closureHash||Ta(r)!==r.integrity.closureHash||C(K(t))!==r.integrity.sourceEvidenceHash||!ne(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=await ae(a,r);for(let i of r.checkpoint.files){let n=await T({workspacePath:a,value:i.path,projectBoundary:o,projectName:r.target.projectName});if(!I(a,n)&&!(o&&I(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await m.lstat(n).catch(()=>{});if(!s){if(i.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${i.path}`);continue}if(!s.isFile()||s.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${i.path}`);let u=await m.readFile(n);if(i.afterHash!==C(u))throw new Error(`Goal repair output changed after transaction closure: ${i.path}`);if(i.mode!==void 0&&s.mode!==i.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${i.path}`)}return r.verification.sourceBinding}async function $e(e,a,r){let t=[],o=[],i=0;for(let n of a){let s=await T({workspacePath:e,value:n,projectBoundary:r}),u=r&&I(d.resolve(r),s)?d.resolve(r):e;if(!I(u,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await z(u,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let c=await m.lstat(s).catch(()=>{});if(c?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(c&&!c.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(c&&c.size>ja){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=c?.size??0,i>_a){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let p=c?await m.readFile(s):void 0;t.push({path:n,existed:!!c,beforeHash:p?C(p):null,...c?{mode:c.mode}:{}});}return {entries:t,errors:o}}function Na(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 ot(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 st(e){let a=await m.readJson(d.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():d.basename(e)}function it(e){return za.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function nt(e,a){let r=d.resolve(e,a),t=d.dirname(r);for(;I(e,t);){if((await m.readdir(t).catch(()=>[])).some(it))return t;if(d.resolve(t)===d.resolve(e))break;t=d.dirname(t);}return e}function ct(e,a,r){return r.some(t=>{let o=d.resolve(e,t.path);if(!I(a,o))return false;let i=d.basename(o);return Ka.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function dt(e){let a=!I(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:te(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function lt(e,a){let r=Te(a.executable),[t="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(r);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(s=>/^(?:test|build|check|verify|package)$/i.test(s))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function pt(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?d.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let u=d.resolve(e.workspacePath,s.cwd),c=te(e.workspacePath,u,n),p=await m.lstat(u).catch(()=>{});if(!p?.isDirectory()||p.isSymbolicLink()||!await z(n??e.workspacePath,u)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!I(n,u)){t.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(G[s.risk]>G[e.maxRisk]){t.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:u,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Je(e.workspacePath,k,e.policy,e.projectRoots),lt(s,k);}catch(w){t.push(w instanceof Error?w.message:String(w));continue}a.push(P({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:k})),i.add(`${c}:${s.kind}`);}for(let s of e.projectRoots){let u=dt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),c=await Wa({workspacePath:e.workspacePath,action:u,authorizedProjectRoot:s},e.dependencies);o.push(...c.adapters);let p=ct(e.workspacePath,s,e.proposal.changes);if(p){for(let w of c.checkpointFiles)r.add(w);t.push(...c.blockers);}let k=te(e.workspacePath,s,s);for(let w of c.stages)!p&&!["test","build"].includes(w.kind)||i.has(`${k}:${w.kind}`)||a.push(w);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function ut(e,a$3={}){let r=d.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(h=>h.cardId===e.cardId).filter(h=>!e.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),i=e.actionId?o.filter(h=>h.id===e.actionId):o,n=t.actions.filter(h=>!e.projectName||!h.projectName||h.projectName===e.projectName).sort((h,R)=>h.order-R.order||h.id.localeCompare(R.id)),s=new Map(n.map(h=>[h.id,h])),u=h=>{let R=new Set(h.map(J=>J.id)),F=[...h];for(;F.length>0;){let J=F.pop();for(let U of J?.dependsOn??[]){let Y=s.get(U);!Y||R.has(Y.id)||(R.add(Y.id),F.push(Y));}}return n.filter(J=>R.has(J.id))},c$1=i.filter(h=>h.findingStatus==="blocking"||h.notes.includes("Doctor finding status: blocking")),p=c$1.length>0?c$1:i.filter(h=>h.findingStatus!=="informational"),k=e.actionId?i.filter(h=>h.id===e.actionId):[],w=[...p].sort((h,R)=>{let F=h.status==="ready"||h.status==="review-required"?0:1,J=R.status==="ready"||R.status==="review-required"?0:1;return F-J||h.order-R.order||h.id.localeCompare(R.id)})[0],j=w?p.filter(h=>h.cardId===w.cardId&&h.findingId===w.findingId&&h.causalKey===w.causalKey&&h.projectName===w.projectName&&h.projectPath===w.projectPath):[],y=u(e.actionId?k:j),$=e.maxRisk??"guarded",q={maxRisk:$,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},g=[{id:"workspace-root",status:await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:y.length>0?"passed":"failed",message:y.length>0?`${y.length} governed action(s) selected.`:"No governed remediation action matches this target."}],f=$a(y);f&&g.push(f);let b$1=[],B=[],V=[],W=[],D=new Set(["replan","manual-repair","cancel"]);for(let h of y){let R=We(h),F=await rt(r,h);if(G[h.risk]<=G[$]||(W.push(`${h.id} exceeds the approved ${$} risk ceiling.`),D.add(h.risk==="invasive"?"approve-invasive":"approve-guarded")),(h.status==="blocked"||h.status==="guidance-only")&&W.push(`${h.id} is ${h.status}: ${h.blocker}`),!R&&!F&&W.push(`${h.id} has no typed operation or structured invocation.`),F)try{Je(r,F,q);}catch(U){let Y=U instanceof Error?U.message:String(U);W.push(Y),/Force-based/.test(Y)&&D.add("allow-force"),/Breaking dependency/.test(Y)&&D.add("allow-breaking");}if(b$1.push({id:`action:${h.id}`,kind:"repair",status:R||F?"pending":"blocked",required:true,risk:h.risk,summary:h.summary,...F?{invocation:F}:{}}),h.transaction){let U=await Wa({workspacePath:r,action:h},a$3);b$1.push(...U.stages),B.push(...U.checkpointFiles),W.push(...U.blockers),V.push(...U.adapters);}}let _=[...new Map(b$1.map(h=>[h.id,h])).values()];b$1.splice(0,b$1.length,..._),b$1.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),b$1.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),b$1.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),g.push(...await ze({workspacePath:r,stages:b$1,toolAvailable:a$3.toolAvailable}));let L=await tt({workspacePath:r,actions:y,dependencyFiles:B}),pe=y[0]?await de(r,y[0]):void 0,Z=await $e(r,L,pe);g.push({id:"rollback-coverage",status:y.some(h=>h.mode==="edit-file"||h.mode==="run-command")&&L.length===0?"failed":"passed",message:L.length>0?`${L.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),g.push({id:"structured-execution",status:b$1.some(h=>h.required&&h.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),g.push({id:"checkpoint-boundary",status:Z.errors.length===0?"passed":"failed",message:Z.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":Z.errors.join(" ")});let se=C(K(t)),M=[...new Set(y.map(h=>h.projectPath).filter(Boolean))],xe=[...new Set(y.map(h=>h.projectName).filter(Boolean))],ue=xe.length===1?xe[0]:void 0,Ie=M.length===1&&xe.length<=1,ie={cardId:e.cardId,scope:Ie?"project":"workspace",...ue?{projectName:ue}:{},...M.length===1?{projectPath:M[0]}:{},actionIds:y.map(h=>h.id)},ke=H(a$3.now),he=`repair_${randomUUID().replaceAll("-","")}`,Q=g.some(h=>h.status==="failed")||W.length>0,we=[...W,...g.filter(h=>h.status==="failed").map(h=>h.message)],be=[...new Map(V.map(h=>[`${h.projectPath}:${h.adapterId}`,h])).values()],l=Ia({actions:y,adapters:be,preconditions:g,stages:b$1,decisionOptions:D,maxRisk:$,fallbackReasons:we}),S={schemaVersion:a,transactionId:he,revision:1,createdAt:ke,updatedAt:ke,workspace:{name:t.workspace.name,rootRef:"."},target:ie,state:Q?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:g,adapterEvaluations:be,checkpoint:{status:L.length>0?"pending":"unavailable",files:Z.entries},stages:b$1,...Q?{decision:{reason:[...new Set(we)].join(" "),options:[...D],causes:l}}:{},events:[],integrity:{sourceEvidenceHash:se,planHash:Ke({sourceEvidenceHash:se,target:ie,policy:q,preconditions:g,adapterEvaluations:be,stages:b$1,checkpointFiles:Z.entries})}};E(S,"planned",Q?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let N=await Aa(r,S);if(N)return N;let ge=ce(r,he);return await m.ensureDir(ge),await re(Ge(r,he),t),await re(Se(r,he),S),await re(d.join(r,b),S),S}async function ht(e,a={}){let r=e.proposal.goalId;if(!r)return Pa(e,a);let t=d.resolve(e.workspacePath);return c$1(t,`.workspai/goals/${r}/repair-proposal`,()=>Pa({...e,workspacePath:t},a))}async function Pa(e$1,a$3={}){a$1(e$1.proposal,e,"Workspace repair proposal");let r=d.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal));if(t.goalId){let l$1=await l({workspacePath:r,goalId:t.goalId});if(!l$1.active||l$1.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(l$1.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${l$1.goalPack?.state??"missing"}`);if((l$1.active.repairTransactionIds??(l$1.active.repairTransactionId?[l$1.active.repairTransactionId]:[])).length>=l$1.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${l$1.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(l$1.goalPack.scope.kind==="project"||l$1.goalPack.scope.kind==="project-set"){let N=l$1.goalPack.scope.projects;if(!t.projectName||!N.includes(t.projectName))throw new Error(l$1.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${N[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${N.join(", ")}).`)}}let o=e$1.maxRisk??"guarded",i={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},n=[],s=[],u=new Set(["replan","manual-repair","cancel"]),c$1=await m.pathExists(d.join(r,".workspai-workspace"))||await m.pathExists(d.join(r,".workspai"));n.push({id:"workspace-root",status:c$1?"passed":"failed",message:c$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let p$1;try{p$1=await Ya({workspacePath:r,proposal:t});}catch(l){s.push(l instanceof Error?l.message:String(l));}let k=p$1&&!I(r,p$1)&&t.projectName?`external/${t.projectName}`:void 0;if(p$1&&(t.projectName||t.projectPath)&&(t.projectPath=k??d.relative(r,p$1).split(d.sep).join("/")),t.projectPath){let l=p$1??d.resolve(r,t.projectPath),S=await m.lstat(l).catch(()=>{});(!S?.isDirectory()||S.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(l=>({...l,cwd:je(r,l.cwd,p$1,k)}));let w=new Set,j=new Set,y=0;for(let l of t.changes){l.path=je(r,l.path,p$1,k),l.path==="."&&s.push(`${l.id} cannot replace the workspace root.`),w.has(l.id)&&s.push(`Duplicate proposal change id: ${l.id}.`),j.has(l.path)&&s.push(`Multiple proposal changes target ${l.path}.`),w.add(l.id),j.add(l.path),y+=Buffer.byteLength(l.content??"","utf8"),y>La&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let S=Na(l.path);if(S&&s.push(`${l.path}: ${S}`),l.operation==="write"){let N=ot(l.path,l.content);N&&s.push(N);}if(G[l.risk]>G[o]&&(s.push(`${l.id} exceeds the approved ${o} risk ceiling.`),u.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let N=p$1??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ge=await T({workspacePath:r,value:l.path,projectBoundary:N,projectName:t.projectName});I(N,ge)||s.push(`${l.path} escapes the declared project scope.`);}}let $=[...j].sort(),q=await $e(r,$,p$1);s.push(...q.errors);let g=new Map(q.entries.map(l=>[l.path,l]));for(let l of t.changes){let S=g.get(l.path);if(!S||S.beforeHash!==l.expectedBeforeHash){s.push(`${l.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}l.operation==="delete"&&!S.existed&&s.push(`${l.path} cannot be deleted because it does not exist.`),l.operation==="write"&&S.beforeHash!==null&&C(l.content??"")===S.beforeHash&&s.push(`${l.path} is a no-op and cannot prove source progress.`);}n.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let f=new Set;if(t.projectPath)f.add(p$1??d.resolve(r,t.projectPath));else for(let l of t.changes)f.add(await nt(r,l.path));let b$1=await pt({workspacePath:r,proposal:t,projectRoots:[...f].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...b$1.blockers);let B=b$1.stages,V=B.some(l=>l.status!=="skipped"&&["audit","test","build"].includes(l.kind));n.push({id:"validation-coverage",status:V?"passed":"unknown",message:V?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let W=[...new Set([...$,...b$1.checkpointFiles])].sort(),D=await $e(r,W,p$1);s.push(...D.errors),n.push({id:"checkpoint-boundary",status:D.errors.length===0?"passed":"failed",message:D.errors.length===0?`${D.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:D.errors.join(" ")});let _=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(l=>({id:`proposal:${l.id}`,kind:"repair",status:G[l.risk]<=G[o]?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,changedPaths:[l.path]})),...B,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];n.push(...await ze({workspacePath:r,stages:_,toolAvailable:a$3.toolAvailable}));let L=new Set(_.map(l=>l.id));L.size!==_.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:L.size===_.length?"passed":"failed",message:L.size===_.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let l=false,S=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),N=S.actions.filter(A=>A.cardId===t.cardId&&(!t.projectName||A.projectName===t.projectName)&&(!t.projectPath||A.projectPath===t.projectPath));if(!t.targetActionIds?.length){let A=ka(N);A.size===1?t.targetActionIds=N.map(Da=>Da.id).sort():A.size>1&&(l=true,s.push(`Repair proposal target is ambiguous: ${A.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ge=[...new Set(t.targetActionIds??[])],h=new Set(ge),R=S.actions.filter(A=>h.has(A.id)),F=new Set(R.map(A=>A.id)),J=ge.filter(A=>!F.has(A));J.length>0&&(l=true,s.push(`Repair proposal references stale or unknown causal action ids: ${J.join(", ")}.`)),R.filter(A=>A.cardId!==t.cardId||t.projectName!==void 0&&A.projectName!==t.projectName||t.projectPath!==void 0&&A.projectPath!==t.projectPath).length>0&&(l=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let Y=ka(R);Y.size>1&&(l=true,s.push(`Repair proposal combines ${Y.size} independent causal finding families. Create one transaction per finding family.`)),R.length>0&&!t.blockerSignature&&(l=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(R.map(A=>A.projectName??A.projectPath).filter(A=>!!A)).size>0&&!t.projectName&&!t.projectPath&&(l=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),R.length>0&&R.every(A=>A.mode==="run-command"&&A.transaction?.kind==="dependency-materialization"&&A.transaction.sourceMutationRequired===false)&&(l=true,s.push("The selected causal action is command-owned and declares that source mutation is not required. Execute the canonical action instead of submitting a model source proposal.")),n.push({id:"causal-target-binding",status:!l&&(R.length>0||N.length===0)?"passed":"failed",message:R.length>0?`${R.length} action(s) bind this proposal to one canonical causal target.`:N.length===0?"No canonical remediation action exists; the bounded source proposal remains the explicit target.":"A single canonical causal target is required before source mutation."});let Ue=$a(R);Ue&&n.push(Ue);}catch{}let pe=C(K(t)),Z={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(l=>`proposal:${l.id}`)},se=H(a$3.now),M=`repair_${randomUUID().replaceAll("-","")}`,ue=n.some(l=>l.status==="failed")||s.length>0,Ie=[...s,...n.filter(l=>l.status==="failed"&&l.id!=="proposal-boundary").map(l=>l.message)],ie=Ia({adapters:b$1.adapters,preconditions:n,stages:_,decisionOptions:u,maxRisk:o,fallbackReasons:Ie});for(let l of t.changes)G[l.risk]<=G[o]||ie.push({kind:"risk-approval",id:`risk:${l.id}`,message:`${l.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let ke=ie.length>0&&ie.every(l=>l.kind==="failed-precondition")&&n.some(l=>l.id==="proposal-boundary"&&l.status==="failed"),he=ke?["replan","cancel"]:[...u],Q={schemaVersion:a,transactionId:M,revision:1,createdAt:se,updatedAt:se,workspace:{name:await st(r),rootRef:"."},target:Z,state:ue?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:b$1.adapters,checkpoint:{status:"pending",files:D.entries},stages:_,...ue?{decision:{reason:[...new Set(Ie)].join(" "),options:he,causes:ie}}:{},events:[],integrity:{sourceEvidenceHash:pe,planHash:Ke({sourceEvidenceHash:pe,target:Z,policy:i,preconditions:n,adapterEvaluations:b$1.adapters,stages:_,checkpointFiles:D.entries})}};E(Q,"planned",ue?ke?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(Q,c,"Workspace repair transaction");let we=await Aa(r,Q);if(we)return we;let be=ce(r,M);return await m.ensureDir(be),await re(Ge(r,M),t),await re(Se(r,M),Q),await re(d.join(r,b),Q),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:M}),Q}async function Yt(e,a={}){let r=await le(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Ve(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=O("The compiled repair plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return C(K(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=O("The persisted source plan changed after planning.",["cancel"]),await x(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:H(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",E(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await x(e.workspacePath,r,a.now),r)}async function qa(e,a){let r=d.join(e,Le,Ma);await m.ensureDir(d.dirname(r));try{let t=await m.stat(r),o=await m.readJson(r).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,n=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&n)try{process.kill(n,0),s=true;}catch(c){s=c!==null&&typeof c=="object"&&"code"in c&&c.code==="EPERM";}let u=!!(i&&i!==hostname());!s&&!u&&Date.now()-t.mtimeMs>Ga&&await m.remove(r);}catch{}try{await m.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 m.readJson(r).catch(async()=>{let o=await m.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await m.remove(r);}}async function Ba(e){let a=await ae(e.workspacePath,e.transaction),r=await $e(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let i=t.get(o.path);if(!i||o.existed!==i.existed||o.beforeHash!==i.beforeHash||o.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function gt(e){if(e.transaction.checkpoint.status==="captured")return;await Ba(e);let a=d.join(ce(e.workspacePath,e.transaction.transactionId),fa);await m.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=await ae(e.workspacePath,e.transaction),i=await T({workspacePath:e.workspacePath,value:t.path,projectBoundary:o,projectName:e.transaction.target.projectName}),n=t.existed?await m.readFile(i):void 0;if(n&&C(n)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let s=`${fa}/${String(r).padStart(4,"0")}.bin`;if(n){let u=d.join(ce(e.workspacePath,e.transaction.transactionId),s),c=`${u}.${process.pid}.${randomUUID()}.tmp`;await m.writeFile(c,n,{flag:"wx"});let p=await m.readFile(c);if(C(p)!==t.beforeHash)throw await m.remove(c),new Error(`Checkpoint backup verification failed for ${t.path}.`);await m.move(c,u,{overwrite:true}),t.backupRef=s;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=H(e.now),e.transaction.state="checkpointed",E(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function ya(e,a){let r=await ae(e,a);for(let t of a.checkpoint.files){let o=await T({workspacePath:e,value:t.path,projectBoundary:r,projectName:a.target.projectName}),i=await m.readFile(o).catch(()=>{});t.afterHash=i?C(i):null;}}function Te(e){return d.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Je(e,a,r,t=[]){let o=d.resolve(e,a.cwd);if(!(I(e,o)||t.some(c=>I(c,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(c=>!c||/[\0\r\n]/.test(c)))throw new Error("Invocation contains invalid arguments.");let n=Te(a.executable),s=d.isAbsolute(a.executable),u=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!I(e,a.executable)&&!t.some(c=>I(c,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!s&&!u&&!Va.has(n))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(c=>/^(?:--force|-f)$/i.test(c)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(c=>/(?:breaking|legacy-peer-deps)/i.test(c)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(n)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${n} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function Me(e){let a=e.projectBoundary?[d.resolve(e.projectBoundary)]:[],r=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary}),t=Je(e.workspacePath,{...e.invocation,cwd:r},e.policy,a),o=await m.lstat(t.cwd).catch(()=>{});if(!o?.isDirectory()||o.isSymbolicLink()||!await z(e.projectBoundary??e.workspacePath,t.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(d.isAbsolute(t.executable)||/^\.{1,2}[\\/]/.test(t.executable)){let s=d.isAbsolute(t.executable)?t.executable:d.resolve(t.cwd,t.executable);if(!await z(e.projectBoundary??e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),n=await execa(t.executable,e.invocation.args,{cwd:t.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:xa,stdin:"ignore",extendEnv:false,env:{...i,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:n.exitCode??null,stdout:n.stdout??"",stderr:n.stderr??""}}function ft(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 mt(e){let a=j.find(p=>p.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await m.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?await T({workspacePath:e.workspacePath,value:e.transaction.target.projectPath,projectName:e.transaction.target.projectName}):d.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);let o=a.scope==="project"?t:e.workspacePath;if(!await z(o,t))throw new Error("The target producer working directory escapes the workspace boundary.");let i=d.resolve(t,a.producerArtifact);if(!I(t,i)||!await z(t,d.dirname(i)))throw new Error("The target producer artifact escapes its canonical scope.");let n=await m.stat(i).catch(()=>{}),s=Object.fromEntries(Object.entries(process.env).filter(([p])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(p))),u=await execa(process.execPath,[r,...ft(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:xa,stdin:"ignore",extendEnv:false,env:{...s,NO_COLOR:"1",CI:process.env.CI??"1"}}),c=await m.stat(i).catch(()=>{});return {exitCode:u.exitCode??null,stdout:u.stdout??"",stderr:u.stderr??"",evidenceProduced:!!(c?.isFile()&&(!n||c.mtimeMs!==n.mtimeMs||c.ctimeMs!==n.ctimeMs||c.size!==n.size))}}async function kt(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=ne(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=ne(e.sourcePlan)?a.actions.filter(i=>t?r.has(i.id):i.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||i.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||i.projectPath===e.transaction.target.projectPath)):a.actions.filter(i=>r.has(i.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(i=>i.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function wt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(u=>!u.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(u=>u.id)),o=a.filter(u=>!t.has(u)),i=e.transaction.preconditions.map(u=>u.id).find(u=>u.startsWith(He))?.slice(He.length),n=r.actions.filter(u=>t.has(u.id)&&a.includes(u.id)),s=o.length===0&&!!i&&Ea(n)!==i;return {current:o.length===0&&!s,missingActionIds:o,semanticDrift:s}}function ee(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function bt(e,a){if(a.type==="file-create")return i$1({projectPath:e,operation:a});if(a.type==="file-append")return j$1({projectPath:e,operation:a});if(a.type==="file-copy")return k({projectPath:e,operation:a});if(a.type==="package-json-script")return h$1({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m$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 vt(e){let a=await ae(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!I(a,r)||!await z(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Na(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(k=>k.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await m.readFile(r).catch(()=>{}),n=i?C(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await m.lstat(r).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!s)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await m.remove(r);return}let u=e.change.content??"";if(Buffer.byteLength(u,"utf8")>ja)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await m.ensureDir(d.dirname(r));let c=d.join(d.dirname(r),`.${d.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await m.writeFile(c,u,{encoding:"utf8",flag:"wx"}),await m.move(c,r,{overwrite:true});let p=await m.readFile(r);if(C(p)!==C(u))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function Ra(e){if(e.stage.status==="passed"||e.stage.status==="skipped")return true;if(e.stage.status==="blocked")return false;e.stage.status="running",e.stage.startedAt=H(e.dependencies.now),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.id==="target-precondition"||e.stage.id==="target-producer-verify"){let a=!!(e.dependencies.verify||e.dependencies.targetVerify||e.dependencies.runInvocation||e.dependencies.toolAvailable||e.dependencies.now),r=await(e.dependencies.runTargetProducer??(a?async()=>({exitCode:0,stdout:"",stderr:""}):mt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=ee(r.stdout),e.stage.stderrTail=ee(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=ee(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await wt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let i=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${i} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await vt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=We(a.action);if(r){let t=await de(e.workspacePath,a.action),o=await ae(e.workspacePath,e.transaction)??e.workspacePath;if(!await z(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await bt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=ee(t.stdout),e.stage.stderrTail=ee(t.stderr),t.exitCode!==0)throw new Error(t.stderr||t.stdout||`Repair command exited with ${t.exitCode}.`)}else throw new Error("Repair stage has no typed operation or structured invocation.")}}else if(e.stage.invocation){let a=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=ee(a.stdout),e.stage.stderrTail=ee(a.stderr),a.exitCode!==0)throw new Error(a.stderr||a.stdout||`${e.stage.kind} exited with ${a.exitCode}.`)}return e.stage.status="passed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=e.stage.id==="target-precondition"?`Exact ${e.transaction.target.cardId} target revalidated before mutation.`:e.stage.id==="target-producer-verify"?`Exact ${e.transaction.target.cardId} producer refreshed after mutation.`:`${e.stage.kind} completed.`,await ya(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=H(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ya(e.workspacePath,e.transaction),E(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false}}async function Re(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",E(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=O(n,["manual-repair","cancel"]),E(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ae(e.workspacePath,e.transaction)??e.workspacePath;for(let n of e.transaction.checkpoint.files){let s=await T({workspacePath:e.workspacePath,value:n.path,projectBoundary:o,projectName:e.transaction.target.projectName});if(!I(o,s)||!await z(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let u=await m.lstat(s).catch(()=>{});if(u?.isSymbolicLink()||u&&!u.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let c=u?await m.readFile(s):void 0,p=c?C(c):null,k=n.afterHash!==void 0&&p===n.afterHash,w=a&&p===n.beforeHash;if(!k&&!w)return r(`Rollback refused because ${n.path} changed outside this transaction.`);if(!n.existed){t.push({entry:n,absolute:s});continue}if(!n.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${n.path}.`);let j=d.join(ce(e.workspacePath,e.transaction.transactionId),n.backupRef),y=await m.lstat(j).catch(()=>{});if(!y?.isFile()||y.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let $=await m.readFile(j);if(C($)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:$});}for(let n of t){if(!n.entry.existed){await m.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let u=d.join(d.dirname(n.absolute),`.${d.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await m.ensureDir(d.dirname(n.absolute)),await m.writeFile(u,s,{flag:"wx"}),n.entry.mode!==void 0&&await m.chmod(u,n.entry.mode),await m.move(u,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=H(e.dependencies.now);let i=e.transaction.stages.filter(n=>n.kind==="reconcile"&&n.invocation);for(let n of i){let s=n.invocation;if(!s)continue;let u=`rollback:${n.id}`,c=e.transaction.stages.find(w=>w.id===u&&w.kind==="rollback"),p=c??{id:u,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};c||e.transaction.stages.push(p),p.status="running",p.startedAt=H(e.dependencies.now),delete p.completedAt,delete p.exitCode,delete p.stdoutTail,delete p.stderrTail,E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"running",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now);let k;try{k=await(e.dependencies.runInvocation??Me)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ae(e.workspacePath,e.transaction)});}catch(w){k={exitCode:null,stdout:"",stderr:w instanceof Error?w.message:String(w)};}if(p.exitCode=k.exitCode,p.stdoutTail=ee(k.stdout),p.stderrTail=ee(k.stderr),p.completedAt=H(e.dependencies.now),k.exitCode!==0)return p.status="failed",p.summary=k.stderr||k.stdout||`Rollback reconciliation exited with ${k.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=O(`Source files were restored, but the installed dependency tree could not be reconciled: ${p.summary}`,["manual-repair","cancel"]),E(e.transaction,"decision",e.transaction.decision.reason,{stageId:p.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),false;p.status="passed",p.summary="Installed dependency tree reconciled with the restored source state.",E(e.transaction,"rollback",p.summary,{stageId:p.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,E(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await x(e.workspacePath,e.transaction,e.dependencies.now),true}async function Xt(e,a={}){let r=d.resolve(e.workspacePath),t=await qa(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["approved","checkpointed","executing","verifying","rollback-required","rolling-back"].includes(o.state))throw new Error(`Repair transaction cannot execute from state ${o.state}.`);if(o.approval.status!=="approved"||o.approval.approvedPlanHash!==o.integrity.planHash)throw new Error("Repair approval is missing, expired, or bound to another plan revision.");if(Ve(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;let i=await Ce(r,e.transactionId);if(C(K(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=O("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),E(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await x(r,o,a.now),o;if(o.state==="approved"&&ne(i)&&i.goalId){let f=await l({workspacePath:r,goalId:i.goalId}),b=f.active?.repairTransactionIds??(f.active?.repairTransactionId?[f.active.repairTransactionId]:[]);if(f.index.activeGoalId!==i.goalId||!b.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let s=(await ze({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(f=>f.status==="failed");if(s){let f=o.stages.find(b=>b.invocation&&`tool:${b.invocation.cwd}:${b.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=O(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...f?{executable:f}:{}}),E(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await x(r,o,a.now),o}if(o.state==="rollback-required"||o.state==="rolling-back"){if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required to resume rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}let u=new Map(ne(i)?i.changes.map(f=>[`proposal:${f.id}`,{kind:"proposal",change:f}]):i.actions.map(f=>[`action:${f.id}`,{kind:"canonical",action:f}]));try{await Ba({workspacePath:r,transaction:o});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await x(r,o,a.now),o}let c=o.stages.find(f=>f.id==="target-precondition");if(!c)return o.approval.status="expired",o.state="decision-required",o.decision=O("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await x(r,o,a.now),o;if(!await Ra({workspacePath:r,transaction:o,stage:c,actions:u,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=O(`Target precondition failed before checkpoint: ${c.summary}`,["cancel"]),E(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await x(r,o,a.now),o;try{await gt({workspacePath:r,transaction:o,now:a.now});}catch(f){return o.approval.status="expired",o.state="decision-required",o.decision=O(f instanceof Error?f.message:String(f),["cancel"]),E(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await x(r,o,a.now),o}o.state="executing",await x(r,o,a.now);for(let f of o.stages.filter(b=>b.id!=="target-precondition"&&b.id!=="canonical-verify"&&b.kind!=="rollback"))if(!await Ra({workspacePath:r,transaction:o,stage:f,actions:u,dependencies:a})&&f.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(`Required stage ${f.id} failed: ${f.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(f=>f.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=H(a.now),E(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await x(r,o,a.now);let w;try{w=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(f){w={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},k.stderrTail=ee(f instanceof Error?f.message:String(f));}let j=w.status==="passed"&&w.exitCode===0?"passed":w.status==="failed"||w.exitCode===1?"failed":"blocked",y=await kt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:j}),$=y.status==="passed"&&j!=="failed",q,g;if($&&ne(i)&&i.goalId){let f=await a$3(r);if(f.status==="miss")$=false,g=`Goal-bound repair could not seal its post-repair Model/Graph source state (${f.reason}).`;else {let b=f.graph.source.inputs?.hash;b?q={modelHash:d$1(f.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$3(f.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:b}:($=false,g="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return k.status=$?"passed":"failed",k.completedAt=H(a.now),k.exitCode=w.exitCode,k.summary=$&&j==="passed"?"Selected repair target and canonical workspace verification passed.":$?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":g||(y.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${j}.`),o.verification={status:$?"passed":"failed",targetStatus:y.status,workspaceStatus:j,remainingActionIds:y.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:w.exitCode,summary:k.summary,...q?{sourceBinding:q}:{}},E(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),$?(o.state="closed",delete o.decision,E(o,"closed",k.summary,{status:"passed",now:a.now}),o.integrity.closureHash=Ta(o),await x(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=O(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await x(r,o,a.now),o.policy.autoRollback&&await Re({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Pt(e,a={}){let r=d.resolve(e.workspacePath),t=await qa(r,e.transactionId);try{let o=await le({workspacePath:r,transactionId:e.transactionId});if(!["checkpointed","executing","verifying","rollback-required","rolling-back","decision-required","failed"].includes(o.state))throw new Error(`Repair transaction cannot roll back from state ${o.state}.`);if(!["captured","restored"].includes(o.checkpoint.status))throw new Error("A captured checkpoint is required for rollback.");return await Re({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function Zt(e,a={}){let r=await le(e);if(["closed","rolled-back","cancelled"].includes(r.state))return r;if(r.checkpoint.status==="captured")throw new Error("Rollback a mutated transaction before cancelling it.");return r.state="cancelled",r.approval.status=r.approval.status==="approved"?"expired":r.approval.status,E(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await x(e.workspacePath,r,a.now),r}async function Qt(e,a={}){let r=d.resolve(e.workspacePath),t=await le({workspacePath:r,transactionId:e.transactionId});if(t.state!=="decision-required"||!t.decision)throw new Error(`Repair transaction is not awaiting a decision: ${t.state}`);if(!t.decision.options.includes(e.decision))throw new Error(`Decision ${e.decision} is not available. Allowed: ${t.decision.options.join(", ")}.`);if(e.decision==="rollback")return 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,E(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await x(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Ce(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,E(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await x(r,t,a.now);let i={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(ne(o))return ht({workspacePath:r,proposal:o,...i},a);let n=t.target.actionIds.map(s=>s.startsWith("action:")?s.slice(7):s);return ut({workspacePath:r,cardId:t.target.cardId,...n.length===1?{actionId:n[0]}:{},projectName:t.target.projectName,...i},a)}async function yt(e){let a=d.join(e,Le,"transactions"),r=await m.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>le({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{Yt as approveWorkspaceRepair,Ut as assertClosedGoalRepairTransactionCurrent,Zt as cancelWorkspaceRepair,Qt as decideWorkspaceRepair,ft as exactCardProducerArgs,Xt as executeWorkspaceRepair,Jt as inspectWorkspaceRepairCapabilities,yt as listWorkspaceRepairTransactions,ut as planWorkspaceRepair,ht as planWorkspaceRepairProposal,le as readWorkspaceRepairTransaction,Pt as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-MYJQGGIU.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-W6FHVXNL.js';
@@ -1 +1 @@
1
- export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-3A23KJAQ.js';
1
+ export{d as WORKSPACE_VERIFY_REPORT_PATH,c as WORKSPACE_VERIFY_SCHEMA_VERSION,f as buildWorkspaceVerify,e as computeAffectedSubgraphGate,h as evaluateWorkspaceVerifyGate,i as workspaceVerifyExitCode,g as writeWorkspaceVerify}from'./chunk-NOV6723U.js';
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-XGE2FDI4.js';import {d,p,j as j$1}from'./chunk-FY4IIAIF.js';import {a as a$1}from'./chunk-GR6442P7.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import y from'fs';var b="workspace-watch-event.v1";function R(e){return a$2(e,"contracts/workspace-watch-event.v1.json","Workspace watch event"),e}function g(e){return `${e.from}\0${e.to}\0${e.kind}`}function f(e){return (j$1(e)?.edges??[]).map(o=>({from:o.from,to:o.to,kind:o.kind}))}function m(e){let r=[...a(e).entries()].sort((a,n)=>a[0].localeCompare(n[0])).map(([a,n])=>({id:a,hash:n})),c=f(e).map(g).sort((a,n)=>a.localeCompare(n));return d({projects:r,edges:c})}function C(e,o){let r=a(o),c=e?a(e):new Map,a$1=[],n=[];for(let[t,s]of r.entries())c.has(t)?c.get(t)!==s&&a$1.push(t):n.push(t);let d=[];for(let t of c.keys())r.has(t)||d.push(t);let i=new Map(e?f(e).map(t=>[g(t),t]):[]),l=new Map(f(o).map(t=>[g(t),t])),p=[];for(let[t,s]of l.entries())i.has(t)||p.push(s);let h=[];for(let[t,s]of i.entries())l.has(t)||h.push(s);let u=(t,s)=>g(t).localeCompare(g(s));return a$1.sort((t,s)=>t.localeCompare(s)),n.sort((t,s)=>t.localeCompare(s)),d.sort((t,s)=>t.localeCompare(s)),p.sort(u),h.sort(u),{changedProjects:a$1,addedProjects:n,removedProjects:d,edgesAdded:p,edgesRemoved:h}}var k=class{model=null;sequence=0;rebuild;now;constructor(o,r){this.rebuild=r?.rebuild??(()=>p({...o})),this.now=r?.now??(()=>new Date);}get currentModel(){return this.model}async start(){let o=Date.now(),{model:r}=await this.rebuild();return this.model=r,this.buildEvent("ready","initial",null,r,Date.now()-o)}async pulse(){let o=Date.now(),r=this.model,{model:c,mode:a}=await this.rebuild(),n=this.buildEvent(this.hasStructuralChange(r,c)?"changed":"unchanged",a,r,c,Date.now()-o);return this.model=c,n}hasStructuralChange(o,r){return o?m(o)!==m(r):true}buildEvent(o,r,c,a,n){let d=C(c,a),i=m(a),l=c?m(c)!==i:true;return R({schemaVersion:b,kind:o,sequence:this.sequence++,timestamp:this.now().toISOString(),mode:r,modelHash:i,modelHashChanged:l,changedProjects:d.changedProjects,addedProjects:d.addedProjects,removedProjects:d.removedProjects,graph:{nodeCount:a.graph?.nodes.length??0,edgeCount:a.graph?.edges.length??0,edgesAdded:d.edgesAdded,edgesRemoved:d.edgesRemoved},durationMs:n})}},S=new Set([".git",".hg",".svn","node_modules",".venv","venv","dist","build","out","target","coverage","htmlcov",".next",".turbo",".cache"]),j=new Set(["reports","cache","tmp",".cache"]);function O(e){if(!e)return false;let o=e.split(/[\\/]/).filter(Boolean);if(o.some(r=>S.has(r)||a$1(r)))return false;for(let r=0;r<o.length-1;r+=1)if((o[r]===".workspai"||o[r]===".rapidkit")&&j.has(o[r+1]))return false;return true}async function N(e){let o=new k(e.buildOptions,e.engineOptions),r=await o.start();if(e.emit(r),o.currentModel&&await e.onModel?.(o.currentModel,r),e.once)return;let c=e.debounceMs??250,a=e.selfWriteSuppressionMs??Math.max(400,c+150),n=null,d=false,i=false,l=0,p=async()=>{if(d){i=true;return}d=true;try{let t=await o.pulse();e.emit(t),o.currentModel&&await e.onModel?.(o.currentModel,t);}catch(t){e.emit(R({schemaVersion:b,kind:"error",sequence:-1,timestamp:new Date().toISOString(),mode:"full",modelHash:o.currentModel?m(o.currentModel):"",modelHashChanged:false,changedProjects:[],addedProjects:[],removedProjects:[],graph:{nodeCount:0,edgeCount:0,edgesAdded:[],edgesRemoved:[]},durationMs:0,error:t instanceof Error?t.message:String(t)}));}finally{d=false,l=Date.now()+a,i&&(i=false,p());}},h=t=>{O(t)&&(d||Date.now()<l||(n&&clearTimeout(n),n=setTimeout(()=>{n=null,p();},c)));};e.onProgress?.(`Watching ${e.workspacePath} for changes (Ctrl+C to stop).`);let u=y.watch(e.workspacePath,{recursive:true},(t,s)=>{typeof s=="string"?h(s):s&&h(Buffer.from(s).toString("utf8"));});await new Promise(t=>{let s=()=>{n&&clearTimeout(n),u.close(),t();};if(e.signal){if(e.signal.aborted){s();return}e.signal.addEventListener("abort",s,{once:true});}u.on("error",()=>s());});}export{b as WORKSPACE_WATCH_EVENT_SCHEMA_VERSION,k as WorkspaceWatchEngine,m as computeWatchModelHash,C as diffWatchModels,O as isWatchRelevantPath,N as runWorkspaceWatch};
@@ -63,7 +63,7 @@ Validate or preview the current CLI announcement locally:
63
63
  npm --workspace workspai run check:release-announcement
64
64
  npm --workspace workspai run release:announcement -- \
65
65
  --product workspai-cli \
66
- --tag v0.64.0 \
66
+ --tag v0.65.0 \
67
67
  --markdown-output /tmp/workspai-discord-announcement.md
68
68
  ```
69
69
 
@@ -95,7 +95,7 @@ npx workspai workspace snapshot [--workspace <path>] [--json] [--include-paths]
95
95
  npx workspai workspace diff --from <snapshot-or-model|git[:ref]> [--workspace <path>] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>] [--strict]
96
96
  npx workspai workspace impact --from <workspace-diff-report> [--workspace <path>] [--scope project:<name>] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>] [--strict]
97
97
  npx workspai workspace verify [--from-impact <file>] [--workspace <path>] [--scope project:<name>] [--strict] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
98
- npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid|jsonld|graphml|gexf] [key] [value] [--from <graph.json>] [--output <file>] [--limit <1..100>] [--workspace <path>] [--scope project:<name>] [--refresh-graph] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
98
+ npx workspai workspace graph [emit|explain|search|benchmark|entities|evidence|path|overlay|dot|mermaid|jsonld|graphml|gexf] [key] [value] [--from <graph.json>] [--output <file>] [--limit <1..100>] [--kind <entity-kind>] [--workspace <path>] [--scope project:<name>] [--refresh-graph] [--json] [--include-paths] [--include-evidence] [--scan-depth <count>]
99
99
  npx workspai workspace eval [init <task> [strategy]|record|status|report|compare --from <report>] [--workspace <path>] [--output <file>] [--json]
100
100
  npx workspai workspace watch [--workspace <path>] [--json] [--graph-stream] [--once] [--scan-depth <count>]
101
101
  npx workspai workspace explain <target> [--workspace <path>] [--json] [--write]
@@ -239,6 +239,8 @@ assert equivalent answer quality or model-specific billing savings.
239
239
 
240
240
  Add `--scope project:<name>` to retrieve project-owned facts plus
241
241
  workspace-level shared entities proven to be connected to that project. The
242
+ `search` mode also accepts `--kind <entity-kind>` so agents can retrieve a
243
+ precise semantic surface such as `runtime-unit`, `endpoint`, or `owner`. The
242
244
  agent projection reports explicit omission budgets for relations, related
243
245
  entities, proofs, aliases, attributes, and proof references. Read-oriented
244
246
  `search`, `entities`, `evidence`, `path`, and `benchmark` modes reuse the