workspai 0.55.1 → 0.56.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 (163) hide show
  1. package/contracts/artifact-remediation-plan.v1.json +110 -2
  2. package/contracts/cli-runtime-command-inventory.v1.snapshot.json +29 -1
  3. package/contracts/doctor-project-evidence.v1.json +68 -2
  4. package/contracts/doctor-remediation-plan.v1.json +29 -2
  5. package/contracts/doctor-workspace-evidence.v1.json +68 -2
  6. package/contracts/extension-cli-compatibility.v1.json +6 -1
  7. package/contracts/published-contract-catalog.v1.json +25 -0
  8. package/contracts/runtime-command-surface.v1.json +63 -0
  9. package/contracts/workspace-intelligence/doctor-capabilities.v1.json +133 -0
  10. package/contracts/workspace-intelligence/doctor-diagnosis.v1.json +273 -0
  11. package/contracts/workspace-intelligence/doctor-graph-diagnosis.v1.json +3 -0
  12. package/contracts/workspace-intelligence/doctor-receipt.v1.json +136 -0
  13. package/contracts/workspace-intelligence/doctor-summary.v1.json +99 -0
  14. package/contracts/workspace-intelligence/doctor-validation.v1.json +109 -0
  15. package/contracts/workspace-intelligence/project-context-agent.v1.json +110 -0
  16. package/contracts/workspace-intelligence/studio-blocker-handoff.v1.json +25 -0
  17. package/contracts/workspace-intelligence/workspace-knowledge-graph.v1.json +36 -0
  18. package/contracts/workspace-intelligence/workspace-knowledge-search.v1.json +54 -0
  19. package/dist/analyze-HJ774J3E.js +1 -0
  20. package/dist/{artifact-remediation-plan-O3YIULQN.js → artifact-remediation-plan-BPLON5VX.js} +1 -1
  21. package/dist/autopilot-release-CH57CGET.js +1 -0
  22. package/dist/capabilities-command-WEOGFCWF.js +1 -0
  23. package/dist/chunk-2647BYBC.js +1 -0
  24. package/dist/chunk-2L4PSZQB.js +1 -0
  25. package/dist/chunk-3U4VLIGW.js +1 -0
  26. package/dist/chunk-5BGPGNRQ.js +2 -0
  27. package/dist/chunk-5EPPPMAS.js +1 -0
  28. package/dist/{chunk-M5ICGR55.js → chunk-5RL254O2.js} +1 -1
  29. package/dist/chunk-5ZA4JYOP.js +1 -0
  30. package/dist/{chunk-AMB42V2F.js → chunk-64JUYYRC.js} +1 -1
  31. package/dist/chunk-664GXRLD.js +1 -0
  32. package/dist/chunk-6HCAGHCY.js +8 -0
  33. package/dist/chunk-7PNARN6S.js +4 -0
  34. package/dist/chunk-7Y3KVZJF.js +8 -0
  35. package/dist/{chunk-WIO6L24E.js → chunk-ADL3CK44.js} +1 -1
  36. package/dist/chunk-AO2ZI42U.js +4 -0
  37. package/dist/chunk-BDN32Y2N.js +81 -0
  38. package/dist/chunk-D4RST2HE.js +1 -0
  39. package/dist/{chunk-6HJJHEL6.js → chunk-DIZSHNZ5.js} +1 -1
  40. package/dist/chunk-DOIZANFA.js +2 -0
  41. package/dist/{chunk-HY3RMPW5.js → chunk-E53BGUOW.js} +1 -1
  42. package/dist/{chunk-FZCYTRBQ.js → chunk-ESWFBSYM.js} +1 -1
  43. package/dist/chunk-GBMCHFOV.js +1 -0
  44. package/dist/{chunk-HUPLAFZQ.js → chunk-HASVV34S.js} +1 -1
  45. package/dist/chunk-IZLEMTES.js +1 -0
  46. package/dist/chunk-KR7CIEQR.js +1 -0
  47. package/dist/chunk-KS4FB5W7.js +6 -0
  48. package/dist/chunk-LYVDRRDO.js +2 -0
  49. package/dist/{chunk-IBPPMOHM.js → chunk-NHTLE3WN.js} +1 -1
  50. package/dist/chunk-NS53IPAC.js +1 -0
  51. package/dist/{chunk-YTLUT6IA.js → chunk-OX53L237.js} +2 -2
  52. package/dist/chunk-PKIRVQLG.js +1 -0
  53. package/dist/chunk-QAF26ZQX.js +36 -0
  54. package/dist/{chunk-NWQ5VWUW.js → chunk-QFCKHUEP.js} +1 -1
  55. package/dist/chunk-QRWWYL52.js +88 -0
  56. package/dist/chunk-QTCZPS5I.js +1 -0
  57. package/dist/{chunk-WSAFBPS5.js → chunk-SV2SP22H.js} +4 -4
  58. package/dist/chunk-T5YRFRJV.js +1 -0
  59. package/dist/chunk-UQEQ6CXU.js +1 -0
  60. package/dist/chunk-V5EYVQ63.js +1 -0
  61. package/dist/chunk-VGJVIHHR.js +1 -0
  62. package/dist/{chunk-MRFN5ZQP.js → chunk-W5ZFXKSL.js} +1 -1
  63. package/dist/chunk-WLCBXCZV.js +5 -0
  64. package/dist/chunk-WOTTSPSF.js +2 -0
  65. package/dist/chunk-X7FYEKLI.js +1 -0
  66. package/dist/chunk-XH7PDHBF.js +1 -0
  67. package/dist/{chunk-KFKZOPZC.js → chunk-XMTLKDPP.js} +1 -1
  68. package/dist/chunk-YJTEMJFV.js +3 -0
  69. package/dist/chunk-YM77FQB3.js +8 -0
  70. package/dist/chunk-ZCPT6KC3.js +6 -0
  71. package/dist/chunk-ZPA6ECBJ.js +7 -0
  72. package/dist/{create-3NSOY7CA.js → create-DLUWG46F.js} +1 -1
  73. package/dist/doctor-IZ4YOCYE.js +1 -0
  74. package/dist/index.d.ts +15 -0
  75. package/dist/index.js +168 -168
  76. package/dist/pipeline-IBQYDLFF.js +5 -0
  77. package/dist/{project-intelligence-lens-ZOAWXYC5.js → project-intelligence-lens-SIU7IXKG.js} +1 -1
  78. package/dist/project-test-coverage-FRMVYTFB.js +1 -0
  79. package/dist/verified-goal-M4GPOXNL.js +1 -0
  80. package/dist/{workspace-C4UETGY7.js → workspace-3AAOUELG.js} +1 -1
  81. package/dist/{workspace-agent-sync-446AXPHJ.js → workspace-agent-sync-QGYLY7HH.js} +1 -1
  82. package/dist/{workspace-archive-VHUPOBAV.js → workspace-archive-BA3ONVXX.js} +1 -1
  83. package/dist/{workspace-context-XSECHC7O.js → workspace-context-JCLPRYNC.js} +1 -1
  84. package/dist/workspace-contract-IUUPBQXU.js +1 -0
  85. package/dist/workspace-explain-CZGBVDE6.js +1 -0
  86. package/dist/workspace-explain-contract-KVQO57RC.js +1 -0
  87. package/dist/{workspace-feedback-WXE7NVMV.js → workspace-feedback-PCZKXG5R.js} +1 -1
  88. package/dist/{workspace-foundation-3EVAQ5X6.js → workspace-foundation-7IGMO4CW.js} +1 -1
  89. package/dist/{workspace-graph-stream-AJPS45FD.js → workspace-graph-stream-5YMLJXAJ.js} +1 -1
  90. package/dist/workspace-graph-token-efficiency-HK4KNWWP.js +1 -0
  91. package/dist/{workspace-history-YY7YRDOH.js → workspace-history-CHJOABME.js} +1 -1
  92. package/dist/{workspace-intelligence-FWRB47EJ.js → workspace-intelligence-XHSUFTAT.js} +1 -1
  93. package/dist/workspace-intelligence-evaluation-YMY3C5AW.js +1 -0
  94. package/dist/{workspace-intelligence-runner-SMEAB4CO.js → workspace-intelligence-runner-EN5V4KSC.js} +1 -1
  95. package/dist/workspace-intelligence-runtime-registry-NCVHKCMP.js +1 -0
  96. package/dist/workspace-knowledge-graph-VWQTIEYK.js +1 -0
  97. package/dist/{workspace-knowledge-graph-query-EKHIE3E2.js → workspace-knowledge-graph-query-TXA3KVUV.js} +1 -1
  98. package/dist/workspace-knowledge-graph-snapshot-WB62AVDK.js +1 -0
  99. package/dist/workspace-mcp-serve-NCAGGWQS.js +3 -0
  100. package/dist/{workspace-model-MNJOGBPP.js → workspace-model-NXFIKX26.js} +1 -1
  101. package/dist/{workspace-onboarding-5KO7Z7AD.js → workspace-onboarding-OP22NHQ4.js} +1 -1
  102. package/dist/{workspace-readme-4S6PJ74A.js → workspace-readme-IVJXSIBS.js} +1 -1
  103. package/dist/{workspace-registry-summary-GPJEL7K7.js → workspace-registry-summary-A5VDPRHU.js} +1 -1
  104. package/dist/workspace-repair-engine-N4KXNSVL.js +3 -0
  105. package/dist/workspace-run-PXKC3ELS.js +1 -0
  106. package/dist/{workspace-verify-C6HWHRLJ.js → workspace-verify-TUVLFPPN.js} +1 -1
  107. package/dist/{workspace-watch-DLPHLF5R.js → workspace-watch-2ZNOYSUQ.js} +1 -1
  108. package/docs/commands-reference.md +35 -6
  109. package/docs/contracts/ARTIFACT_CATALOG.md +6 -1
  110. package/docs/contracts/README.md +5 -0
  111. package/docs/doctor-command.md +158 -7
  112. package/docs/graph-benchmark-methodology.md +13 -0
  113. package/docs/workspace-intelligence-runner.md +4 -0
  114. package/docs/workspace-knowledge-graph.md +53 -4
  115. package/docs/workspace-run.md +14 -3
  116. package/package.json +10 -3
  117. package/dist/analyze-AAZEJ4FC.js +0 -1
  118. package/dist/autopilot-release-3H5FTF6H.js +0 -1
  119. package/dist/chunk-2PY65U6X.js +0 -5
  120. package/dist/chunk-3DONU3DU.js +0 -1
  121. package/dist/chunk-44VJHNZB.js +0 -1
  122. package/dist/chunk-5XDPQ3CB.js +0 -1
  123. package/dist/chunk-7AR5PDLD.js +0 -1
  124. package/dist/chunk-7KKP7RNB.js +0 -3
  125. package/dist/chunk-7S4QNH5A.js +0 -5
  126. package/dist/chunk-7T4TSV5C.js +0 -1
  127. package/dist/chunk-BYVTHIC3.js +0 -2
  128. package/dist/chunk-CEIJIFY7.js +0 -88
  129. package/dist/chunk-D37NEYV6.js +0 -1
  130. package/dist/chunk-DPMO4U3Z.js +0 -8
  131. package/dist/chunk-DS4UYMLX.js +0 -1
  132. package/dist/chunk-FQLB4BIC.js +0 -7
  133. package/dist/chunk-GDU7VP6G.js +0 -1
  134. package/dist/chunk-H7P7SSUW.js +0 -75
  135. package/dist/chunk-KVUYAYTY.js +0 -8
  136. package/dist/chunk-MQ73VS4E.js +0 -2
  137. package/dist/chunk-NYHVCFBT.js +0 -1
  138. package/dist/chunk-OUBBBC7T.js +0 -36
  139. package/dist/chunk-P7K5RHJC.js +0 -2
  140. package/dist/chunk-PS5F4DCT.js +0 -1
  141. package/dist/chunk-QZ7PNMVP.js +0 -1
  142. package/dist/chunk-RA24WQLF.js +0 -1
  143. package/dist/chunk-RMXXK64P.js +0 -4
  144. package/dist/chunk-S7Z4DP3P.js +0 -2
  145. package/dist/chunk-SJLUE6AY.js +0 -1
  146. package/dist/chunk-TEHQ7XKK.js +0 -3
  147. package/dist/chunk-UFOCUHG3.js +0 -1
  148. package/dist/chunk-WD2XDMGB.js +0 -1
  149. package/dist/chunk-XVRJVKOX.js +0 -1
  150. package/dist/doctor-UEFFNAUD.js +0 -1
  151. package/dist/pipeline-B5S6P36F.js +0 -5
  152. package/dist/project-test-coverage-44ZPCOPV.js +0 -1
  153. package/dist/verified-goal-KOU3WJYN.js +0 -1
  154. package/dist/workspace-contract-AYFTZIKM.js +0 -1
  155. package/dist/workspace-explain-ZEWVKDBF.js +0 -1
  156. package/dist/workspace-explain-contract-6CCC26QT.js +0 -1
  157. package/dist/workspace-graph-token-efficiency-5FNH4JZ5.js +0 -1
  158. package/dist/workspace-intelligence-evaluation-UP2K3L35.js +0 -1
  159. package/dist/workspace-intelligence-runtime-registry-MRSF7RTT.js +0 -1
  160. package/dist/workspace-knowledge-graph-BMMM2FUE.js +0 -1
  161. package/dist/workspace-mcp-serve-X6C3AWTA.js +0 -3
  162. package/dist/workspace-repair-engine-GWTXVVKB.js +0 -3
  163. package/dist/workspace-run-FJTBX4JQ.js +0 -1
@@ -0,0 +1,5 @@
1
+ import {a as a$2}from'./chunk-YM77FQB3.js';import {c}from'./chunk-6HCAGHCY.js';import {r}from'./chunk-QRWWYL52.js';import {c as c$1}from'./chunk-FPJNWPKU.js';import {a as a$3}from'./chunk-7PNARN6S.js';import {f,e as e$1}from'./chunk-T3GJ7YVG.js';import {a}from'./chunk-W5ZFXKSL.js';import {g}from'./chunk-SV2SP22H.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-ADL3CK44.js';import {e,i,h}from'./chunk-5EPPPMAS.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-IUUPBQXU.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-QGYLY7HH.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
+ \u{1F517} Workspai Governance Pipeline
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
+ Blocking reasons:`));for(let t of a.blockingReasons.slice(0,8))console.log(c$2.gray(` \u2022 ${t}`));}console.log(c$2.gray(`
5
+ Evidence: ${a.artifacts.reportPath}`)),a.agentGrounding?.writtenFiles.length&&console.log(c$2.gray(`Agent grounding: ${a.agentGrounding.writtenFiles.length} file(s) synced (INDEX + AGENTS.md + Copilot/Cursor/Claude hooks)`));}let i=K(a.summary.exitCode,s.strict===true);i!==0&&process.exit(i);}export{K as pipelineProcessExitCode,U as runPipeline,ue as runPipelineCommand};
@@ -1 +1 @@
1
- export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-H7P7SSUW.js';
1
+ export{a as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,b as PROJECT_GROUNDING_MODE_VALUES,d as WORKSPAI_PROJECT_GROUNDING_END,c as WORKSPAI_PROJECT_GROUNDING_START,e as buildProjectContextAgent,h as resolveWorkspaceProjectLensTargets,f as syncProjectIntelligenceLens,g as syncWorkspaceProjectLenses}from'./chunk-BDN32Y2N.js';
@@ -0,0 +1 @@
1
+ export{b as PROJECT_TEST_COVERAGE_ARTIFACT,a as PROJECT_TEST_COVERAGE_SCHEMA,c as collectProjectTestCoverage}from'./chunk-3U4VLIGW.js';
@@ -0,0 +1 @@
1
+ import {c}from'./chunk-664GXRLD.js';import {a as a$2}from'./chunk-WLCBXCZV.js';import {c as c$1}from'./chunk-3U4VLIGW.js';import {a as a$1}from'./chunk-7PNARN6S.js';import {p}from'./chunk-5ZA4JYOP.js';import {a as a$3}from'./chunk-GR6442P7.js';import {e as e$1,d}from'./chunk-ADL3CK44.js';import {a}from'./chunk-AFIFZTOY.js';import {e,f}from'./chunk-5EPPPMAS.js';import {createHash}from'crypto';import l from'path';import y from'fs-extra';var W="workspai.verified-goal.v1",x=f.verifiedGoalStatus,C=e.verifiedGoalStatus,J="contracts/workspace-intelligence/verified-goal.v1.json",G="contracts/workspace-intelligence/verified-goal-status.v1.json";function A(e){return Array.isArray(e)?`[${e.map(A).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${A(a)}`).join(",")}}`:JSON.stringify(e)}function H(e){return createHash("sha256").update(A(e)).digest("hex")}var te=["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","Pipfile","Pipfile.lock","poetry.lock","uv.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","packages.lock.json","Directory.Packages.props","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deps.edn","project.clj","build.sbt"],ae=new Set(te.map(e=>e.toLowerCase())),se=new Set([".git",".hg",".svn",".workspai",".venv","venv",".tox",".mypy_cache",".pytest_cache","__pycache__","node_modules","vendor","pods","dist","build","out","target","bin","obj","coverage",".coverage",".next",".nuxt",".svelte-kit"]),F=1e5;function ne(e){return ae.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function re(e){let t=[e],a=[],s=0;for(;t.length>0;){let o=t.shift();if(o===void 0)break;let i=await y.readdir(o,{withFileTypes:true});if(i.sort((n,r)=>n.name.localeCompare(r.name)),s+=i.length,s>F)throw new Error(`Dependency safety baseline exceeded ${F} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of i){let r=l.join(o,n.name);if(n.isDirectory()){!se.has(n.name.toLowerCase())&&!a$3(n.name)&&t.push(r);continue}n.isFile()&&ne(n.name)&&a.push(r);}}return a}function ie(e){return /^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/i.test(e)?"node":/^(?:pyproject\.toml|requirements\.txt|Pipfile(?:\.lock)?|poetry\.lock|uv\.lock)$/i.test(e)?"python":/^go\.(?:mod|sum)$/i.test(e)?"go":/^Cargo\.(?:toml|lock)$/i.test(e)?"rust":/^(?:pom\.xml|build\.gradle(?:\.kts)?|gradle\.lockfile)$/i.test(e)?"jvm":/^(?:Directory\.Packages\.props|packages\.lock\.json)$/i.test(e)?"dotnet":/^composer\.(?:json|lock)$/i.test(e)?"php":/^Gemfile(?:\.lock)?$/i.test(e)?"ruby":/^mix\.(?:exs|lock)$/i.test(e)?"elixir":/^(?:deps\.edn|project\.clj)$/i.test(e)?"clojure":/^build\.sbt$/i.test(e)?"scala":/\.(?:csproj|fsproj|vbproj)$/i.test(e)?"dotnet":"unknown"}function K(e){try{let t=JSON.parse(e),a={};for(let s of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let o=t[s];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let[i,n]of Object.entries(o))typeof n=="string"&&(a[`${s}:${i}`]=n);}return a}catch{return}}async function U(e,t){let s=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(i=>t.kind==="workspace"||i.name===t.projectName||l.resolve(e,i.path)===l.resolve(t.projectPath??"")),o=new Map;for(let i of s){let n=l.resolve(e,i.path),r=await re(n);for(let c of r){let p=l.basename(c),f=await y.readFile(c,"utf8"),d=l.relative(e,c).split(l.sep).join("/");o.set(d,{path:d,ecosystem:ie(p),sha256:createHash("sha256").update(f).digest("hex"),...p==="package.json"?{dependencies:K(f)??{}}:{}});}}return {manifests:[...o.values()].sort((i,n)=>i.path.localeCompare(n.path))}}function O(e){let a=e.replace(/^(?:workspace:|npm:[^@]+@)/,"").match(/(?:^|[^\d])(\d+)(?:\.\d+)?(?:\.\d+)?/);return a?Number(a[1]):null}function S(e){return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|poetry\.lock|uv\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|gradle\.lockfile|packages\.lock\.json|composer\.lock|Gemfile\.lock|mix\.lock)$/i.test(e)}async function oe(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],s=await U(e.workspace.path,e.scope),o=new Map(s.manifests.map(r=>[r.path,r])),i=new Map(t.manifests.map(r=>[r.path,r])),n=new Set;for(let r of t.manifests){let c=o.get(r.path);(!c||c.sha256!==r.sha256)&&n.add(r.path);}for(let r of s.manifests)i.has(r.path)||n.add(r.path);for(let r of s.manifests)!i.has(r.path)&&!S(r.path)&&a.push(`${r.path} was added after the safety baseline`);for(let r of t.manifests){let c=o.get(r.path);if(!c){a.push(`${r.path} was removed`);continue}if(c.sha256===r.sha256)continue;if(r.dependencies){let d=await y.readFile(l.join(e.workspace.path,r.path),"utf8"),m=K(d);if(!m){a.push(`${r.path} is not valid dependency JSON`);continue}for(let[u,g]of Object.entries(r.dependencies)){let h=m[u];if(!h){a.push(`${u.replace(/^[^:]+:/,"")} was removed`);continue}if(h===g)continue;let $=O(g),R=O(h);($===null||R===null||$!==R||/(?:latest|\*)/i.test(h))&&a.push(`${u.replace(/^[^:]+:/,"")} changed outside its proven major range (${g} \u2192 ${h})`);}continue}if(S(r.path))continue;let p=l.posix.dirname(r.path);[...o.values()].some(d=>{let m=l.posix.dirname(d.path);return d.ecosystem===r.ecosystem&&(m===p||p.startsWith(`${m}/`))&&S(d.path)&&n.has(d.path)})||a.push(`${r.path} changed without a matching reconciled ${r.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=l.join(e,".workspai","goals",t);return {directory:a,goal:l.join(a,"goal.json"),status:l.join(a,"status.json"),latestReport:l.join(e,C)}}function ce(e){return {workspacePath:l.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,constraints:e.constraints}}async function V(e,t){await y.ensureDir(l.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await y.writeJson(a,t,{spaces:2}),await y.rename(a,e);}async function le(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let s=a.startsWith("project:")?a.slice(8).trim():a;if(!s)throw new Error("Project goal scope must name a project.");let i=(await p({workspacePath:e,includeAbsolutePaths:true})).projects.filter(c=>{let p=l.resolve(e,c.path);return c.name===s||c.path===s||p===l.resolve(s)});if(i.length!==1)throw new Error(i.length===0?`Project goal scope was not found: ${s}`:`Project goal scope is ambiguous: ${s}`);let n=i[0],r=l.resolve(e,n.path);return {project:n,scope:{kind:"project",projectName:n.name,projectPath:r}}}function z(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Y(e){if(!e)return null;try{let t=await y.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function de(e){return Array.isArray(e.projects)?e.projects.filter(t=>!!t&&typeof t=="object"&&!Array.isArray(t)):e.project&&typeof e.project=="object"&&!Array.isArray(e.project)?[e.project]:[]}function ue(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function X(e$1,t){let a=await d(e$1,e.doctor),s=await Y(a);if(!s)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let o=de(s).filter(c=>{if(t.kind==="workspace")return true;let p=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?l.resolve(c.path):typeof c.projectPath=="string"?l.resolve(c.projectPath):"";return p===t.projectName||t.projectPath!==void 0&&f===l.resolve(t.projectPath)}),i=o.map(ue).filter(c=>c!==null),n=i.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),r=o.length>0&&n.length===o.length?n.reduce((c,p)=>c+p,0):null;return {measuredAt:(()=>{let c=i.map(p=>p.generatedAt).filter(p=>typeof p=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:r,target:0,unit:"blocking-vulnerabilities",status:z(r,0,"maximum"),evidencePaths:a?[a]:[],message:r===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${r} blocking dependency vulnerability finding(s) remain.`}}async function Q(e){let t=await a$1({startPath:e,writeReport:false}),a=t.gates.filter(o=>o.status==="pass").length,s=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:s,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(o=>o.evidencePath).filter(o=>typeof o=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${s-a} release readiness gate(s) still require work.`}}async function B(e){let t=await c$1({projectPath:e.projectPath,target:e.target,run:e.run}),s=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:s,target:e.target,unit:"percent",status:z(s,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":s===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${s}% (target ${e.target}%).`}}}async function Z(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return B({projectPath:e.scope.projectPath,target:e.target,run:e.run})}let t=await p({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=[];for(let d of t.projects)a.push({projectName:d.name,result:await B({projectPath:l.resolve(e.workspacePath,d.path),target:e.target,run:e.run})});let s=a.filter(d=>d.result.executionStatus==="failed"),o=a.filter(d=>d.result.measurement.status==="unavailable"),i=a.filter(d=>d.result.measurement.status==="unsatisfied"),n=a.map(d=>d.result.measurement.value).filter(d=>d!==null),r=n.length===a.length&&n.length>0?Math.min(...n):null,c=s.length>0?"failed":o.length>0?"unavailable":i.length>0?"below-target":"passed",p$1=a.map(d=>d.result.measurement.measuredAt).sort(),f=[...s.map(d=>`${d.projectName}: coverage command failed`),...o.map(d=>`${d.projectName}: coverage unavailable`),...i.map(d=>`${d.projectName}: ${d.result.measurement.value??"unknown"}%`)];return {executionStatus:c,measurement:{measuredAt:p$1[p$1.length-1]??new Date().toISOString(),value:r,target:e.target,unit:"percent",status:c==="passed"?"satisfied":c==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(a.flatMap(d=>d.result.measurement.evidencePaths))],message:c==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${f.join("; ")}.`}}}function pe(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${t} test coverage to ${e.target??80}% without breaking its build.`}function ge(e,t){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t}}async function fe(e){return e.kind==="release-readiness"?Q(e.workspacePath):e.kind==="dependency-security"?X(e.workspacePath,e.scope):(await Z({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false})).measurement}async function Ge(e){let t=l.resolve(e.workspacePath),a$1=Math.max(0,Math.min(100,Math.round(e.target??80))),{scope:s}=await le(t,e.scope),o={workspacePath:l.resolve(t),kind:e.kind,scope:s,target:e.kind==="test-coverage"?a$1:null,constraints:{allowBreakingChanges:e.allowBreakingChanges===true,allowForce:e.allowForce===true,requireBuild:e.requireBuild!==false,requireTests:e.requireTests!==false}},i=H(o),n=`goal-${e.kind}-${i.slice(0,16)}`,r=E(t,n);if(await y.pathExists(r.goal)){let{goal:m,status:u}=await ee(t,n);if(m.fingerprint===i)return {goal:m,status:u,resumed:u.state!=="verified"}}let c=new Date().toISOString(),p=await fe({workspacePath:t,kind:e.kind,scope:s,target:a$1}),f={schemaVersion:W,id:n,fingerprint:i,createdAt:c,updatedAt:c,workspace:{name:l.basename(t),path:t},scope:s,kind:e.kind,summary:pe({kind:e.kind,scope:s,target:a$1}),constraints:o.constraints,criteria:ge(e.kind,a$1),baseline:p,...e.kind==="dependency-security"?{dependencySafetyBaseline:await U(t,s)}:{},artifactPaths:{goal:r.goal,status:r.status,latestReport:r.latestReport}},d={schemaVersion:x,goalId:n,goalFingerprint:i,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:p,checks:[],blockingReasons:[],evidencePaths:p.evidencePaths,nextActions:e.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:r.status};return a(f,J,"Verified goal"),a(d,G,"Verified goal status"),await V(r.goal,f),await V(r.status,d),await e$1(t,C,d),{goal:f,status:d,resumed:false}}async function ee(e,t){let a$1=E(l.resolve(e),t),s=await y.readJson(a$1.goal),o=await y.readJson(a$1.status);a(s,J,"Verified goal"),a(o,G,"Verified goal status");let i=l.resolve(e),n=l.resolve(s.artifactPaths.goal)===l.resolve(a$1.goal)&&l.resolve(s.artifactPaths.status)===l.resolve(a$1.status)&&l.resolve(s.artifactPaths.latestReport)===l.resolve(a$1.latestReport);if(s.schemaVersion!==W||o.schemaVersion!==x||s.id!==o.goalId||s.fingerprint!==o.goalFingerprint||s.fingerprint!==H(ce(s))||l.resolve(s.workspace.path)!==i||l.resolve(o.workspacePath)!==i||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:s,status:o}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function q(e){let t=[],a=e.goal.scope.kind==="project"&&e.goal.scope.projectName?`project:${e.goal.scope.projectName}`:void 0;for(let s of ["test","build"]){if(s==="test"&&e.includeTests===false)continue;if(!(s==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:s,label:`${s} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:s,label:`${s} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let i=await a$2({workspacePath:e.goal.workspace.path,stage:s,scope:a,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false});if(t.push(k({id:s,label:`${s} validation`,status:i.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${i.summary.exitCode}`,evidencePath:l.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),i.summary.exitCode!==0)break}return t}async function Ee(e$2){let t=l.resolve(e$2.workspacePath),{goal:a$1,status:s}=await ee(t,e$2.goalId),o=e$2.run!==false,i=[],n;if(o&&e$2.runIntelligence!==false){let u=await c({workspacePath:t,strict:true,agent:"generic"}),g=u.exitCode===0||u.exitCode===2,h=a$1.kind==="release-readiness";i.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:u.exitCode===0||u.exitCode===2&&!h?"passed":u.exitCode===2?"blocked":"failed",expected:"passed",actual:u.exitCode===2&&g&&!h?`${u.status}; canonical evidence refreshed for goal-scoped verification`:u.status,evidencePath:l.join(t,e.intelligenceRun)}));}if(a$1.kind==="release-readiness"){n=await Q(t),i.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:l.join(t,e.readiness)}));let u=await d(t,e.verify),g=await Y(u),h=g?.summary&&typeof g.summary=="object"&&!Array.isArray(g.summary)?String(g.summary.verdict??"missing"):"missing";i.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:l.join(t,e.verify)}));}else if(a$1.kind==="dependency-security")n=await X(t,a$1.scope),i.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(a$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 oe(a$1)),n.status==="satisfied"&&i.push(...await q({goal:a$1,run:o}));else {let u=a$1.criteria.kind==="test-coverage"?a$1.criteria.minimumPercent:a$1.baseline.target;if(u===null)throw new Error("Coverage goal does not have a valid target.");let g=await Z({workspacePath:t,scope:a$1.scope,target:u,run:o});n=g.measurement,i.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${u}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),i.push(k({id:"test",label:"Coverage test execution",status:g.executionStatus==="failed"?"failed":g.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:g.executionStatus==="failed"?"coverage test command failed":g.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&i.push(...await q({goal:a$1,run:o,includeTests:false}));}let r=i.filter(u=>u.status==="blocked"||u.status==="failed"||u.status==="missing").map(u=>u.message),c$1=[...new Set([...n.evidencePaths,...i.map(u=>u.evidencePath).filter(u=>typeof u=="string")])],p=n.status==="satisfied"&&i.every(u=>u.status==="passed"||u.status==="skipped"),f=E(t,a$1.id),d$1=p?[]: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:x,goalId:a$1.id,goalFingerprint:a$1.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:p?"verified":i.some(u=>u.status==="failed")?"failed":"blocked",attempt:s.attempt+1,progress:n,checks:i,blockingReasons:r,evidencePaths:c$1,nextActions:d$1,artifactPath:f.status};return a(m,G,"Verified goal status"),await V(f.status,m),await e$1(t,C,m),m}export{C as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,W as VERIFIED_GOAL_SCHEMA_VERSION,x as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Ge as planVerifiedGoal,ee as readVerifiedGoal,Ee as verifyVerifiedGoal};
@@ -1 +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-WSAFBPS5.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-SV2SP22H.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-OUBBBC7T.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,A as LEGACY_COPILOT_GROUNDING_SKILL_PATH,m as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,C as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,i as LEGACY_CURSOR_GROUNDING_RULE_PATH,E as LEGACY_MCP_DESIGN_REPORT_PATH,G as LEGACY_VSCODE_AGENT_HOOKS_PATH,z as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,l as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,B as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,D as WORKSPAI_MCP_DESIGN_REPORT_PATH,F as WORKSPAI_VSCODE_AGENT_HOOKS_PATH}from'./chunk-AMB42V2F.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-QAF26ZQX.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,A as LEGACY_COPILOT_GROUNDING_SKILL_PATH,m as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,C as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,i as LEGACY_CURSOR_GROUNDING_RULE_PATH,E as LEGACY_MCP_DESIGN_REPORT_PATH,G as LEGACY_VSCODE_AGENT_HOOKS_PATH,z as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,l as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,B as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,D as WORKSPAI_MCP_DESIGN_REPORT_PATH,F as WORKSPAI_VSCODE_AGENT_HOOKS_PATH}from'./chunk-64JUYYRC.js';
@@ -1 +1 @@
1
- export{f as WORKSPACE_ARCHIVE_KIND,e as WORKSPACE_ARCHIVE_MANIFEST_PATH,h as assertSafeRemoteArchiveUrl,o as doctorWorkspaceArchive,l as exportWorkspaceArchive,p as hydrateWorkspaceArchive,m as inspectWorkspaceArchive,g as isPrivateAddress,j as isSafeArchiveEntryName,i as sanitizeWorkspaceArchiveName,k as shouldExcludeWorkspaceArchivePath,n as verifyWorkspaceArchive}from'./chunk-HY3RMPW5.js';
1
+ export{f as WORKSPACE_ARCHIVE_KIND,e as WORKSPACE_ARCHIVE_MANIFEST_PATH,h as assertSafeRemoteArchiveUrl,o as doctorWorkspaceArchive,l as exportWorkspaceArchive,p as hydrateWorkspaceArchive,m as inspectWorkspaceArchive,g as isPrivateAddress,j as isSafeArchiveEntryName,i as sanitizeWorkspaceArchiveName,k as shouldExcludeWorkspaceArchivePath,n as verifyWorkspaceArchive}from'./chunk-E53BGUOW.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-P7K5RHJC.js';
1
+ export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-WOTTSPSF.js';
@@ -0,0 +1 @@
1
+ export{d as WORKSPACE_CONTRACT_PATH,f as WORKSPACE_CONTRACT_SCHEMA_VERSION,e as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,g as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,h as WorkspaceContractVerificationError,j as buildWorkspaceContract,n as buildWorkspaceContractGraph,i as discoverProjectJsonFiles,m as readWorkspaceContract,l as syncWorkspaceContract,o as verifyWorkspaceContract,k as writeWorkspaceContract,p as writeWorkspaceContractVerifyEvidence}from'./chunk-DOIZANFA.js';
@@ -0,0 +1 @@
1
+ export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-OX53L237.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-64JUYYRC.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-5BGPGNRQ.js';
@@ -0,0 +1 @@
1
+ export{a as WORKSPACE_EXPLAIN_SCHEMA_VERSION,b as WORKSPACE_EXPLAIN_TARGETS,e as isWorkspaceExplainReport,c as parseWorkspaceExplainTarget,d as resolveWorkspaceTraceTarget}from'./chunk-NHTLE3WN.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-64JUYYRC.js';
@@ -1 +1 @@
1
- import {b}from'./chunk-ICGWHIMK.js';import {b as b$1,f,j}from'./chunk-GDU7VP6G.js';import o from'path';async function m(r){let t=o.resolve(r.workspacePath),n=b(r.payload);if(!n)return {ok:false,error:"Invalid agent-action-outcome payload",historyPath:o.join(t,b$1)};let c=f(n),p=o.join(t,b$1);return await j(t,c,{retention:r.retention}),{ok:true,entry:c,historyPath:p}}function l(r){let t=r.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function h(){let r=[];for await(let t of process.stdin)r.push(typeof t=="string"?Buffer.from(t):t);return Buffer.concat(r).toString("utf8")}export{l as parseFeedbackStdinPayload,h as readStdinAll,m as recordWorkspaceFeedback};
1
+ import {b}from'./chunk-ICGWHIMK.js';import {b as b$1,f,j}from'./chunk-GBMCHFOV.js';import o from'path';async function m(r){let t=o.resolve(r.workspacePath),n=b(r.payload);if(!n)return {ok:false,error:"Invalid agent-action-outcome payload",historyPath:o.join(t,b$1)};let c=f(n),p=o.join(t,b$1);return await j(t,c,{retention:r.retention}),{ok:true,entry:c,historyPath:p}}function l(r){let t=r.trim();if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function h(){let r=[];for await(let t of process.stdin)r.push(typeof t=="string"?Buffer.from(t):t);return Buffer.concat(r).toString("utf8")}export{l as parseFeedbackStdinPayload,h as readStdinAll,m as recordWorkspaceFeedback};
@@ -1 +1 @@
1
- import {b}from'./chunk-NWQ5VWUW.js';import {a}from'./chunk-Y5YAP4F3.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await b(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-GPJEL7K7.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
1
+ import {b}from'./chunk-QFCKHUEP.js';import {a}from'./chunk-Y5YAP4F3.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await b(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-A5VDPRHU.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
@@ -1 +1 @@
1
- import {c}from'./chunk-7KKP7RNB.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c$1({...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$1(f(t))!==c$1(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$1(i)!==c$1(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){c(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=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$2=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c$1(t.quality)!==c$1(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$2.added,entitiesUpdated:c$2.updated,entitiesRemoved:c$2.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};
1
+ import {c}from'./chunk-7Y3KVZJF.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {a}from'./chunk-AFIFZTOY.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c$1({...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$1(f(t))!==c$1(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$1(i)!==c$1(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){c(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=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$2=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c$1(t.quality)!==c$1(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$2.added,entitiesUpdated:c$2.updated,entitiesRemoved:c$2.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-KR7CIEQR.js';
@@ -1 +1 @@
1
- export{c as DEFAULT_HISTORY_RETENTION,b as WORKSPACE_HISTORY_PATH,a as WORKSPACE_HISTORY_SCHEMA_VERSION,i as appendHistoryEntry,f as historyEntryFromAgentAction,g as historyEntryFromDoctorFixResult,e as historyEntryFromVerify,d as normalizeHistoryEntry,h as readWorkspaceHistory,j as recordWorkspaceHistory}from'./chunk-GDU7VP6G.js';
1
+ export{c as DEFAULT_HISTORY_RETENTION,b as WORKSPACE_HISTORY_PATH,a as WORKSPACE_HISTORY_SCHEMA_VERSION,i as appendHistoryEntry,f as historyEntryFromAgentAction,g as historyEntryFromDoctorFixResult,e as historyEntryFromVerify,d as normalizeHistoryEntry,h as readWorkspaceHistory,j as recordWorkspaceHistory}from'./chunk-GBMCHFOV.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-S7Z4DP3P.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-5BGPGNRQ.js';export{d as hashWorkspaceModel}from'./chunk-EWZZUQBR.js';
@@ -0,0 +1 @@
1
+ import {a as a$1,b as b$1,c,d as d$1}from'./chunk-V5EYVQ63.js';import {a}from'./chunk-AFIFZTOY.js';import {e}from'./chunk-5EPPPMAS.js';import d from'crypto';import s from'path';import {open,unlink,stat}from'fs/promises';import u from'fs-extra';var k=e.evaluationLive,O=e.evaluationLastRun,W="contracts/workspace-intelligence/model-usage-event.v1.json",E="contracts/workspace-intelligence/workspace-intelligence-evaluation.v1.json",P="contracts/workspace-intelligence/workspace-intelligence-evaluation-comparison.v1.json",_=3e4,N=100,b=25;function C(){return {modelCalls:0,toolCalls:0,tokenSources:{providerReported:0,tokenizerCounted:0,estimated:0,unavailable:0},tokens:{input:0,output:0,cachedInput:0,reasoning:0,observedTotal:0},latencyMs:0,costs:[],outcome:{status:"unknown",verified:false,blockersResolved:0},efficiency:{tokensPerVerifiedOutcome:null,noProgressDecisions:0,repeatedArtifactReads:0}}}function m(t){return t??0}function S(t){let e=C(),a=new Map,n=new Map;for(let o of t){if(o.kind==="model-call"){e.modelCalls+=1;let r={"provider-reported":"providerReported","tokenizer-counted":"tokenizerCounted",estimated:"estimated",unavailable:"unavailable"}[o.modelCall.source];if(e.tokenSources[r]+=1,e.tokens.input+=m(o.modelCall.inputTokens),e.tokens.output+=m(o.modelCall.outputTokens),e.tokens.cachedInput+=m(o.modelCall.cachedInputTokens),e.tokens.reasoning+=m(o.modelCall.reasoningTokens),e.latencyMs+=o.modelCall.latencyMs??0,o.modelCall.cost){let i=o.modelCall.cost.currency.toUpperCase(),l=n.get(i)??{currency:i,amount:0,providerReported:0,estimated:0};l.amount+=o.modelCall.cost.amount,o.modelCall.cost.source==="provider-reported"?l.providerReported+=o.modelCall.cost.amount:l.estimated+=o.modelCall.cost.amount,n.set(i,l);}continue}if(o.kind==="tool-call"){e.toolCalls+=1,e.latencyMs+=o.toolCall.durationMs??0,!o.toolCall.changedSource&&o.toolCall.result==="passed"&&(e.efficiency.noProgressDecisions+=1),o.toolCall.artifact&&a.set(o.toolCall.artifact,(a.get(o.toolCall.artifact)??0)+1);continue}o.kind==="outcome"&&(e.outcome={status:o.outcome.status,verified:o.outcome.verified,blockersResolved:o.outcome.blockersResolved});}return e.tokens.observedTotal=e.tokens.input+e.tokens.output,e.costs=[...n.values()].map(o=>({...o,amount:Number(o.amount.toFixed(8)),providerReported:Number(o.providerReported.toFixed(8)),estimated:Number(o.estimated.toFixed(8))})).sort((o,r)=>o.currency.localeCompare(r.currency)),e.efficiency.repeatedArtifactReads=[...a.values()].reduce((o,r)=>o+Math.max(0,r-1),0),e.efficiency.tokensPerVerifiedOutcome=e.outcome.verified&&e.outcome.status==="passed"?e.tokens.observedTotal:null,e}function x(t,e=new Date){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Evaluation event must be a JSON object.");let a$2=t,n={...a$2,schemaVersion:a$1,eventId:typeof a$2.eventId=="string"&&a$2.eventId.trim()?a$2.eventId.trim():d.randomUUID(),recordedAt:typeof a$2.recordedAt=="string"&&a$2.recordedAt.trim()?a$2.recordedAt:e.toISOString()};a(n,W,"workspace evaluation event");let o={"model-call":"modelCall","tool-call":"toolCall",outcome:"outcome",milestone:"milestone"}[n.kind],r=["modelCall","toolCall","outcome","milestone"].filter(i=>a$2[i]!==void 0);if(r.length!==1||r[0]!==o)throw new Error(`Evaluation event kind ${n.kind} requires only ${o}.`);if(n.kind==="model-call"&&n.modelCall.source!=="unavailable"&&n.modelCall.inputTokens===null&&n.modelCall.outputTokens===null)throw new Error("Measured model calls require at least one input or output token count.");return n}function J(t){let e=t.now??new Date,a$1=s.resolve(t.workspacePath),n={schemaVersion:b$1,runId:t.runId??d.randomUUID(),sessionId:t.sessionId??d.randomUUID(),status:"live",startedAt:e.toISOString(),updatedAt:e.toISOString(),workspace:{name:t.workspaceName?.trim()||s.basename(a$1),path:a$1},configuration:{taskId:t.taskId.trim(),strategy:t.strategy??"workspace-intelligence",...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baselineRunId?{baselineRunId:t.baselineRunId}:{}},methodology:{id:"provider-usage-and-verified-outcome.v1",claimBoundary:"Provider-reported and tokenizer-counted values are measured; estimated values remain explicitly labelled. Verified task success is required before reporting tokens per successful outcome."},events:[],summary:C()};return a(n,E,"workspace evaluation"),n}async function L(t,e){await u.ensureDir(s.dirname(t));let a=`${t}.${process.pid}.${d.randomUUID()}.tmp`;try{await u.writeJson(a,e,{spaces:2}),await u.rename(a,t);}finally{await u.remove(a).catch(()=>{});}}async function A(t,e){let a=s.join(s.resolve(t),`${k}.lock`);await u.ensureDir(s.dirname(a));for(let n=0;n<N;n+=1)try{let o=await open(a,"wx");try{return await o.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await o.close(),await unlink(a).catch(()=>{});}}catch(o){if(o.code!=="EEXIST")throw o;let i=await stat(a).catch(()=>null);if(i&&Date.now()-i.mtimeMs>_){await unlink(a).catch(()=>{});continue}await new Promise(l=>setTimeout(l,b));}throw new Error("Timed out waiting for the workspace evaluation writer lock.")}async function v(t,e,a$1=k){let n=s.join(s.resolve(t),a$1);return a(e,E,a$1),await L(n,e),n}async function T(t,e=k){let a$1=s.isAbsolute(e)?e:s.join(s.resolve(t),e),n=await u.readJson(a$1);return a(n,E,a$1),n}async function G(t){return A(t.workspacePath,async()=>{let e=await T(t.workspacePath);if(e.status!=="live")throw new Error(`Evaluation ${e.runId} is ${e.status}; initialize a new run.`);let a=x(t.payload,t.now);if(e.events.some(o=>o.eventId===a.eventId))return e;let n={...e,updatedAt:(t.now??new Date).toISOString(),events:[...e.events,a],summary:S([...e.events,a])};return await v(t.workspacePath,n),n})}async function H(t){return A(t.workspacePath,async()=>{let e=await T(t.workspacePath),a=(t.now??new Date).toISOString(),n={...e,status:t.status??"completed",updatedAt:a,completedAt:a,summary:S(e.events)},o=await v(t.workspacePath,n,O);return await v(t.workspacePath,n),{report:n,outputPath:o}})}function q(t,e){let a$1=t.summary.tokens.observedTotal,n=e.summary.tokens.observedTotal,o=a$1-n,r={schemaVersion:c,generatedAt:new Date().toISOString(),taskAligned:t.configuration.taskId===e.configuration.taskId,current:{runId:t.runId,strategy:t.configuration.strategy,tokens:a$1,verified:t.summary.outcome.verified,status:t.summary.outcome.status},baseline:{runId:e.runId,strategy:e.configuration.strategy,tokens:n,verified:e.summary.outcome.verified,status:e.summary.outcome.status},delta:{tokens:o,reductionPercent:n===0?null:Number((-o/n*100).toFixed(2)),modelCalls:t.summary.modelCalls-e.summary.modelCalls,toolCalls:t.summary.toolCalls-e.summary.toolCalls,latencyMs:Number((t.summary.latencyMs-e.summary.latencyMs).toFixed(2))},comparableOutcome:t.summary.outcome.verified&&e.summary.outcome.verified&&t.summary.outcome.status===e.summary.outcome.status};return a(r,P,"workspace evaluation comparison"),r}function B(){if(d$1.length!==4)throw new Error("Model usage source taxonomy is incomplete.")}export{O as WORKSPACE_EVALUATION_LAST_RUN_PATH,k as WORKSPACE_EVALUATION_LIVE_PATH,G as appendWorkspaceEvaluationEvent,B as assertWorkspaceEvaluationSourceTaxonomy,q as compareWorkspaceEvaluations,J as createWorkspaceEvaluation,H as finalizeWorkspaceEvaluation,x as normalizeWorkspaceEvaluationEvent,T as readWorkspaceEvaluation,S as summarizeWorkspaceEvaluation,v as writeWorkspaceEvaluation};
@@ -1 +1 @@
1
- export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-DS4UYMLX.js';
1
+ export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-664GXRLD.js';
@@ -0,0 +1 @@
1
+ export{j as WORKSPACE_INTELLIGENCE_ADDITIONAL_PRODUCERS,e as WORKSPACE_INTELLIGENCE_ARTIFACTS,f as WORKSPACE_INTELLIGENCE_ARTIFACT_SCHEMAS,g as WORKSPACE_INTELLIGENCE_ARTIFACT_SCHEMA_CONTRACTS,k as WORKSPACE_INTELLIGENCE_COMMAND_SIGNATURES,o as WORKSPACE_INTELLIGENCE_PREFLIGHT_ARTIFACTS,n as WORKSPACE_INTELLIGENCE_PREFLIGHT_IDS,l as WORKSPACE_INTELLIGENCE_ROOT_COMMANDS,p as WORKSPACE_INTELLIGENCE_RUNTIME_STEPS,m as WORKSPACE_INTELLIGENCE_STEP_IDS,i as WORKSPACE_SUPPLEMENTAL_ARTIFACTS,h as WORKSPACE_SUPPLEMENTAL_ARTIFACT_CONTRACTS,q as workspaceIntelligenceRuntimeStep}from'./chunk-5EPPPMAS.js';
@@ -0,0 +1 @@
1
+ export{b as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,c as assertWorkspaceKnowledgeGraphSourceBinding,e as buildWorkspaceKnowledgeGraph,d as computeWorkspaceKnowledgeGraphInputFingerprint,f as knowledgeEntityId}from'./chunk-7Y3KVZJF.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-PS5F4DCT.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-VGJVIHHR.js';
@@ -0,0 +1 @@
1
+ import {c,d as d$1}from'./chunk-7Y3KVZJF.js';import {d}from'./chunk-ADL3CK44.js';import {e,f as f$1}from'./chunk-5EPPPMAS.js';import A from'fs-extra';function t(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function W(e){let s=t(e);return !!(s&&s.schemaVersion===f$1.model&&t(s.workspace)&&Array.isArray(s.projects)&&(t(s.projectTopology)||t(s.graph)))}function G(e){let s=t(e);return !!(s&&s.schemaVersion===f$1.knowledgeGraph&&t(s.source)&&t(s.workspace)&&Array.isArray(s.entities)&&Array.isArray(s.relations)&&Array.isArray(s.proofs)&&Array.isArray(s.providers)&&t(s.quality))}async function f(e){try{return await A.readJson(e)}catch{return null}}async function I(e$1){let[s,n]=await Promise.all([d(e$1,e.model),d(e$1,e.knowledgeGraph)]);if(!s)return {status:"miss",reason:"missing-model"};if(!n)return {status:"miss",reason:"missing-graph"};let[i,o]=await Promise.all([f(s),f(n)]);if(!W(i))return {status:"miss",reason:"invalid-model"};if(!G(o))return {status:"miss",reason:"invalid-graph"};if(o.proofs.some(r=>r.freshness==="stale"))return {status:"miss",reason:"stale-proof"};try{c(o,i);}catch{return {status:"miss",reason:"source-mismatch"}}let a=o.source.inputs;if(!a)return {status:"miss",reason:"missing-input-fingerprint"};let d$2=a.scopes.filter(r=>r.kind==="workspace"),p=a.scopes.filter(r=>r.kind==="project"),k=i.projects.map(r=>r.name).sort(),w=p.map(r=>r.id).sort(),y=new Set(p.map(r=>r.fileLimit));if(a.schemaVersion!=="workspace-knowledge-graph-inputs.v1"||a.strategy!=="hybrid-git-content-v2"||a.hashAlgorithm!=="sha256"||d$2.length!==1||y.size>1||JSON.stringify(k)!==JSON.stringify(w))return {status:"miss",reason:"invalid-input-fingerprint"};let c$1;try{c$1=await d$1({workspacePath:e$1,projects:i.projects.map(r=>({id:r.name,path:r.path,...r.absolutePath?{absolutePath:r.absolutePath}:{}})),projectFileLimit:p[0]?.fileLimit??2e4,workspaceFileLimit:d$2[0].fileLimit});}catch{return {status:"miss",reason:"input-scan-failed"}}return !c$1||c$1.hash!==a.hash?{status:"miss",reason:"live-input-mismatch"}:{status:"hit",model:i,graph:o,modelPath:s,graphPath:n}}export{I as readWorkspaceKnowledgeGraphSnapshot};
@@ -0,0 +1,3 @@
1
+ import {b}from'./chunk-OX53L237.js';import {c,e as e$1}from'./chunk-NHTLE3WN.js';import {d,c as c$1,f,e as e$2}from'./chunk-VGJVIHHR.js';import {c as c$3,b as b$2}from'./chunk-64JUYYRC.js';import {b as b$1}from'./chunk-WOTTSPSF.js';import {d as d$2}from'./chunk-XH7PDHBF.js';import {c as c$2}from'./chunk-7Y3KVZJF.js';import {k}from'./chunk-5ZA4JYOP.js';import {e as e$3}from'./chunk-DOIZANFA.js';import {d as d$1}from'./chunk-ADL3CK44.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {e,g}from'./chunk-5EPPPMAS.js';import {v}from'./chunk-MOSXTVPU.js';import u from'path';import N from'readline';import g$1 from'fs-extra';var L=e.agentIndex,q=new Map(Object.keys(e).flatMap(e$1=>{let t=g[e$1];return t?[[e[e$1],t]]:[]}));function M(e,t){return e.kind!==t.kind?false:e.kind==="project"&&t.kind==="project"?e.project.toLowerCase()===t.project.toLowerCase():e.kind==="blocker"&&t.kind==="blocker"?e.blockerId===t.blockerId:e.kind==="trace"&&t.kind==="trace"?e.diffRef===t.diffRef:true}var J=[{name:"getWorkspaceModel",description:"Read workspace-model.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceKnowledgeGraph",description:"Read the current proof-backed workspace knowledge graph artifact",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceEvaluation",description:"Read the live or finalized provenance-aware model usage and verified-outcome report",inputSchema:{type:"object",properties:{live:{type:"boolean",description:"Read the live report instead of the finalized last-run report"}}}},{name:"queryWorkspaceEntities",description:"List workspace knowledge entities, optionally filtered by kind",inputSchema:{type:"object",properties:{kind:{type:"string",description:"Optional entity kind"}}}},{name:"searchWorkspaceGraph",description:"Return bounded, proof-carrying workspace context matching a text query",inputSchema:{type:"object",properties:{query:{type:"string",description:"Text, path, symbol, service, or concept to find"},kind:{type:"string",description:"Optional entity kind filter"},projectId:{type:"string",description:"Optional canonical project id filter"},limit:{type:"integer",minimum:1,maximum:100,default:12}},required:["query"]}},{name:"getWorkspaceGraphEvidence",description:"Resolve portable evidence for a knowledge graph entity or relation",inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]}},{name:"findWorkspaceGraphPath",description:"Find a shortest proof-carrying path between two workspace entities",inputSchema:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"]}},{name:"getEvidenceIndex",description:"Read agent reports INDEX.json",inputSchema:{type:"object",properties:{}}},{name:"getBlockers",description:"Aggregate blocking reasons from verify, explain, and contract-verify reports",inputSchema:{type:"object",properties:{}}},{name:"getSafeCommands",description:"Read safe commands from workspace-context-agent.json",inputSchema:{type:"object",properties:{}}},{name:"getProjectContext",description:"Read scoped project context from workspace-context-agent.json",inputSchema:{type:"object",properties:{project:{type:"string",description:"Optional project name; defaults to active scope"}}}},{name:"getArtifact",description:"Read one workspace-relative artifact path",inputSchema:{type:"object",properties:{relativePath:{type:"string"}},required:["relativePath"]}},{name:"listOperationalSkills",description:"Read workspace-skills-index.json",inputSchema:{type:"object",properties:{}}},{name:"getWorkspaceExplain",description:"Build or read workspace explain report",inputSchema:{type:"object",properties:{target:{type:"string",description:"release-blocked | project:<name> | blocker:<id> | trace:<diffRef> | <project>"}}}}];function H(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!u.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function a(e$1,t){if(!H(t))throw new Error(`Unsafe artifact path: ${t}`);let r=await d$1(e$1,t)??u.join(e$1,t);if(!await g$1.pathExists(r))return null;let n=await g$1.readJson(r),o=v(t),c=q.get(o);if(c&&a$1(n,c,`MCP artifact ${o}`),o===e.knowledgeGraph){let p=u.join(e$1,k);if(!await g$1.pathExists(p))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let l=await g$1.readJson(p);c$2(n,l);}return n}async function F(e){let t=[],r=new Set,o=((await a(e,d$2))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$2,reasons:o});for(let i of o)r.add(i);}let c=await a(e,c$3);if(e$1(c)){let i=(c.blockingReasons??[]).filter(s=>typeof s=="string"&&s.trim().length>0);if(i.length>0){t.push({artifact:c$3,reasons:i});for(let s of i)r.add(s);}}let p=await a(e,e$3),l=(p?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(l.length>0||String(p?.status??"").toLowerCase()==="failed"){let i=l.length>0?l:["Workspace contract verification failed"];t.push({artifact:e$3,reasons:i});for(let s of i)r.add(s);}return {blockingReasons:[...r],sources:t}}async function G(e$3,t,r){switch(t){case "getWorkspaceModel":return a(e$3,k);case "getWorkspaceKnowledgeGraph":return a(e$3,e.knowledgeGraph);case "getWorkspaceEvaluation":return a(e$3,r.live===true?e.evaluationLive:e.evaluationLastRun);case "queryWorkspaceEntities":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=String(r.kind??"").trim();return {schemaVersion:n.schemaVersion,generatedAt:n.generatedAt,entities:e$2(n,o||void 0)}}case "searchWorkspaceGraph":{let n=await a(e$3,e.knowledgeGraph);if(!n)return null;let o=typeof r.limit=="number"?r.limit:Number(r.limit??12);return f(n,{query:String(r.query??""),...typeof r.kind=="string"&&r.kind.trim()?{kind:r.kind.trim()}:{},...typeof r.projectId=="string"&&r.projectId.trim()?{projectId:r.projectId.trim()}:{},limit:Number.isFinite(o)?o:12,projection:"agent"})}case "getWorkspaceGraphEvidence":{let n=await a(e$3,e.knowledgeGraph);return n?c$1(n,String(r.query??"")):null}case "findWorkspaceGraphPath":{let n=await a(e$3,e.knowledgeGraph);return n?d(n,String(r.from??""),String(r.to??"")):null}case "getEvidenceIndex":return a(e$3,L);case "getBlockers":return F(e$3);case "getSafeCommands":return {safeCommands:(await a(e$3,b$1))?.safeCommands??[]};case "getProjectContext":{let n=await a(e$3,b$1);if(!n)return null;let o=String(r.project??"").trim(),c=n.scope?.activeProject??void 0,p=o||c,l=Array.isArray(n.projects)?n.projects:[],i=p&&l.find(s=>typeof s.name=="string"&&s.name.toLowerCase()===p.toLowerCase());return {workspace:n.workspace??null,scope:n.scope??null,validation:n.validation??null,project:i??null,safeCommands:n.safeCommands??[]}}case "getArtifact":{let n=String(r.relativePath??"").trim();return a(e$3,n)}case "listOperationalSkills":return a(e$3,b$2);case "getWorkspaceExplain":{let n=String(r.target??"release-blocked").trim(),o=c(n);if(!o)throw new Error(`Invalid explain target: ${n}`);let c$1=await a(e$3,c$3);return e$1(c$1)&&M(c$1.target,o)?c$1:b({workspacePath:e$3,target:o})}default:throw new Error(`Unknown tool: ${t}`)}}function R(e,t){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:t})}
2
+ `);}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};
@@ -1 +1 @@
1
- export{k as WORKSPACE_MODEL_REPORT_PATH,j as WORKSPACE_MODEL_SCHEMA_VERSION,p as buildWorkspaceModel,q as buildWorkspaceModelCached,o as buildWorkspaceModelFacts,r as buildWorkspaceModelIncremental,m as createWorkspaceModelBuildProvenance,n as validateWorkspaceModelStrict,l as workspaceModelProjectTopology,s as writeWorkspaceModel}from'./chunk-7AR5PDLD.js';
1
+ export{k as WORKSPACE_MODEL_REPORT_PATH,j as WORKSPACE_MODEL_SCHEMA_VERSION,p as buildWorkspaceModel,q as buildWorkspaceModelCached,o as buildWorkspaceModelFacts,r as buildWorkspaceModelIncremental,m as createWorkspaceModelBuildProvenance,n as validateWorkspaceModelStrict,l as workspaceModelProjectTopology,s as writeWorkspaceModel}from'./chunk-5ZA4JYOP.js';
@@ -1 +1 @@
1
- export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-HUPLAFZQ.js';
1
+ export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-HASVV34S.js';
@@ -1,4 +1,4 @@
1
- import {b as b$1}from'./chunk-RA24WQLF.js';import {g as g$1}from'./chunk-WIO6L24E.js';import g from'path';import i from'fs-extra';var l="README.md",h="<!-- workspai:workspace-intelligence:start -->",c="<!-- workspai:workspace-intelligence:end -->",m={minimal:"A lightweight workspace boundary that adds runtimes only when you need them.","node-only":"A Node.js-focused workspace with shared evidence and agent grounding.","python-only":"A Python-focused workspace with shared evidence and agent grounding.","go-only":"A Go-focused workspace with shared evidence and agent grounding.","java-only":"A Java-focused workspace with shared evidence and agent grounding.","dotnet-only":"A .NET-focused workspace with shared evidence and agent grounding.",polyglot:"A multi-runtime workspace for projects that share contracts, evidence, and agents.",enterprise:"A governed multi-runtime workspace with the complete evidence, policy, and agent surface."};function w(e){return e?.trim()||"minimal"}async function u(e){let n=g.join(e,".workspai","workspace.json");return await i.pathExists(n)?await i.readJson(n).catch(()=>({})):{}}function f(e){let n=e.engine;if(!n)return;if(n.python_core?.status==="skipped")return "Optional Python engine: not installed";if(n.python_version)return `Optional Python engine: Python ${n.python_version} via ${n.install_method||"local environment"}`}function y(e){let n=w(e.profile),r=b$1().presentations.standard.nodes.map(s=>s.label).join(" \u2192 "),a=e.projectCount===1?"project":"projects",t=m[n]??"A governed workspace with shared evidence for developers, tools, CI, IDEs, and AI agents.";return `${h}
1
+ import {b as b$1}from'./chunk-UQEQ6CXU.js';import {g as g$1}from'./chunk-ADL3CK44.js';import g from'path';import i from'fs-extra';var l="README.md",h="<!-- workspai:workspace-intelligence:start -->",c="<!-- workspai:workspace-intelligence:end -->",m={minimal:"A lightweight workspace boundary that adds runtimes only when you need them.","node-only":"A Node.js-focused workspace with shared evidence and agent grounding.","python-only":"A Python-focused workspace with shared evidence and agent grounding.","go-only":"A Go-focused workspace with shared evidence and agent grounding.","java-only":"A Java-focused workspace with shared evidence and agent grounding.","dotnet-only":"A .NET-focused workspace with shared evidence and agent grounding.",polyglot:"A multi-runtime workspace for projects that share contracts, evidence, and agents.",enterprise:"A governed multi-runtime workspace with the complete evidence, policy, and agent surface."};function w(e){return e?.trim()||"minimal"}async function u(e){let n=g.join(e,".workspai","workspace.json");return await i.pathExists(n)?await i.readJson(n).catch(()=>({})):{}}function f(e){let n=e.engine;if(!n)return;if(n.python_core?.status==="skipped")return "Optional Python engine: not installed";if(n.python_version)return `Optional Python engine: Python ${n.python_version} via ${n.install_method||"local environment"}`}function y(e){let n=w(e.profile),r=b$1().presentations.standard.nodes.map(s=>s.label).join(" \u2192 "),a=e.projectCount===1?"project":"projects",t=m[n]??"A governed workspace with shared evidence for developers, tools, CI, IDEs, and AI agents.";return `${h}
2
2
  # ${e.workspaceName}
3
3
 
4
4
  This is a **Workspai Workspace Intelligence** workspace. It gives every registered project one shared, evidence-backed view for developers, CI, IDEs, and AI agents.
@@ -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-3DONU3DU.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-QTCZPS5I.js';
@@ -0,0 +1,3 @@
1
+ import {c as c$2}from'./chunk-664GXRLD.js';import {a as a$1}from'./chunk-YJTEMJFV.js';import {d as d$1,i as i$1,j as j$1,k,h as h$2,m,n,o}from'./chunk-QRWWYL52.js';import {c,e,j,d,g,b,i,f}from'./chunk-PKIRVQLG.js';import {a as a$2}from'./chunk-AO2ZI42U.js';import {h as h$1}from'./chunk-BDN32Y2N.js';import {a}from'./chunk-AFIFZTOY.js';import {e as e$1}from'./chunk-5EPPPMAS.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import h from'fs-extra';var $e=".workspai/repair",ga="transaction.json",fa="source-plan.json",Ue="checkpoint",ka="engine.lock",aa=5*1024*1024,ma=25*1024*1024,wa=25*1024*1024,ta=4*1024*1024,ba=900*1e3,va=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"]),ya=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","requirements.txt","requirements-dev.txt","uv.lock","poetry.lock","go.mod","go.sum","Cargo.toml","Cargo.lock","composer.json","composer.lock","Gemfile","Gemfile.lock","mix.exs","mix.lock","deno.json","deno.jsonc","deno.lock","Directory.Packages.props","packages.lock.json","pom.xml","build.gradle","build.gradle.kts","gradle.lockfile","deps.edn","project.clj","build.sbt"]),_={safe:0,guarded:1,invasive:2},Pa=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 Ra(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function N(e,a,r={kind:"failed-precondition"}){return {reason:e,options:a,causes:[{...r,id:r.id??`runtime:${$(e).slice(0,16)}`,message:r.message??e}]}}function ra(e){let a=new Map,r=t=>a.set(Ra(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=ye(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}:{}}),_[t.risk]>_[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(s=>s.invocation&&`tool:${s.invocation.cwd}:${s.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${$(t).slice(0,16)}`,message:t});}return [...a.values()]}function D(e){return (e?.()??new Date).toISOString()}function $(e){return createHash("sha256").update(e).digest("hex")}function Q(e){return Array.isArray(e)?`[${e.map(Q).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)}:${Q(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}var Ae="causal-action-integrity:";function oa(e){return $(Q([...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 sa(e){if(e.length===0)return;let a=oa(e);return {id:`${Ae}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function C(e,a){let r=c$1.relative(c$1.resolve(e),c$1.resolve(a));return r===""||!r.startsWith("..")&&!c$1.isAbsolute(r)}async function H(e,a){let r=await h.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await h.pathExists(t);){let s=c$1.dirname(t);if(s===t)return false;t=s;}let o=await h.realpath(t).catch(()=>c$1.resolve(t));return C(r,o)}function F(e,a){let r=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!C(e,r))throw new Error(`Repair path escapes workspace boundary: ${a}`);return c$1.relative(e,r).split(c$1.sep).join("/")||"."}function ae(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,$e,"transactions",a)}function ve(e,a){return c$1.join(ae(e,a),ga)}function Se(e,a){return c$1.join(ae(e,a),fa)}async function Z(e,a){await h.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await h.writeJson(r,a,{spaces:2}),await h.move(r,e,{overwrite:true});}function A(e,a,r,t={}){e.events.push({sequence:e.events.length+1,at:D(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r});}async function R(e$1,a$1,r){a$1.revision+=1,a$1.updatedAt=D(r),a(a$1,e,"Workspace repair transaction"),await Z(ve(e$1,a$1.transactionId),a$1),await Z(c$1.join(e$1,d),a$1);}async function ce(e$1){let a$1=await h.readJson(ve(e$1.workspacePath,e$1.transactionId));if(a$1.schemaVersion!==c)throw new Error(`Unsupported repair transaction schema: ${a$1.schemaVersion}`);return a(a$1,e,"Workspace repair transaction"),a$1}async function Ce(e,a){return await h.readJson(Se(e,a))}function we(e){return e.schemaVersion===f}function he(e,a){let r=a.scope==="project"&&a.projectPath?a.projectPath:".",t=c$1.isAbsolute(r)?c$1.resolve(r):c$1.resolve(e,r);if(!C(e,t))throw new Error(`Repair project scope escapes workspace: ${r}`);return t}function v(e){return {cwd:F(e.workspacePath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Ie(e){return h.readFile(e,"utf8").catch(()=>"")}async function xa(e){return h.readJson(e).catch(()=>({}))}function Ye(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}function ja(e){let a=process.platform==="win32"?(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(t=>t.toLowerCase()):[""],r=c$1.extname(e).length>0;return (process.env.PATH??"").split(c$1.delimiter).filter(Boolean).flatMap(t=>r?[c$1.join(t,e)]:a.map(o=>c$1.join(t,`${e}${o}`)))}function Xe(e){return e?.isFile()?process.platform==="win32"||(e.mode&73)!==0:false}async function ia(e){let a=c$1.resolve(e.workspacePath,e.invocation.cwd);if(e.toolAvailable)return e.toolAvailable(e.invocation.executable,a);let r=e.invocation.executable;if(c$1.isAbsolute(r)||/^\.{1,2}[\\/]/.test(r)){let t=c$1.isAbsolute(r)?r:c$1.resolve(a,r),o=await h.stat(t).catch(()=>{});return Xe(o)}for(let t of ja(r)){let o=await h.stat(t).catch(()=>{});if(Xe(o))return true}return false}async function We(e){let a=new Set;for(let s of e.stages){if(s.kind!=="repair"||!s.invocation)continue;let d=Pe(s.invocation.executable);!["python","python3","py"].includes(d)||!s.invocation.args.includes("venv")||!s.invocation.args.includes(".venv")||a.add(c$1.normalize(c$1.join(c$1.resolve(e.workspacePath,s.invocation.cwd),".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(s=>s.required&&s.status!=="skipped"&&s.invocation).map(s=>s.invocation),t=new Map;for(let s of r)t.set(`${s.cwd}\0${s.executable}`,s);let o=[];for(let s of t.values()){let d=c$1.isAbsolute(s.executable)?c$1.normalize(s.executable):c$1.normalize(c$1.resolve(e.workspacePath,s.cwd,s.executable));if(a.has(d)){o.push({id:`tool:${s.cwd}:${s.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${s.executable} (${s.cwd}).`});continue}let i=await ia({workspacePath:e.workspacePath,invocation:s,toolAvailable:e.toolAvailable});o.push({id:`tool:${s.cwd}:${s.executable}`,status:i?"passed":"failed",message:i?`Required repair executable is available: ${s.executable} (${s.cwd}).`:`Required repair executable is unavailable: ${s.executable} (${s.cwd}). Install or configure it, then create a fresh plan.`});}return o}function X(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function y(e){return {id:e.id,kind:e.kind,status:e.invocation?"pending":e.required===false?"skipped":"blocked",required:e.required??true,risk:e.risk??"safe",summary:e.summary,...e.invocation?{invocation:e.invocation}:{}}}function Ia(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 Aa(e){let a=he(e.workspacePath,e.action),r=F(e.workspacePath,a),t=async p=>h.pathExists(c$1.join(a,p)),o=new Set,s=[],d=[],i$1=p=>`${r}:${e.adapterId}:${p}`,g=p=>p.forEach(P=>o.add(F(e.workspacePath,c$1.join(a,P)))),n=p=>{s.push(p),p.required&&p.status==="blocked"&&d.push(p.summary);},f=Ia(e.workspacePath,a,e.action),k=()=>{let p=i.find(P=>P.id===e.adapterId);if(!p)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:s,checkpointFiles:[...o],blockers:d,adapters:[{adapterId:p.id,ecosystem:p.ecosystem,projectPath:r,manifests:p.manifests,support:p.support,status:d.length>0?"partial":"ready",requiredExecutables:[...new Set(s.filter(P=>P.required&&P.invocation).map(P=>P.invocation.executable))],missingExecutables:[],message:d.length>0?[...new Set(d)].join(" "):`${p.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let p=await xa(c$1.join(a,"package.json")),P=p.scripts&&typeof p.scripts=="object"&&!Array.isArray(p.scripts)?p.scripts:{},b=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",T=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";g(["package.json",T]),n(y({id:i$1("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 S=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 n(y({id:i$1("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:f??S})),n(typeof P.test=="string"&&P.test.trim()?y({id:i$1("test"),kind:"test",summary:"Run the declared project test contract.",invocation:Ye({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"test",purpose:"test"})}):X(i$1("test"),"test","No test script is declared.")),n(typeof P.build=="string"&&P.build.trim()?y({id:i$1("build"),kind:"build",summary:"Run the declared project build contract.",invocation:Ye({workspacePath:e.workspacePath,projectPath:a,manager:b,script:"build",purpose:"build"})}):X(i$1("build"),"build","No build script is declared.")),k()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){g(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let p=e.action.transaction?.ecosystem.toLowerCase(),P=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),b=P==="uv"||p==="uv"||await t("uv.lock"),T=!b&&(P==="poetry"||p==="poetry"||await t("poetry.lock")),S=!b&&!T&&["python","python3","py"].includes(P)&&(e.action.invocation?.args??[]).some(L=>L==="venv")&&(e.action.invocation?.args??[]).some(L=>L===".venv"),j=process.platform==="win32"?"python":"python3",O=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await h.pathExists(O)||S)&&(j=O);let te=b?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):T?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&C(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&C(e.workspacePath,j)?v({workspacePath:e.workspacePath,projectPath:a,executable:j,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:te})),n(y({id:i$1("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:f}));let M=await Ie(c$1.join(a,"pyproject.toml")),B=await t("tests")||/\[tool\.pytest/i.test(M),J=v(T?{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:j,args:["-m","pytest"],purpose:"test"}),re=v(T?{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:j,args:["-m","build"],purpose:"build"});return n(B?y({id:i$1("test"),kind:"test",summary:"Run the Python test contract.",invocation:J}):X(i$1("test"),"test","No Python test surface is declared.")),n(/\[build-system\]/i.test(M)?y({id:i$1("build"),kind:"build",summary:"Build the declared Python package.",invocation:re}):X(i$1("build"),"build","No Python build contract is declared.")),k()}let m=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let p of m){if(p.adapterId!==e.adapterId)continue;let P=await t(p.manifest)?p.manifest:p.alternateManifest&&await t(p.alternateManifest)?p.alternateManifest:void 0;if(!P)continue;g(p.files),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${P} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.reconcile[0],args:p.reconcile[1],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:f??(p.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:p.audit[0],args:p.audit[1],purpose:"audit"}):void 0)}));let b=await Ie(c$1.join(a,P)),T=p.manifest==="composer.json"||p.adapterId==="deno"?/["']test["']\s*:/.test(b):p.manifest==="Gemfile"?await t("Rakefile"):true,S=p.manifest==="composer.json"||p.manifest==="deno.json"?/["']build["']\s*:/.test(b):p.manifest==="Gemfile"?(await h.readdir(a)).some(j=>j.endsWith(".gemspec")):true;return n(T?y({id:i$1("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.test[0],args:p.test[1],purpose:"test"})}):X(i$1("test"),"test","No test contract is declared.")),n(S?y({id:i$1("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p.build[0],args:p.build[1],purpose:"build"})}):X(i$1("build"),"build","No build contract is declared.")),k()}let x=await h.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&x.some(p=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(p)))return g(["Directory.Packages.props","packages.lock.json",...x.filter(p=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(p))]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:f??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),n(y({id:i$1("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),n(y({id:i$1("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 I=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return g(["pom.xml"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["dependency:resolve"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:I,args:["package","-DskipTests"],purpose:"build"})})),k();let W=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&W){let p=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return g([W,"gradle.lockfile","gradle/libs.versions.toml"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["dependencies"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:p,args:["build","-x","test"],purpose:"build"})})),k()}let w=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&w){let p=w==="deps.edn",P=await Ie(c$1.join(a,w)),b=p?"clojure":"lein";g([w]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${w} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:p?["-P"]:["deps"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:f}));let T=!p||/:test\b/.test(P);return n(T?y({id:i$1("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:b,args:p?["-M:test"]:["test"],purpose:"test"})}):X(i$1("test"),"test","No Clojure :test alias is declared.")),n(p?X(i$1("build"),"build","No portable Clojure CLI build entrypoint is declared."):y({id:i$1("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")?(g(["build.sbt"]),n(y({id:i$1("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),n(y({id:i$1("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:f})),n(y({id:i$1("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),n(y({id:i$1("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),k()):(d.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),n(y({id:i$1("reconcile"),kind:"reconcile",required:true,summary:d[0]})),k())}async function na(e){let a=s=>h.pathExists(c$1.join(e,s)),r=await h.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(s=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");let o=new Map(i.map((s,d)=>[s.id,d]));return [...new Set(t)].sort((s,d)=>(o.get(s)??999)-(o.get(d)??999))}function Ea(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 ca(e,a={}){let r=he(e.workspacePath,e.action),t=F(e.workspacePath,r),o=await na(r),s=Ea(e.action.transaction?.ecosystem),d=s?[s]:o;if(s&&!o.includes(s)){let n=`Doctor declared the ${s} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[y({id:`${t}:${s}:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:s,ecosystem:i.find(f=>f.id===s)?.ecosystem??s,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:n}]}}if(d.length===0){let n=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[y({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:n})],checkpointFiles:[],blockers:[n],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:n}]}}let i$1={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let n of d){let f=await Aa({...e,adapterId:n});i$1.stages.push(...f.stages),i$1.checkpointFiles.push(...f.checkpointFiles),i$1.blockers.push(...f.blockers),i$1.adapters.push(...f.adapters);}i$1.stages=[...new Map(i$1.stages.map(n=>[n.id,n])).values()],i$1.checkpointFiles=[...new Set(i$1.checkpointFiles)].sort(),i$1.blockers=[...new Set(i$1.blockers)];let g=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let n=new Set(e.action.transaction.requiredStages),f=Pe(e.action.invocation?.executable??""),k=e.action.invocation?.args??[],m=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(f)&&k.includes("venv")&&k.includes(".venv");m&&g.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),i$1.stages=i$1.stages.filter(x=>x.kind==="reconcile"?m&&n.has("reconcile"):n.has(x.kind)),i$1.blockers=i$1.stages.filter(x=>x.required&&x.status==="blocked").map(x=>x.summary);}for(let n of i$1.adapters){let f=i$1.stages.filter(m=>m.id.startsWith(`${n.projectPath}:${n.adapterId}:`)),k=[];n.requiredExecutables=[...new Set(f.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))];for(let m of f){if(!m.required||!m.invocation)continue;let x=c$1.isAbsolute(m.invocation.executable)?c$1.normalize(m.invocation.executable):c$1.normalize(c$1.resolve(e.workspacePath,m.invocation.cwd,m.invocation.executable));g.has(x)||await ia({workspacePath:e.workspacePath,invocation:m.invocation,toolAvailable:a.toolAvailable})||k.push(m.invocation.executable);}n.missingExecutables=[...new Set(k)],n.missingExecutables.length>0&&(n.status="partial",n.message=`Required executable(s) unavailable: ${n.missingExecutables.join(", ")}.`);}if(d.length===1){let n=`:${d[0]}:`;for(let f of i$1.stages)f.id=f.id.replace(n,":");}return i$1}async function ut(e={}){let a=j();if(!e.workspacePath&&!e.projectPath&&!e.project)return a;let r=c$1.resolve(e.workspacePath??process.cwd()),t,o;if(e.project?.trim()){let s=e.project.trim(),d=await h$1(r),i=s.replace(/\\/g,"/").replace(/^\.\//,""),g=c$1.resolve(r,s),n=d.resolved.filter(f=>{let k=C(r,f.projectPath)?F(r,f.projectPath):void 0;return f.name===s||k===i||c$1.resolve(f.projectPath)===g});if(n.length===0){let f=d.skipped.find(k=>k.name===s);throw f?new Error(`Registered project is unavailable for repair capability inspection: ${s} (${f.reason}).`):new Error(`Registered project not found for repair capability inspection: ${s}.`)}if(n.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${s}.`);t=c$1.resolve(n[0].projectPath),o=n[0].name;}else {if(t=c$1.resolve(r,e.projectPath??"."),!C(r,t))throw new Error("Repair capability inspection project path escapes the workspace.");o=F(r,t);}return {...a,inspection:{projectPath:o,detectedAdapters:await na(t)}}}function ye(e){if(e.command){let a=d$1(e.command);if(a)return a}return a$2(e.operation)??void 0}async function $a(e){let a=new Set(e.dependencyFiles);for(let r of e.actions){let t=he(e.workspacePath,r);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);for(let d of r.files){let i=c$1.isAbsolute(d)?c$1.resolve(d):c$1.resolve(e.workspacePath,d);if(!await H(e.workspacePath,i))throw new Error(`Repair checkpoint path escapes workspace through a symbolic link: ${d}`);a.add(F(e.workspacePath,d));}let o=ye(r);if(!o)continue;let s="path"in o?o.path:void 0;if(s){let d=c$1.resolve(t,s);if(!await H(e.workspacePath,d))throw new Error(`Repair operation target escapes workspace through a symbolic link: ${s}`);a.add(F(e.workspacePath,d));}}return [...a].filter(r=>r!==".").sort()}function Sa(e,a){if(!a.invocation)return;let r=he(e,a);return v({workspacePath:e,projectPath:r,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Te(e){return $(Q({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 da(e){return Te({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}async function be(e,a){let r=[],t=[],o=0;for(let s of a){let d=c$1.resolve(e,s);if(!C(e,d)){t.push(`Checkpoint path escapes workspace: ${s}`);continue}if(!await H(e,d)){t.push(`Checkpoint path resolves through a link outside the workspace: ${s}`);continue}let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()){t.push(`Checkpoint refuses symbolic link mutation: ${s}`);continue}if(i&&!i.isFile()){t.push(`Checkpoint target is not a regular file: ${s}`);continue}if(i&&i.size>aa){t.push(`Checkpoint file exceeds 5 MiB: ${s}`);continue}if(o+=i?.size??0,o>ma){t.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let g=i?await h.readFile(d):void 0;r.push({path:s,existed:!!i,beforeHash:g?$(g):null,...i?{mode:i.mode}:{}});}return {entries:r,errors:t}}function pa(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}async function Ca(e){let a=await h.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function Wa(e){return va.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function Ta(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;C(e,t);){if((await h.readdir(t).catch(()=>[])).some(Wa))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function qa(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!C(a,o))return false;let s=c$1.basename(o);return ya.has(s)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(s)})}function Na(e){let a=F(e.workspacePath,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 Da(e,a){let r=Pe(a.executable),[t="",o=""]=a.args;if(a.args.some(i=>/^(?:-e|--eval|-c|--command|-command)$/i.test(i)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let s=["npm","pnpm","yarn","bun"].includes(r);if(!(s&&e.kind==="audit"&&a.args.some(i=>/audit/i.test(i))||s&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(i=>/^(?:test|build|check|verify|package)$/i.test(i))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function Fa(e){let a=[],r=new Set,t=[],o=[],s=new Set,d=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let i of e.proposal.validation??[]){let g=c$1.resolve(e.workspacePath,i.cwd),n=F(e.workspacePath,g),f=await h.lstat(g).catch(()=>{});if(!f?.isDirectory()||f.isSymbolicLink()||!await H(e.workspacePath,g)){t.push(`Validation ${i.id} requires a real directory inside the workspace.`);continue}if(d&&!C(d,g)){t.push(`Validation ${i.id} escapes the declared project scope.`);continue}if(_[i.risk]>_[e.maxRisk]){t.push(`Validation ${i.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let k=v({workspacePath:e.workspacePath,projectPath:g,executable:i.executable,args:i.args,purpose:i.kind,timeoutMs:i.timeoutMs});try{qe(e.workspacePath,k,e.policy),Da(i,k);}catch(m){t.push(m instanceof Error?m.message:String(m));continue}a.push(y({id:`validation:${i.id}`,kind:i.kind,risk:i.risk,required:i.required,summary:i.summary,invocation:k})),s.add(`${n}:${i.kind}`);}for(let i of e.projectRoots){let g=Na({workspacePath:e.workspacePath,projectPath:i,proposal:e.proposal}),n=await ca({workspacePath:e.workspacePath,action:g},e.dependencies);o.push(...n.adapters);let f=qa(e.workspacePath,i,e.proposal.changes);if(f){for(let m of n.checkpointFiles)r.add(m);t.push(...n.blockers);}let k=F(e.workspacePath,i);for(let m of n.stages)!f&&!["test","build"].includes(m.kind)||s.has(`${k}:${m.kind}`)||a.push(m);}return {stages:[...new Map(a.map(i=>[i.id,i])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(i=>[`${i.projectPath}:${i.adapterId}`,i])).values()]}}async function Oa(e$1,a$2={}){let r=c$1.resolve(e$1.workspacePath),t=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),o=t.actions.filter(l=>l.cardId===e$1.cardId).filter(l=>!e$1.projectName||l.projectName===e$1.projectName).sort((l,E)=>l.order-E.order||l.id.localeCompare(E.id)),s=e$1.actionId?o.filter(l=>l.id===e$1.actionId):o,d$1=t.actions.filter(l=>!e$1.projectName||!l.projectName||l.projectName===e$1.projectName).sort((l,E)=>l.order-E.order||l.id.localeCompare(E.id)),i=new Map(d$1.map(l=>[l.id,l])),g=l=>{let E=new Set(l.map(se=>se.id)),V=[...l];for(;V.length>0;){let se=V.pop();for(let K of se?.dependsOn??[]){let Y=i.get(K);!Y||E.has(Y.id)||(E.add(Y.id),V.push(Y));}}return d$1.filter(se=>E.has(se.id))},n=s.filter(l=>l.findingStatus==="blocking"||l.notes.includes("Doctor finding status: blocking")),f=n.length>0?n:s.filter(l=>l.findingStatus!=="advisory"&&l.findingStatus!=="informational"),k=e$1.actionId?s.filter(l=>l.id===e$1.actionId):[],m=f[0],x=m?f.filter(l=>l.cardId===m.cardId&&l.findingId===m.findingId):[],I=g(e$1.actionId?k:x),W=e$1.maxRisk??"guarded",w={maxRisk:W,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},p=[{id:"workspace-root",status:await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:I.length>0?"passed":"failed",message:I.length>0?`${I.length} governed action(s) selected.`:"No governed remediation action matches this target."}],P=sa(I);P&&p.push(P);let b=[],T=[],S=[],j=[],O=new Set(["manual-repair","cancel"]);for(let l of I){let E=ye(l),V=Sa(r,l);if(_[l.risk]<=_[W]||(j.push(`${l.id} exceeds the approved ${W} risk ceiling.`),O.add(l.risk==="invasive"?"approve-invasive":"approve-guarded")),(l.status==="blocked"||l.status==="guidance-only")&&j.push(`${l.id} is ${l.status}: ${l.blocker}`),!E&&!V&&j.push(`${l.id} has no typed operation or structured invocation.`),V)try{qe(r,V,w);}catch(K){let Y=K instanceof Error?K.message:String(K);j.push(Y),/Force-based/.test(Y)&&O.add("allow-force"),/Breaking dependency/.test(Y)&&O.add("allow-breaking");}if(b.push({id:`action:${l.id}`,kind:"repair",status:E||V?"pending":"blocked",required:true,risk:l.risk,summary:l.summary,...V?{invocation:V}:{}}),l.transaction){let K=await ca({workspacePath:r,action:l},a$2);b.push(...K.stages),T.push(...K.checkpointFiles),j.push(...K.blockers),S.push(...K.adapters);}}let te=[...new Map(b.map(l=>[l.id,l])).values()];b.splice(0,b.length,...te),b.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.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.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),p.push(...await We({workspacePath:r,stages:b,toolAvailable:a$2.toolAvailable}));let M=await $a({workspacePath:r,actions:I,dependencyFiles:T}),B=await be(r,M);p.push({id:"rollback-coverage",status:I.some(l=>l.mode==="edit-file"||l.mode==="run-command")&&M.length===0?"failed":"passed",message:M.length>0?`${M.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),p.push({id:"structured-execution",status:b.some(l=>l.required&&l.status==="blocked")?"failed":"passed",message:"Every executable stage must use a typed operation or structured invocation."}),p.push({id:"checkpoint-boundary",status:B.errors.length===0?"passed":"failed",message:B.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":B.errors.join(" ")});let J=$(Q(t)),re=[...new Set(I.map(l=>l.projectPath).filter(Boolean))],L={cardId:e$1.cardId,scope:e$1.projectName||re.length===1?"project":"workspace",...e$1.projectName?{projectName:e$1.projectName}:{},...re.length===1?{projectPath:re[0]}:{},actionIds:I.map(l=>l.id)},de=D(a$2.now),ee=`repair_${randomUUID().replaceAll("-","")}`,z=p.some(l=>l.status==="failed")||j.length>0,ge=[...j,...p.filter(l=>l.status==="failed").map(l=>l.message)],u=[...new Map(S.map(l=>[`${l.projectPath}:${l.adapterId}`,l])).values()],q=ra({actions:I,adapters:u,preconditions:p,stages:b,decisionOptions:O,maxRisk:W,fallbackReasons:ge}),G={schemaVersion:c,transactionId:ee,revision:1,createdAt:de,updatedAt:de,workspace:{name:t.workspace.name,rootRef:"."},target:L,state:z?"decision-required":"awaiting-approval",policy:w,approval:{required:true,status:"pending"},preconditions:p,adapterEvaluations:u,checkpoint:{status:M.length>0?"pending":"unavailable",files:B.entries},stages:b,...z?{decision:{reason:[...new Set(ge)].join(" "),options:[...O],causes:q}}:{},events:[],integrity:{sourceEvidenceHash:J,planHash:Te({sourceEvidenceHash:J,target:L,policy:w,preconditions:p,adapterEvaluations:u,stages:b,checkpointFiles:B.entries})}};A(G,"planned",z?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$2.now}),a(G,e,"Workspace repair transaction");let oe=ae(r,ee);return await h.ensureDir(oe),await Z(Se(r,ee),t),await Z(ve(r,ee),G),await Z(c$1.join(r,d),G),G}async function _a(e$1,a$2={}){a(e$1.proposal,g,"Workspace repair proposal");let r=c$1.resolve(e$1.workspacePath),t=JSON.parse(JSON.stringify(e$1.proposal)),o=e$1.maxRisk??"guarded",s={maxRisk:o,allowForce:e$1.allowForce===true,allowBreaking:e$1.allowBreaking===true,autoRollback:e$1.autoRollback!==false,strictVerify:true},d$1=[],i=[],g$1=new Set(["manual-repair","cancel"]),n=await h.pathExists(c$1.join(r,".workspai-workspace"))||await h.pathExists(c$1.join(r,".workspai"));if(d$1.push({id:"workspace-root",status:n?"passed":"failed",message:n?"Canonical workspace root markers exist.":"Workspace root markers must exist."}),t.projectPath){t.projectPath=F(r,t.projectPath);let u=c$1.resolve(r,t.projectPath),q=await h.lstat(u).catch(()=>{});(!q?.isDirectory()||q.isSymbolicLink())&&i.push("The declared project path must be a real directory inside the workspace.");}t.validation=t.validation?.map(u=>({...u,cwd:F(r,u.cwd)}));let f=new Set,k=new Set,m=0;for(let u of t.changes){u.path=F(r,u.path),u.path==="."&&i.push(`${u.id} cannot replace the workspace root.`),f.has(u.id)&&i.push(`Duplicate proposal change id: ${u.id}.`),k.has(u.path)&&i.push(`Multiple proposal changes target ${u.path}.`),f.add(u.id),k.add(u.path),m+=Buffer.byteLength(u.content??"","utf8"),m>wa&&i.push("The model proposal exceeds the 25 MiB source-change limit.");let q=pa(u.path);if(q&&i.push(`${u.path}: ${q}`),_[u.risk]>_[o]&&(i.push(`${u.id} exceeds the approved ${o} risk ceiling.`),g$1.add(u.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let G=c$1.resolve(r,t.projectPath),oe=c$1.resolve(r,u.path);C(G,oe)||i.push(`${u.path} escapes the declared project scope.`);}}let x=[...k].sort(),I=await be(r,x);i.push(...I.errors);let W=new Map(I.entries.map(u=>[u.path,u]));for(let u of t.changes){let q=W.get(u.path);if(!q||q.beforeHash!==u.expectedBeforeHash){i.push(`${u.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}u.operation==="delete"&&!q.existed&&i.push(`${u.path} cannot be deleted because it does not exist.`),u.operation==="write"&&q.beforeHash!==null&&$(u.content??"")===q.beforeHash&&i.push(`${u.path} is a no-op and cannot prove source progress.`);}d$1.push({id:"proposal-boundary",status:i.length===0?"passed":"failed",message:i.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(i)].join(" ")});let w=new Set;if(t.projectPath)w.add(c$1.resolve(r,t.projectPath));else for(let u of t.changes)w.add(await Ta(r,u.path));let p=await Fa({workspacePath:r,proposal:t,projectRoots:[...w].sort(),maxRisk:o,policy:s,dependencies:a$2});i.push(...p.blockers);let P=p.stages,b=P.some(u=>u.status!=="skipped"&&["audit","test","build"].includes(u.kind));d$1.push({id:"validation-coverage",status:b?"passed":"unknown",message:b?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let T=[...new Set([...x,...p.checkpointFiles])].sort(),S=await be(r,T);i.push(...S.errors),d$1.push({id:"checkpoint-boundary",status:S.errors.length===0?"passed":"failed",message:S.errors.length===0?`${S.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:S.errors.join(" ")});let j=[{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(u=>({id:`proposal:${u.id}`,kind:"repair",status:_[u.risk]<=_[o]?"pending":"blocked",required:true,risk:u.risk,summary:u.summary,changedPaths:[u.path]})),...P,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];d$1.push(...await We({workspacePath:r,stages:j,toolAvailable:a$2.toolAvailable}));let O=new Set(j.map(u=>u.id));O.size!==j.length&&i.push("Repair proposal stage ids must be unique."),d$1.push({id:"stage-identity",status:O.size===j.length?"passed":"failed",message:O.size===j.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let u=await a$1({workspacePath:r,includeAbsolutePaths:false,ciMode:true});if(!t.targetActionIds?.length){let l=u.actions.filter(E=>E.cardId===t.cardId&&(!t.projectName||E.projectName===t.projectName)&&(!t.projectPath||E.projectPath===t.projectPath)).map(E=>E.id).sort();l.length>0&&(t.targetActionIds=l);}let q=new Set(t.targetActionIds??[]),G=u.actions.filter(l=>q.has(l.id)),oe=sa(G);oe&&d$1.push(oe);}catch{}let te=$(Q(t)),M={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(u=>`proposal:${u.id}`)},B=D(a$2.now),J=`repair_${randomUUID().replaceAll("-","")}`,L=d$1.some(u=>u.status==="failed")||i.length>0,de=[...i,...d$1.filter(u=>u.status==="failed").map(u=>u.message)],ee=ra({adapters:p.adapters,preconditions:d$1,stages:j,decisionOptions:g$1,maxRisk:o,fallbackReasons:de});for(let u of t.changes)_[u.risk]<=_[o]||ee.push({kind:"risk-approval",id:`risk:${u.id}`,message:`${u.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let z={schemaVersion:c,transactionId:J,revision:1,createdAt:B,updatedAt:B,workspace:{name:await Ca(r),rootRef:"."},target:M,state:L?"decision-required":"awaiting-approval",policy:s,approval:{required:true,status:"pending"},preconditions:d$1,adapterEvaluations:p.adapters,checkpoint:{status:"pending",files:S.entries},stages:j,...L?{decision:{reason:[...new Set(de)].join(" "),options:[...g$1],causes:ee}}:{},events:[],integrity:{sourceEvidenceHash:te,planHash:Te({sourceEvidenceHash:te,target:M,policy:s,preconditions:d$1,adapterEvaluations:p.adapters,stages:j,checkpointFiles:S.entries})}};A(z,"planned",L?"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$2.now}),a(z,e,"Workspace repair transaction");let ge=ae(r,J);return await h.ensureDir(ge),await Z(Se(r,J),t),await Z(ve(r,J),z),await Z(c$1.join(r,d),z),z}async function ht(e,a={}){let r=await ce(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(da(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=N("The compiled repair plan changed after planning.",["cancel"]),await R(e.workspacePath,r,a.now),r;let t=await Ce(e.workspacePath,e.transactionId);return $(Q(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=N("The persisted source plan changed after planning.",["cancel"]),await R(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:D(a.now),approvedBy:e.approvedBy?.trim()||"local-user",approvedPlanHash:r.integrity.planHash},r.state="approved",A(r,"approval","The immutable repair plan was explicitly approved.",{status:"approved",now:a.now}),await R(e.workspacePath,r,a.now),r)}async function la(e,a){let r=c$1.join(e,$e,ka);await h.ensureDir(c$1.dirname(r));try{let t=await h.stat(r),o=await h.readJson(r).catch(()=>({})),s=typeof o.host=="string"?o.host:void 0,d=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,i=false;if((!s||s===hostname())&&d)try{process.kill(d,0),i=true;}catch(n){i=n!==null&&typeof n=="object"&&"code"in n&&n.code==="EPERM";}let g=!!(s&&s!==hostname());!i&&!g&&Date.now()-t.mtimeMs>ba&&await h.remove(r);}catch{}try{await h.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
2
+ `,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await h.readJson(r).catch(async()=>{let o=await h.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await h.remove(r);}}async function ua(e){let a=await be(e.workspacePath,e.transaction.checkpoint.files.map(t=>t.path));if(a.errors.length>0)throw new Error(a.errors.join(" "));let r=new Map(a.entries.map(t=>[t.path,t]));for(let t of e.transaction.checkpoint.files){let o=r.get(t.path);if(!o||t.existed!==o.existed||t.beforeHash!==o.beforeHash||t.mode!==o.mode)throw new Error(`Checkpoint precondition changed after planning: ${t.path}. Create and approve a fresh plan.`)}}async function Ma(e){if(e.transaction.checkpoint.status==="captured")return;await ua(e);let a=c$1.join(ae(e.workspacePath,e.transaction.transactionId),Ue);await h.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=c$1.resolve(e.workspacePath,t.path),s=t.existed?await h.readFile(o):void 0;if(s&&$(s)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let d=`${Ue}/${String(r).padStart(4,"0")}.bin`;if(s){let i=c$1.join(ae(e.workspacePath,e.transaction.transactionId),d),g=`${i}.${process.pid}.${randomUUID()}.tmp`;await h.writeFile(g,s,{flag:"wx"});let n=await h.readFile(g);if($(n)!==t.beforeHash)throw await h.remove(g),new Error(`Checkpoint backup verification failed for ${t.path}.`);await h.move(g,i,{overwrite:true}),t.backupRef=d;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=D(e.now),e.transaction.state="checkpointed",A(e.transaction,"checkpoint",`Captured ${e.transaction.checkpoint.files.length} bounded file checkpoint(s).`,{status:"captured",now:e.now});}async function Ze(e,a){for(let r of a.checkpoint.files){let t=c$1.resolve(e,r.path),o=await h.readFile(t).catch(()=>{});r.afterHash=o?$(o):null;}}function Pe(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function qe(e,a,r){let t=c$1.resolve(e,a.cwd);if(!C(e,t))throw new Error(`Invocation cwd escapes workspace: ${a.cwd}`);if(a.args.length>100||a.args.some(i=>!i||/[\0\r\n]/.test(i)))throw new Error("Invocation contains invalid arguments.");let o=Pe(a.executable),s=c$1.isAbsolute(a.executable),d=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!C(e,a.executable))throw new Error(`Invocation executable escapes workspace: ${a.executable}`);if(!s&&!d&&!Pa.has(o))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(i=>/^(?:--force|-f)$/i.test(i)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(i=>/(?:breaking|legacy-peer-deps)/i.test(i)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(o)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${o} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:t,executable:a.executable}}async function Ee(e){let a=qe(e.workspacePath,e.invocation,e.policy),r=await h.lstat(a.cwd).catch(()=>{});if(!r?.isDirectory()||r.isSymbolicLink()||!await H(e.workspacePath,a.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(a.executable)||/^\.{1,2}[\\/]/.test(a.executable)){let s=c$1.isAbsolute(a.executable)?a.executable:c$1.resolve(a.cwd,a.executable);if(!await H(e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let t=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),o=await execa(a.executable,e.invocation.args,{cwd:a.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:ta,stdin:"ignore",extendEnv:false,env:{...t,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:o.exitCode??null,stdout:o.stdout??"",stderr:o.stderr??""}}function Ha(e){let a=b.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 Ba(e){let a=b.find(d=>d.cardId===e.transaction.target.cardId);if(!a)throw new Error(`No canonical producer is registered for repair card ${e.transaction.target.cardId}.`);let r=process.argv[1]?.trim();if(!r||!await h.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?c$1.resolve(e.workspacePath,e.transaction.target.projectPath):c$1.resolve(e.workspacePath);if(a.scope==="project"&&!e.transaction.target.projectPath)throw new Error(`Repair card ${a.cardId} requires an explicit project path for exact producer verification.`);if(!await H(e.workspacePath,t))throw new Error("The target producer working directory escapes the workspace boundary.");let o=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),s=await execa(process.execPath,[r,...Ha(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:ta,stdin:"ignore",extendEnv:false,env:{...o,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:s.exitCode??null,stdout:s.stdout??"",stderr:s.stderr??""}}async function La(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=we(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=we(e.sourcePlan)?a.actions.filter(s=>t?r.has(s.id):s.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||s.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||s.projectPath===e.transaction.target.projectPath)):a.actions.filter(s=>r.has(s.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(s=>s.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function Va(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(g=>!g.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$1({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(g=>g.id)),o=a.filter(g=>!t.has(g)),s=e.transaction.preconditions.map(g=>g.id).find(g=>g.startsWith(Ae))?.slice(Ae.length),d=r.actions.filter(g=>t.has(g.id)&&a.includes(g.id)),i=o.length===0&&!!s&&oa(d)!==s;return {current:o.length===0&&!i,missingActionIds:o,semanticDrift:i}}function U(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function Ka(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$2({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return m({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 Ja(e){let a=c$1.resolve(e.workspacePath,e.change.path);if(!C(e.workspacePath,a)||!await H(e.workspacePath,a))throw new Error(`Proposal target escaped the canonical workspace boundary: ${e.change.path}`);let r=pa(e.change.path);if(r)throw new Error(`${e.change.path}: ${r}`);let t=e.transaction.checkpoint.files.find(f=>f.path===e.change.path);if(!t)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let o=await h.readFile(a).catch(()=>{}),s=o?$(o):null;if(s!==t.beforeHash||s!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let d=await h.lstat(a).catch(()=>{});if(d?.isSymbolicLink()||d&&!d.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!d)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await h.remove(a);return}let i=e.change.content??"";if(Buffer.byteLength(i,"utf8")>aa)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await h.ensureDir(c$1.dirname(a));let g=c$1.join(c$1.dirname(a),`.${c$1.basename(a)}.${process.pid}.${randomUUID()}.repair-tmp`);await h.writeFile(g,i,{encoding:"utf8",flag:"wx"}),await h.move(g,a,{overwrite:true});let n=await h.readFile(a);if($(n)!==$(i))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function Qe(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=D(e.dependencies.now),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);try{if(e.stage.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:""}):Ba))({workspacePath:e.workspacePath,transaction:e.transaction});if(e.stage.exitCode=r.exitCode,e.stage.stdoutTail=U(r.stdout),e.stage.stderrTail=U(r.stderr),r.exitCode!==0&&r.exitCode!==2)throw new Error(r.stderr||r.stdout||`Exact card producer exited with ${String(r.exitCode)}.`);if(e.stage.id==="target-precondition"){let t=await Va({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!t.current){let o=t.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${t.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${o} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await Ja({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=ye(a.action);if(r){let t=he(e.workspacePath,a.action);if(!await H(e.workspacePath,t))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${t}`);await Ka(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Ee)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=U(t.stdout),e.stage.stderrTail=U(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??Ee)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=U(a.stdout),e.stage.stderrTail=U(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=D(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 Ze(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=D(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await Ze(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ue(e){let a=e.transaction.state==="rolling-back"||e.transaction.checkpoint.status==="restored";e.transaction.state="rolling-back",A(e.transaction,"rollback","Rollback started from the bounded transaction checkpoint.",{status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let r=async s=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=N(s,["manual-repair","cancel"]),A(e.transaction,"decision",s,{status:"conflicted",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false),t=[];for(let s of e.transaction.checkpoint.files){let d=c$1.resolve(e.workspacePath,s.path);if(!C(e.workspacePath,d)||!await H(e.workspacePath,d))return r(`Rollback refused because ${s.path} escaped the workspace boundary.`);let i=await h.lstat(d).catch(()=>{});if(i?.isSymbolicLink()||i&&!i.isFile())return r(`Rollback refused because ${s.path} is no longer a regular file.`);let g=i?await h.readFile(d):void 0,n=g?$(g):null,f=s.afterHash!==void 0&&n===s.afterHash,k=a&&n===s.beforeHash;if(!f&&!k)return r(`Rollback refused because ${s.path} changed outside this transaction.`);if(!s.existed){t.push({entry:s,absolute:d});continue}if(!s.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${s.path}.`);let m=c$1.join(ae(e.workspacePath,e.transaction.transactionId),s.backupRef),x=await h.lstat(m).catch(()=>{});if(!x?.isFile()||x.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${s.path}.`);let I=await h.readFile(m);if($(I)!==s.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${s.path}.`);t.push({entry:s,absolute:d,backup:I});}for(let s of t){if(!s.entry.existed){await h.remove(s.absolute);continue}let d=s.backup;if(d===void 0)throw new Error(`Validated checkpoint backup disappeared for ${s.entry.path}.`);let i=c$1.join(c$1.dirname(s.absolute),`.${c$1.basename(s.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await h.ensureDir(c$1.dirname(s.absolute)),await h.writeFile(i,d,{flag:"wx"}),s.entry.mode!==void 0&&await h.chmod(i,s.entry.mode),await h.move(i,s.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=D(e.dependencies.now);let o=e.transaction.stages.filter(s=>s.kind==="reconcile"&&s.invocation);for(let s of o){let d=s.invocation;if(!d)continue;let i=`rollback:${s.id}`,g=e.transaction.stages.find(k=>k.id===i&&k.kind==="rollback"),n=g??{id:i,kind:"rollback",status:"pending",required:true,risk:s.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:d};g||e.transaction.stages.push(n),n.status="running",n.startedAt=D(e.dependencies.now),delete n.completedAt,delete n.exitCode,delete n.stdoutTail,delete n.stderrTail,A(e.transaction,"rollback",n.summary,{stageId:n.id,status:"running",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now);let f;try{f=await(e.dependencies.runInvocation??Ee)({workspacePath:e.workspacePath,invocation:d,policy:e.transaction.policy});}catch(k){f={exitCode:null,stdout:"",stderr:k instanceof Error?k.message:String(k)};}if(n.exitCode=f.exitCode,n.stdoutTail=U(f.stdout),n.stderrTail=U(f.stderr),n.completedAt=D(e.dependencies.now),f.exitCode!==0)return n.status="failed",n.summary=f.stderr||f.stdout||`Rollback reconciliation exited with ${f.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=N(`Source files were restored, but the installed dependency tree could not be reconciled: ${n.summary}`,["manual-repair","cancel"]),A(e.transaction,"decision",e.transaction.decision.reason,{stageId:n.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),false;n.status="passed",n.summary="Installed dependency tree reconciled with the restored source state.",A(e.transaction,"rollback",n.summary,{stageId:n.id,status:"passed",now:e.dependencies.now});}return e.transaction.state="rolled-back",delete e.transaction.decision,A(e.transaction,"rollback","Rollback restored every bounded checkpoint file and reconciled dependency state.",{status:"passed",now:e.dependencies.now}),await R(e.workspacePath,e.transaction,e.dependencies.now),true}async function gt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await la(r,e.transactionId);try{let o=await ce({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(da(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=N("The compiled repair plan changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,o,a.now),o;let s=await Ce(r,e.transactionId);if($(Q(s))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=N("Persisted remediation evidence changed after approval. Create and approve a fresh transaction.",["cancel"]),A(o,"decision",o.decision.reason,{status:"integrity-failed",now:a.now}),await R(r,o,a.now),o;let i=(await We({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(w=>w.status==="failed");if(i){let w=o.stages.find(p=>p.invocation&&`tool:${p.invocation.cwd}:${p.invocation.executable}`===i.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=N(`${i.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:i.id,message:i.message,...w?{executable:w}:{}}),A(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await R(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 ue({workspacePath:r,transaction:o,dependencies:a}),o}let g=new Map(we(s)?s.changes.map(w=>[`proposal:${w.id}`,{kind:"proposal",change:w}]):s.actions.map(w=>[`action:${w.id}`,{kind:"canonical",action:w}]));try{await ua({workspacePath:r,transaction:o});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision=N(w instanceof Error?w.message:String(w),["cancel"]),A(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await R(r,o,a.now),o}let n=o.stages.find(w=>w.id==="target-precondition");if(!n)return o.approval.status="expired",o.state="decision-required",o.decision=N("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await R(r,o,a.now),o;if(!await Qe({workspacePath:r,transaction:o,stage:n,actions:g,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=N(`Target precondition failed before checkpoint: ${n.summary}`,["cancel"]),A(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await R(r,o,a.now),o;try{await Ma({workspacePath:r,transaction:o,now:a.now});}catch(w){return o.approval.status="expired",o.state="decision-required",o.decision=N(w instanceof Error?w.message:String(w),["cancel"]),A(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await R(r,o,a.now),o}o.state="executing",await R(r,o,a.now);for(let w of o.stages.filter(p=>p.id!=="target-precondition"&&p.id!=="canonical-verify"&&p.kind!=="rollback"))if(!await Qe({workspacePath:r,transaction:o,stage:w,actions:g,dependencies:a})&&w.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N(`Required stage ${w.id} failed: ${w.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let k=o.stages.find(w=>w.id==="canonical-verify");if(!k)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o;k.status="running",k.startedAt=D(a.now),A(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:k.id,status:"running",now:a.now}),await R(r,o,a.now);let m;try{m=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(w){m={status:"failed",exitCode:1,artifactPath:e$1.intelligenceRun},k.stderrTail=U(w instanceof Error?w.message:String(w));}let x=m.status==="passed"&&m.exitCode===0?"passed":m.status==="failed"||m.exitCode===1?"failed":"blocked",I=await La({workspacePath:r,transaction:o,sourcePlan:s,dependencies:a,workspaceStatus:x}),W=I.status==="passed"&&x!=="failed";return k.status=W?"passed":"failed",k.completedAt=D(a.now),k.exitCode=m.exitCode,k.summary=W&&x==="passed"?"Selected repair target and canonical workspace verification passed.":W?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":I.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${x}.`,o.verification={status:W?"passed":"failed",targetStatus:I.status,workspaceStatus:x,remainingActionIds:I.remainingActionIds,artifact:e$1.intelligenceRun,exitCode:m.exitCode,summary:k.summary},A(o,"verification",k.summary,{stageId:k.id,status:k.status,now:a.now}),W?(o.state="closed",delete o.decision,A(o,"closed",k.summary,{status:"passed",now:a.now}),await R(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=N(k.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await R(r,o,a.now),o.policy.autoRollback&&await ue({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function za(e,a={}){let r=c$1.resolve(e.workspacePath),t=await la(r,e.transactionId);try{let o=await ce({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 ue({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function ft(e,a={}){let r=await ce(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,A(r,"cancelled","Repair transaction cancelled before mutation.",{status:"cancelled",now:a.now}),await R(e.workspacePath,r,a.now),r}async function kt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await ce({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 za({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,A(t,"decision",e.decision==="manual-repair"?"The user chose manual repair; this transaction released source ownership without mutation.":"The user cancelled the decision-required transaction.",{status:e.decision,now:a.now}),await R(r,t,a.now),t}if(t.checkpoint.status==="captured")throw new Error("Repair policy cannot change after a checkpoint has been captured. Roll back first.");let o=await Ce(r,e.transactionId);t.state="cancelled",t.approval.status=t.approval.status==="approved"?"expired":t.approval.status,A(t,"decision",`The user selected ${e.decision}; a fresh immutable plan and approval are required.`,{status:"superseded",now:a.now}),await R(r,t,a.now);let s={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback};if(we(o))return _a({workspacePath:r,proposal:o,...s},a);let d=t.target.actionIds.map(i=>i.startsWith("action:")?i.slice(7):i);return Oa({workspacePath:r,cardId:t.target.cardId,...d.length===1?{actionId:d[0]}:{},projectName:t.target.projectName,...s},a)}async function mt(e){let a=c$1.join(e,$e,"transactions"),r=await h.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>ce({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,s)=>s.updatedAt.localeCompare(o.updatedAt))}export{ht as approveWorkspaceRepair,ft as cancelWorkspaceRepair,kt as decideWorkspaceRepair,Ha as exactCardProducerArgs,gt as executeWorkspaceRepair,ut as inspectWorkspaceRepairCapabilities,mt as listWorkspaceRepairTransactions,Oa as planWorkspaceRepair,_a as planWorkspaceRepairProposal,ce as readWorkspaceRepairTransaction,za as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as runWorkspaceStage}from'./chunk-WLCBXCZV.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-IZLEMTES.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-XVRJVKOX.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-XH7PDHBF.js';
@@ -1 +1 @@
1
- import {a}from'./chunk-FZCYTRBQ.js';import {f as f$1,r,l}from'./chunk-7AR5PDLD.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 (l(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 f$1({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$1){this.rebuild=r$1?.rebuild??(()=>r({...o})),this.now=r$1?.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};
1
+ import {a}from'./chunk-ESWFBSYM.js';import {f as f$1,r,l}from'./chunk-5ZA4JYOP.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 (l(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 f$1({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$1){this.rebuild=r$1?.rebuild??(()=>r({...o})),this.now=r$1?.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};