workspai 0.73.0 → 0.74.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 (102) hide show
  1. package/contracts/runtime-command-surface.v1.json +7 -3
  2. package/dist/analyze-IA33T6MY.js +1 -0
  3. package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-OVTQM7HN.js} +1 -1
  4. package/dist/autopilot-release-T327V7QK.js +1 -0
  5. package/dist/chunk-252EKOR6.js +2 -0
  6. package/dist/{chunk-3GO7BJ5J.js → chunk-4JJDDL3X.js} +1 -1
  7. package/dist/chunk-5EVBOUYW.js +3 -0
  8. package/dist/chunk-5Y4YRYZI.js +12 -0
  9. package/dist/{chunk-J44PN2FX.js → chunk-773WUMFU.js} +15 -15
  10. package/dist/{chunk-FRH7AIGY.js → chunk-BTJPTJLT.js} +2 -2
  11. package/dist/{chunk-OIGI7MP6.js → chunk-C43NXRRE.js} +1 -1
  12. package/dist/chunk-D6BL7ARI.js +2 -0
  13. package/dist/chunk-DLLHUG2Q.js +9 -0
  14. package/dist/chunk-DPC5DKH6.js +2 -0
  15. package/dist/{chunk-R5OJD5K2.js → chunk-DTLLIA2C.js} +1 -1
  16. package/dist/{chunk-LDJAUIAG.js → chunk-FYR4FD7K.js} +1 -1
  17. package/dist/chunk-G6ADWA2B.js +2 -0
  18. package/dist/chunk-H333GKL4.js +3 -0
  19. package/dist/{chunk-EDDGQ6LM.js → chunk-H5DRKXXC.js} +1 -1
  20. package/dist/{chunk-DNKELRK6.js → chunk-IQFXLJIM.js} +1 -1
  21. package/dist/{chunk-UCNIXOTL.js → chunk-IUOMBLRR.js} +1 -1
  22. package/dist/chunk-K3FXRBER.js +4 -0
  23. package/dist/{chunk-TIZCESKY.js → chunk-KCIET26G.js} +1 -1
  24. package/dist/chunk-LEEOZRWR.js +7 -0
  25. package/dist/{chunk-T5NBSCVX.js → chunk-NCZJUPG5.js} +49 -49
  26. package/dist/{chunk-TSYDTKXO.js → chunk-RPM67N7A.js} +1 -1
  27. package/dist/{chunk-NSMRQOWP.js → chunk-SAZXL36B.js} +1 -1
  28. package/dist/chunk-SVGUAVMG.js +1 -0
  29. package/dist/chunk-TBOIXIQA.js +1 -0
  30. package/dist/chunk-TGDXD4CD.js +1 -0
  31. package/dist/{chunk-IPZT6WKM.js → chunk-TVSMNF5G.js} +1 -1
  32. package/dist/{chunk-D3N2WFDV.js → chunk-UHT2SW7O.js} +1 -1
  33. package/dist/chunk-VLKX5U4H.js +13 -0
  34. package/dist/chunk-XF65LQ6M.js +1 -0
  35. package/dist/chunk-ZKYH44ER.js +1 -0
  36. package/dist/{chunk-TZK2R6RD.js → chunk-ZNKZ2KXR.js} +1 -1
  37. package/dist/chunk-ZS7JHATN.js +1 -0
  38. package/dist/{create-XYKXS3JB.js → create-EKA2QG5R.js} +1 -1
  39. package/dist/doctor-BXSNADVR.js +1 -0
  40. package/dist/{goal-lifecycle-BIX2JVNO.js → goal-lifecycle-XXWNMIAD.js} +1 -1
  41. package/dist/{goal-pack-SUWH6K7U.js → goal-pack-NTHYLISY.js} +1 -1
  42. package/dist/index.js +158 -158
  43. package/dist/pipeline-JLOC2SUT.js +5 -0
  44. package/dist/{project-agent-entry-Y3NEHZED.js → project-agent-entry-ZNUHGCVC.js} +1 -1
  45. package/dist/{project-intelligence-lens-6Q6XSUDJ.js → project-intelligence-lens-W72OUEDW.js} +1 -1
  46. package/dist/{proof-carrying-change-456TYEDW.js → proof-carrying-change-WLUPMUO7.js} +1 -1
  47. package/dist/verified-goal-6O2JZOOR.js +1 -0
  48. package/dist/{workspace-ROUEA3RT.js → workspace-XTIGVLGH.js} +1 -1
  49. package/dist/{workspace-agent-sync-6UYG33EQ.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
  50. package/dist/{workspace-context-H7ZXR6VI.js → workspace-context-Y3TNY2XZ.js} +1 -1
  51. package/dist/{workspace-contract-2V2BI6A3.js → workspace-contract-GRZY7WRD.js} +1 -1
  52. package/dist/{workspace-explain-IBMTRUSF.js → workspace-explain-KUYHJFLY.js} +1 -1
  53. package/dist/{workspace-foundation-H5B3TTZD.js → workspace-foundation-ZBUJTR56.js} +1 -1
  54. package/dist/{workspace-graph-stream-YDEET5LK.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
  55. package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
  56. package/dist/{workspace-intelligence-DXKQXTTM.js → workspace-intelligence-26YT6KMN.js} +1 -1
  57. package/dist/{workspace-intelligence-benchmark-L46EGZZM.js → workspace-intelligence-benchmark-QFVTUBDO.js} +1 -1
  58. package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
  59. package/dist/{workspace-intelligence-runner-SCB44IXU.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
  60. package/dist/{workspace-knowledge-graph-BNEVFEOW.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
  61. package/dist/{workspace-knowledge-graph-query-GOC365ZR.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
  62. package/dist/workspace-knowledge-graph-snapshot-JEJMRQZL.js +1 -0
  63. package/dist/workspace-marker-7U3NYRPJ.js +1 -0
  64. package/dist/{workspace-mcp-serve-JLZTTEVG.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
  65. package/dist/{workspace-model-XSNLDUI2.js → workspace-model-2ODVOWDQ.js} +1 -1
  66. package/dist/{workspace-onboarding-IRBVZTT4.js → workspace-onboarding-BY6RUBBH.js} +1 -1
  67. package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
  68. package/dist/{workspace-registry-summary-CBZDSG6I.js → workspace-registry-summary-VKTJ7PHV.js} +1 -1
  69. package/dist/workspace-repair-engine-RBM7NCGI.js +3 -0
  70. package/dist/workspace-run-JCA5WPCR.js +1 -0
  71. package/dist/{workspace-verify-QTRY7WW3.js → workspace-verify-NFJ7RKKT.js} +1 -1
  72. package/dist/{workspace-watch-PDQKYBYQ.js → workspace-watch-3DBBB6IP.js} +1 -1
  73. package/docs/ci-workflows.md +1 -1
  74. package/package.json +1 -1
  75. package/dist/analyze-WC2TY5AT.js +0 -1
  76. package/dist/autopilot-release-LJDRECFW.js +0 -1
  77. package/dist/chunk-2BCECNIW.js +0 -1
  78. package/dist/chunk-2LIVMG5C.js +0 -2
  79. package/dist/chunk-3SNP6M4M.js +0 -2
  80. package/dist/chunk-4HQU2GQM.js +0 -1
  81. package/dist/chunk-4JAURS76.js +0 -13
  82. package/dist/chunk-7O7P4MRD.js +0 -1
  83. package/dist/chunk-AQNU5RXV.js +0 -2
  84. package/dist/chunk-CQBM6BBP.js +0 -2
  85. package/dist/chunk-CY4QZ3PE.js +0 -3
  86. package/dist/chunk-F6CTGVJA.js +0 -9
  87. package/dist/chunk-K3O3HENC.js +0 -5
  88. package/dist/chunk-LGC4CRUF.js +0 -3
  89. package/dist/chunk-NNQE4DS2.js +0 -2
  90. package/dist/chunk-NSH7TTSV.js +0 -1
  91. package/dist/chunk-SO4CGS35.js +0 -4
  92. package/dist/chunk-UNXG3ZFV.js +0 -1
  93. package/dist/chunk-VBMWFT7Q.js +0 -1
  94. package/dist/chunk-ZZWGD3X3.js +0 -12
  95. package/dist/doctor-LQ7FT6AZ.js +0 -1
  96. package/dist/pipeline-NSPPWD7U.js +0 -5
  97. package/dist/verified-goal-GRH5UOJR.js +0 -1
  98. package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +0 -1
  99. package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +0 -1
  100. package/dist/workspace-marker-XGAWZZDX.js +0 -1
  101. package/dist/workspace-repair-engine-TDUNQSFJ.js +0 -3
  102. package/dist/workspace-run-I2W5PIPK.js +0 -1
@@ -0,0 +1,5 @@
1
+ import {c}from'./chunk-4JJDDL3X.js';import {c as c$1}from'./chunk-LPCWROQ3.js';import {a as a$3}from'./chunk-ZNKZ2KXR.js';import {g as g$1}from'./chunk-BTJPTJLT.js';import {a as a$2}from'./chunk-DLLHUG2Q.js';import {v}from'./chunk-NCZJUPG5.js';import {f,e}from'./chunk-XF65LQ6M.js';import {c as c$3}from'./chunk-X7FYEKLI.js';import {a}from'./chunk-MGL6DBOR.js';import {g,a as a$1,h}from'./chunk-FE5R6EUV.js';import {p,t,s}from'./chunk-ODK4LCEL.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$1(s,true),i=false;try{let{syncWorkspaceContract:t}=await import('./workspace-contract-GRZY7WRD.js');await t({workspacePath:s}),i=true;}catch{i=false;}return {sync:a,contractSynced:i}}async function U(s$1={}){let a$4=d.resolve(s$1.workspacePath??process.cwd()),i=a(a$4);if(!i)throw new Error("No Workspai workspace found in current directory or parents");let t$1=[],n=[],u=false,m,w,g$1,h$1=Date.now();try{let{sync:e,contractSynced:r}=await J(i),o=e.workspaceFound&&(e.added.length>0||e.skipped>=0)||e.workspaceFound?"pass":"warn";t$1.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$1.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=await v({workspace:true,json:true,quiet:true,strict:s$1.strict===true,ci:s$1.strict!==true}),r=L(e),o=await g(i,p.doctor)??a$1(i,p.doctor),l=await _(o);t$1.push({name:"doctor",status:r,durationMs:Date.now()-P,summary:r==="pass"?"doctor workspace passed":r==="warn"?"doctor workspace reported warnings":"doctor workspace did not pass",exitCode:e,evidencePath:o,policyProfile:l.policyProfile,blockers:l.blockers}),r==="fail"?n.push(...l.blockers.length>0?l.blockers.map(O=>`doctor: ${O}`):["doctor workspace gate failed"]):r==="warn"&&n.push("doctor workspace reported warnings");}catch(e){u=true,t$1.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$1.skipAnalyze)t$1.push({name:"analyze",status:"skipped",durationMs:0,summary:"analyze stage skipped"});else {let e=Date.now();try{let r=await a$2({workspacePath:i,json:true,strict:s$1.strict===true});m=d.isAbsolute(r.enterpriseControls.evidencePath)?r.enterpriseControls.evidencePath:d.join(i,r.enterpriseControls.evidencePath);let o=r.summary.verdict==="blocked"?"fail":r.summary.verdict==="needs-attention"?"warn":"pass";t$1.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$1.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,writeReport:true,skipVerify:s$1.skipVerify===true});w=e.evidencePath;let r=e.overallStatus==="pass"?"pass":e.overallStatus==="warn"?"warn":"fail";t$1.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$1.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$1.skipAutopilot)t$1.push({name:"autopilot",status:"skipped",durationMs:0,summary:"autopilot stage skipped"});else {let e=Date.now(),r=s$1.autopilotMode??"audit";try{let o=await c({workspacePath:i,mode:r,json:true,skipPipelineStages:true});g$1=o.artifacts.reportPath;let l=o.summary.verdict==="approved"?"pass":o.summary.verdict==="partial"?"warn":"fail";t$1.push({name:"autopilot",status:l,durationMs:Date.now()-e,summary:`autopilot ${r}: ${o.summary.verdict}`,exitCode:o.summary.exitCode,evidencePath:g$1}),l!=="pass"&&n.push(...o.blockingReasons.slice(0,5));}catch(o){u=true,t$1.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$1),S=V(t$1,u),I=d.join(i,t.pipelineLastRun),p$1={schemaVersion:s.pipelineLastRun.schemaVersion,generatedAt:new Date().toISOString(),workspacePath:i,summary:{verdict:N,exitCode:S,stagesPassed:t$1.filter(e=>e.status==="pass").length,stagesWarn:t$1.filter(e=>e.status==="warn").length,stagesFailed:t$1.filter(e=>e.status==="fail").length},stages:t$1,blockingReasons:[...new Set(n)],artifacts:{reportPath:I,analyzeEvidencePath:m,readinessEvidencePath:w,autopilotEvidencePath:g$1}};if(s$1.writeReport!==false){let e$1=f(p$1,{commandId:"workspacePipeline",exitCode:S,generatedAt:p$1.generatedAt,blockers:p$1.blockingReasons,runId:e()});await h(i,t.pipelineLastRun,e$1);}if(s$1.writeReport!==false&&s$1.noAgentSync!==true&&process.env.RAPIDKIT_NO_AGENT_SYNC!=="1"&&s$1.agentSync!==false)try{let{syncWorkspaceAgentGrounding:e}=await import('./workspace-agent-sync-TN6QDNBR.js'),r=await e({workspacePath:i,write:true,refreshContext:true,strict:false});p$1.agentGrounding={indexPath:r.indexPath,writtenFiles:r.writtenFiles,blockers:r.blockers};}catch{}return p$1}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{c as AGENT_BOOTSTRAP_RECEIPT_SCHEMA_VERSION,f as AGENT_ENTRY_HOST_IDS,g as PROJECT_AGENT_ADAPTER_ENTRY_FILES,b as PROJECT_AGENT_ENTRY_RELATIVE_PATH,a as PROJECT_AGENT_ENTRY_SCHEMA_VERSION,e as WORKSPAI_AGENT_ENTRY_END,d as WORKSPAI_AGENT_ENTRY_START,j as buildAgentBootstrapReceipt,i as buildProjectAgentEntryManifest,h as normalizeAgentEntryHost}from'./chunk-AQNU5RXV.js';
1
+ export{c as AGENT_BOOTSTRAP_RECEIPT_SCHEMA_VERSION,f as AGENT_ENTRY_HOST_IDS,g as PROJECT_AGENT_ADAPTER_ENTRY_FILES,b as PROJECT_AGENT_ENTRY_RELATIVE_PATH,a as PROJECT_AGENT_ENTRY_SCHEMA_VERSION,e as WORKSPAI_AGENT_ENTRY_END,d as WORKSPAI_AGENT_ENTRY_START,j as buildAgentBootstrapReceipt,i as buildProjectAgentEntryManifest,h as normalizeAgentEntryHost}from'./chunk-DPC5DKH6.js';
@@ -1 +1 @@
1
- export{b as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,c as PROJECT_GROUNDING_MODE_VALUES,g as PROJECT_PORTABLE_GROUNDING_SKILL_PATH,e as WORKSPAI_PROJECT_GROUNDING_END,d as WORKSPAI_PROJECT_GROUNDING_START,f as WORKSPAI_PROJECT_SKILL_MARKER,i as buildProjectContextAgent,j as resolveProjectPortableSkillTransactionPaths,m as resolveWorkspaceProjectLensTargets,h as selectBoundedProjectLensEntities,k as syncProjectIntelligenceLens,l as syncWorkspaceProjectLenses}from'./chunk-NSMRQOWP.js';
1
+ export{b as PROJECT_CONTEXT_AGENT_SCHEMA_VERSION,c as PROJECT_GROUNDING_MODE_VALUES,g as PROJECT_PORTABLE_GROUNDING_SKILL_PATH,e as WORKSPAI_PROJECT_GROUNDING_END,d as WORKSPAI_PROJECT_GROUNDING_START,f as WORKSPAI_PROJECT_SKILL_MARKER,i as buildProjectContextAgent,j as resolveProjectPortableSkillTransactionPaths,m as resolveWorkspaceProjectLensTargets,h as selectBoundedProjectLensEntities,k as syncProjectIntelligenceLens,l as syncWorkspaceProjectLenses}from'./chunk-SAZXL36B.js';
@@ -1 +1 @@
1
- export{l as abortProofCarryingChange,s as assertSealedProofCarryingChangeCurrent,d as authorizeProofCarryingChange,b as beginProofCarryingChange,a as createDeletedArtifactReference,r as decisionTransactionForCapsule,n as exportProofCarryingChangeCapsule,h as findUncoveredEffectArtifacts,j as inspectProofCarryingChange,k as listProofCarryingChanges,f as recordProofCarryingChangeEffect,c as recordProofCarryingChangePrediction,g as recordProofCarryingChangeVerification,e as resumeProofCarryingChange,p as validateEffectReceiptInput,o as validatePredictedArchitectureChangeInput,m as validateProofCarryingChangeCapsule,q as validateVerificationReceiptInput,i as verifyProofCarryingChange}from'./chunk-SO4CGS35.js';
1
+ export{l as abortProofCarryingChange,s as assertSealedProofCarryingChangeCurrent,d as authorizeProofCarryingChange,b as beginProofCarryingChange,a as createDeletedArtifactReference,r as decisionTransactionForCapsule,n as exportProofCarryingChangeCapsule,h as findUncoveredEffectArtifacts,j as inspectProofCarryingChange,k as listProofCarryingChanges,f as recordProofCarryingChangeEffect,c as recordProofCarryingChangePrediction,g as recordProofCarryingChangeVerification,e as resumeProofCarryingChange,p as validateEffectReceiptInput,o as validatePredictedArchitectureChangeInput,m as validateProofCarryingChangeCapsule,q as validateVerificationReceiptInput,i as verifyProofCarryingChange}from'./chunk-K3FXRBER.js';
@@ -0,0 +1 @@
1
+ import {b as b$1}from'./chunk-LEEOZRWR.js';import {d}from'./chunk-HAZGSAKP.js';import {c}from'./chunk-SVGUAVMG.js';import {a as a$1}from'./chunk-ZNKZ2KXR.js';import {q as q$2}from'./chunk-TGDXD4CD.js';import {a as a$2}from'./chunk-GR6442P7.js';import {h,g}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {b}from'./chunk-252EKOR6.js';import {p,q as q$1}from'./chunk-ODK4LCEL.js';import {createHash}from'crypto';import u from'path';import v from'fs-extra';var J="workspai.verified-goal.v1",A=q$1.verifiedGoalStatus,V=p.verifiedGoalStatus,H="contracts/workspace-intelligence/verified-goal.v1.json",$="contracts/workspace-intelligence/verified-goal-status.v1.json";function K(e,t,a){if(t.kind==="workspace")return true;let r=u.resolve(e,a.path);return t.kind==="project"?a.name===t.projectName||r===u.resolve(t.projectPath):t.projects.some(i=>i.projectName===a.name||u.resolve(i.projectPath)===r)}function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>`${JSON.stringify(t)}:${x(a)}`).join(",")}}`:JSON.stringify(e)}function z(e){return createHash("sha256").update(x(e)).digest("hex")}var re=["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"],se=new Set(re.map(e=>e.toLowerCase())),ne=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"]),O=1e5;function ie(e){return se.has(e.toLowerCase())||/\.(?:csproj|fsproj|vbproj)$/i.test(e)}async function oe(e){let t=[e],a=[],r=0;for(;t.length>0;){let i=t.shift();if(i===void 0)break;let o=await v.readdir(i,{withFileTypes:true});if(o.sort((n,s)=>n.name.localeCompare(s.name)),r+=o.length,r>O)throw new Error(`Dependency safety baseline exceeded ${O} filesystem entries under ${e}. Narrow the project boundary before creating this goal.`);for(let n of o){let s=u.join(i,n.name);if(n.isDirectory()){!ne.has(n.name.toLowerCase())&&!a$2(n.name)&&t.push(s);continue}n.isFile()&&ie(n.name)&&a.push(s);}}return a}function ce(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 U(e){try{let t=JSON.parse(e),a={};for(let r of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let i=t[r];if(!(!i||typeof i!="object"||Array.isArray(i)))for(let[o,n]of Object.entries(i))typeof n=="string"&&(a[`${r}:${o}`]=n);}return a}catch{return}}async function Y(e,t){let r=(await q$2({workspacePath:e,includeAbsolutePaths:true})).projects.filter(o=>K(e,t,o)),i=new Map;for(let o of r){let n=u.resolve(e,o.path),s=await oe(n);for(let c of s){let g=u.basename(c),f=await v.readFile(c,"utf8"),p=u.relative(e,c).split(u.sep).join("/");i.set(p,{path:p,ecosystem:ce(g),sha256:createHash("sha256").update(f).digest("hex"),...g==="package.json"?{dependencies:U(f)??{}}:{}});}}return {manifests:[...i.values()].sort((o,n)=>o.path.localeCompare(n.path))}}function B(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 le(e){let t=e.dependencySafetyBaseline;if(!t)return k({id:"change-policy",label:"Change safety policy",status:"missing",expected:"dependency manifest safety baseline",actual:"baseline unavailable"});let a=[],r=await Y(e.workspace.path,e.scope),i=new Map(r.manifests.map(s=>[s.path,s])),o=new Map(t.manifests.map(s=>[s.path,s])),n=new Set;for(let s of t.manifests){let c=i.get(s.path);(!c||c.sha256!==s.sha256)&&n.add(s.path);}for(let s of r.manifests)o.has(s.path)||n.add(s.path);for(let s of r.manifests)!o.has(s.path)&&!S(s.path)&&a.push(`${s.path} was added after the safety baseline`);for(let s of t.manifests){let c=i.get(s.path);if(!c){a.push(`${s.path} was removed`);continue}if(c.sha256===s.sha256)continue;if(s.dependencies){let p=await v.readFile(u.join(e.workspace.path,s.path),"utf8"),m=U(p);if(!m){a.push(`${s.path} is not valid dependency JSON`);continue}for(let[d,l]of Object.entries(s.dependencies)){let h=m[d];if(!h){a.push(`${d.replace(/^[^:]+:/,"")} was removed`);continue}if(h===l)continue;let G=B(l),R=B(h);(G===null||R===null||G!==R||/(?:latest|\*)/i.test(h))&&a.push(`${d.replace(/^[^:]+:/,"")} changed outside its proven major range (${l} \u2192 ${h})`);}continue}if(S(s.path))continue;let g=u.posix.dirname(s.path);[...i.values()].some(p=>{let m=u.posix.dirname(p.path);return p.ecosystem===s.ecosystem&&(m===g||g.startsWith(`${m}/`))&&S(p.path)&&n.has(p.path)})||a.push(`${s.path} changed without a matching reconciled ${s.ecosystem} lockfile`);}return k({id:"change-policy",label:"Change safety policy",status:a.length===0?"passed":"blocked",expected:"no force, removal, unbounded, or major dependency changes",actual:a.length===0?"manifest changes are within proven bounds":a.join("; ")})}function E(e,t){if(!/^[a-z0-9][a-z0-9._-]{7,95}$/i.test(t))throw new Error(`Invalid verified goal id: ${t}`);let a=u.join(e,".workspai","goals",t);return {directory:a,goal:u.join(a,"goal.json"),status:u.join(a,"status.json"),latestReport:u.join(e,V)}}function ue(e){return {workspacePath:u.resolve(e.workspace.path),kind:e.kind,scope:e.scope,target:e.criteria.kind==="test-coverage"?e.criteria.minimumPercent:null,...e.criteria.kind==="test-coverage"&&e.criteria.runtime?{runtime:e.criteria.runtime}:{},constraints:e.constraints}}async function C(e,t){await v.ensureDir(u.dirname(e));let a=`${e}.${process.pid}.${Date.now()}.tmp`;await v.writeJson(a,t,{spaces:2}),await v.rename(a,e);}async function de(e,t){let a=t?.trim();if(!a||a==="workspace")return {scope:{kind:"workspace"}};let r=a.startsWith("projects:")?"projects:":a.startsWith("project:")&&a.slice(8).includes(",")?"project:":null,i=a.startsWith("project:")?a.slice(8).trim():r?a.slice(r.length).trim():a;if(!i)throw new Error("Project goal scope must name a project.");let o=await q$2({workspacePath:e,includeAbsolutePaths:true});if(r){let g=i.split(",").map(p=>p.trim()).filter(Boolean);if(g.length<2||new Set(g).size!==g.length)throw new Error("A project-set goal scope must name at least two unique projects.");return {scope:{kind:"project-set",projects:g.map(p=>{let m=o.projects.filter(d=>d.name===p||d.path===p);if(m.length!==1)throw new Error(m.length===0?`Project goal scope was not found: ${p}`:`Project goal scope is ambiguous: ${p}`);return m[0]}).map(p=>({projectName:p.name,projectPath:u.resolve(e,p.path)})).sort((p,m)=>p.projectName.localeCompare(m.projectName))}}}let n=o.projects.filter(g=>{let f=u.resolve(e,g.path);return g.name===i||g.path===i||f===u.resolve(i)});if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found: ${i}`:`Project goal scope is ambiguous: ${i}`);let s=n[0],c=u.resolve(e,s.path);return {project:s,scope:{kind:"project",projectName:s.name,projectPath:c}}}function X(e,t,a){return e===null?"unavailable":a==="minimum"?e>=t?"satisfied":"unsatisfied":e<=t?"satisfied":"unsatisfied"}async function Q(e){if(!e)return null;try{let t=await v.readJson(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function pe(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 ge(e){let t=e.dependencyAudit;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}async function Z(e,t){let a=await g(e,p.doctor),r=await Q(a);if(!r)return {measuredAt:new Date().toISOString(),value:null,target:0,unit:"blocking-vulnerabilities",status:"unavailable",evidencePaths:[],message:"Fresh Doctor dependency evidence is not available."};let i=pe(r).filter(c=>{if(t.kind==="workspace")return true;let g=typeof c.name=="string"?c.name:typeof c.projectName=="string"?c.projectName:"",f=typeof c.path=="string"?u.resolve(c.path):typeof c.projectPath=="string"?u.resolve(c.projectPath):"";return t.kind==="project"?g===t.projectName||f===u.resolve(t.projectPath):t.projects.some(p=>p.projectName===g||u.resolve(p.projectPath)===f)}),o=i.map(ge).filter(c=>c!==null),n=o.map(c=>c.blockingFindingCount).filter(c=>Number.isInteger(c)&&Number(c)>=0),s=i.length>0&&n.length===i.length?n.reduce((c,g)=>c+g,0):null;return {measuredAt:(()=>{let c=o.map(g=>g.generatedAt).filter(g=>typeof g=="string").sort();return c[c.length-1]??new Date().toISOString()})(),value:s,target:0,unit:"blocking-vulnerabilities",status:X(s,0,"maximum"),evidencePaths:a?[a]:[],message:s===null?"Doctor did not publish complete dependency audit counts for the selected scope.":`${s} blocking dependency vulnerability finding(s) remain.`}}async function ee(e){let t=await a$1({startPath:e,writeReport:false}),a=t.gates.filter(i=>i.status==="pass").length,r=t.gates.length;return {measuredAt:t.generatedAt,value:a,target:r,unit:"gates",status:t.overallStatus==="pass"?"satisfied":"unsatisfied",evidencePaths:[...new Set(t.gates.map(i=>i.evidencePath).filter(i=>typeof i=="string"))],message:t.overallStatus==="pass"?"All release readiness gates pass.":`${r-a} release readiness gate(s) still require work.`}}async function q(e){let t=await d({projectPath:e.projectPath,target:e.target,run:e.run,runtime:e.runtime}),r=t.metrics[t.target.metric]?.percent??null;return {executionStatus:t.status,measurement:{measuredAt:t.generatedAt,value:r,target:e.target,unit:"percent",status:X(r,e.target,"minimum"),evidencePaths:[t.artifactPaths.project],message:t.status==="failed"?"The runtime-native coverage test command failed.":r===null?"Machine-readable coverage evidence is unavailable.":`${t.target.metric} coverage is ${r}% (target ${e.target}%).`}}}async function te(e){if(e.scope.kind==="project"){if(!e.scope.projectPath)throw new Error("Coverage goal project scope does not have a project path.");return q({projectPath:e.scope.projectPath,target:e.target,run:e.run,runtime:e.runtime})}let t=await q$2({workspacePath:e.workspacePath,includeAbsolutePaths:true});if(t.projects.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:"The workspace does not contain a registered project to measure."}};let a=t.projects.filter(l=>K(e.workspacePath,e.scope,l)),r=e.runtime,i=r?a.filter(l=>l.runtimeCandidates.includes(r)):a;if(i.length===0)return {executionStatus:"unavailable",measurement:{measuredAt:new Date().toISOString(),value:null,target:e.target,unit:"percent",status:"unavailable",evidencePaths:[],message:`The selected scope does not contain the ${e.runtime} coverage runtime.`}};let o=[];for(let l of i)o.push({projectName:l.name,result:await q({projectPath:u.resolve(e.workspacePath,l.path),target:e.target,run:e.run,runtime:e.runtime})});let n=o.filter(l=>l.result.executionStatus==="failed"),s=o.filter(l=>l.result.measurement.status==="unavailable"),c=o.filter(l=>l.result.measurement.status==="unsatisfied"),g=o.map(l=>l.result.measurement.value).filter(l=>l!==null),f=g.length===o.length&&g.length>0?Math.min(...g):null,p=n.length>0?"failed":s.length>0?"unavailable":c.length>0?"below-target":"passed",m=o.map(l=>l.result.measurement.measuredAt).sort(),d=[...n.map(l=>`${l.projectName}: coverage command failed`),...s.map(l=>`${l.projectName}: coverage unavailable`),...c.map(l=>`${l.projectName}: ${l.result.measurement.value??"unknown"}%`)];return {executionStatus:p,measurement:{measuredAt:m[m.length-1]??new Date().toISOString(),value:f,target:e.target,unit:"percent",status:p==="passed"?"satisfied":p==="below-target"?"unsatisfied":"unavailable",evidencePaths:[...new Set(o.flatMap(l=>l.result.measurement.evidencePaths))],message:p==="passed"?`Every registered project has at least ${e.target}% test coverage.`:`Workspace coverage is not verified: ${d.join("; ")}.`}}}function me(e){let t=e.scope.kind==="project"?`project ${e.scope.projectName??"selected project"}`:e.scope.kind==="project-set"?`projects ${e.scope.projects.map(a=>a.projectName).join(", ")}`:"workspace";return e.kind==="release-readiness"?`Prepare the ${t} for release.`:e.kind==="dependency-security"?`Resolve blocking dependency vulnerabilities in the ${t} without unsafe changes.`:`Raise ${e.runtime?`${e.runtime} `:""}${t} test coverage to ${e.target??80}% without breaking its build.`}function fe(e,t,a){return e==="release-readiness"?{kind:e,readiness:"pass",workspaceVerify:"ready"}:e==="dependency-security"?{kind:e,maximumBlockingVulnerabilities:0,requireFreshAudit:true}:{kind:e,metric:"auto",minimumPercent:t,...a?{runtime:a}:{}}}async function he(e){return e.kind==="release-readiness"?ee(e.workspacePath):e.kind==="dependency-security"?Z(e.workspacePath,e.scope):(await te({workspacePath:e.workspacePath,scope:e.scope,target:e.target,run:false,runtime:e.runtime})).measurement}async function Re(e){let t=u.resolve(e.workspacePath),a$1=Math.max(0,Math.min(100,Math.round(e.target??80))),{scope:r}=await de(t,e.scope),i={workspacePath:u.resolve(t),kind:e.kind,scope:r,target:e.kind==="test-coverage"?a$1:null,...e.kind==="test-coverage"&&e.runtime?{runtime:e.runtime}:{},constraints:{allowBreakingChanges:e.allowBreakingChanges===true,allowForce:e.allowForce===true,requireBuild:e.requireBuild!==false,requireTests:e.requireTests!==false}},o=z(i),n=`goal-${e.kind}-${o.slice(0,16)}`,s=E(t,n);if(await v.pathExists(s.goal)){let{goal:m,status:d}=await ae(t,n);if(m.fingerprint===o)return {goal:m,status:d,resumed:d.state!=="verified"}}let c=new Date().toISOString(),g=await he({workspacePath:t,kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),f={schemaVersion:J,id:n,fingerprint:o,createdAt:c,updatedAt:c,workspace:{name:await b(t),path:t},scope:r,kind:e.kind,summary:me({kind:e.kind,scope:r,target:a$1,runtime:e.runtime}),constraints:i.constraints,criteria:fe(e.kind,a$1,e.runtime),baseline:g,...e.kind==="dependency-security"?{dependencySafetyBaseline:await Y(t,r)}:{},artifactPaths:{goal:s.goal,status:s.status,latestReport:s.latestReport}},p={schemaVersion:A,goalId:n,goalFingerprint:o,workspacePath:t,updatedAt:c,state:"planned",attempt:0,progress:g,checks:[],blockingReasons:[],evidencePaths:g.evidencePaths,nextActions:e.kind==="test-coverage"?["Add focused tests for the lowest-coverage source paths.","Run verified goal checks."]:e.kind==="dependency-security"?["Inspect the fresh project dependency audit.","Apply only compatible non-force dependency repairs.","Reconcile the lockfile, test, build, and verify again."]:["Inspect the current remediation plan and failing release gates.","Repair the next causal blocker, then verify again."],artifactPath:s.status};return a(f,H,"Verified goal"),a(p,$,"Verified goal status"),await C(s.goal,f),await C(s.status,p),await h(t,V,p),{goal:f,status:p,resumed:false}}async function ae(e,t){let a$1=E(u.resolve(e),t),r=await v.readJson(a$1.goal),i=await v.readJson(a$1.status);a(r,H,"Verified goal"),a(i,$,"Verified goal status");let o=u.resolve(e),n=u.resolve(r.artifactPaths.goal)===u.resolve(a$1.goal)&&u.resolve(r.artifactPaths.status)===u.resolve(a$1.status)&&u.resolve(r.artifactPaths.latestReport)===u.resolve(a$1.latestReport);if(r.schemaVersion!==J||i.schemaVersion!==A||r.id!==i.goalId||r.fingerprint!==i.goalFingerprint||r.fingerprint!==z(ue(r))||u.resolve(r.workspace.path)!==o||u.resolve(i.workspacePath)!==o||!n)throw new Error(`Verified goal artifacts are inconsistent: ${t}`);return {goal:r,status:i}}function k(e){return {...e,message:e.message??`${e.label}: ${e.actual}; expected ${e.expected}.`}}async function L(e){let t=[],a=e.goal.scope.kind==="project"?[`project:${e.goal.scope.projectName}`]:e.goal.scope.kind==="project-set"?e.goal.scope.projects.map(r=>`project:${r.projectName}`):[void 0];for(let r of ["test","build"]){if(r==="test"&&e.includeTests===false)continue;if(!(r==="test"?e.goal.constraints.requireTests:e.goal.constraints.requireBuild)){t.push(k({id:r,label:`${r} validation`,status:"skipped",expected:"not required",actual:"skipped by goal contract"}));continue}if(!e.run){t.push(k({id:r,label:`${r} validation`,status:"missing",expected:"fresh passed evidence",actual:"execution disabled"}));continue}let o=false;for(let n of a){let s=await b$1({workspacePath:e.goal.workspace.path,stage:r,scope:n,parallel:false,continueOnError:false,strict:true,json:true,enforceGates:false}),c=n?.replace(/^project:/,"");if(t.push(k({id:c?`${r}:${c}`:r,label:c?`${r} validation \xB7 ${c}`:`${r} validation`,status:s.summary.exitCode===0?"passed":"failed",expected:"exit 0",actual:`exit ${s.summary.exitCode}`,evidencePath:u.join(e.goal.workspace.path,".workspai","reports","workspace-run-last.json")})),s.summary.exitCode!==0){o=true;break}}if(o)break}return t}async function Ne(e){let t=u.resolve(e.workspacePath),{goal:a$1,status:r}=await ae(t,e.goalId),i=e.run!==false,o=[],n;if(i&&e.runIntelligence!==false){let d=await c({workspacePath:t,strict:true,agent:"generic"}),l=d.exitCode===0||d.exitCode===2,h=a$1.kind==="release-readiness";o.push(k({id:"workspace-intelligence-chain",label:"Workspace Intelligence chain",status:d.exitCode===0||d.exitCode===2&&!h?"passed":d.exitCode===2?"blocked":"failed",expected:"passed",actual:d.exitCode===2&&l&&!h?`${d.status}; canonical evidence refreshed for goal-scoped verification`:d.status,evidencePath:u.join(t,p.intelligenceRun)}));}if(a$1.kind==="release-readiness"){n=await ee(t),o.push(k({id:"release-readiness",label:"Release readiness",status:n.status==="satisfied"?"passed":"blocked",expected:"all gates pass",actual:n.message,evidencePath:u.join(t,p.readiness)}));let d=await g(t,p.verify),l=await Q(d),h=l?.summary&&typeof l.summary=="object"&&!Array.isArray(l.summary)?String(l.summary.verdict??"missing"):"missing";o.push(k({id:"workspace-verify",label:"Workspace verification",status:h==="ready"?"passed":h==="missing"?"missing":"blocked",expected:"ready",actual:h,evidencePath:u.join(t,p.verify)}));}else if(a$1.kind==="dependency-security")n=await Z(t,a$1.scope),o.push(k({id:"dependency-audit",label:"Dependency security audit",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:"0 blocking vulnerabilities",actual:n.message,evidencePath:n.evidencePaths[0]})),o.push(a$1.constraints.allowBreakingChanges||a$1.constraints.allowForce?k({id:"change-policy",label:"Change safety policy",status:"blocked",expected:"breaking and force changes disabled",actual:`allowBreakingChanges=${a$1.constraints.allowBreakingChanges}, allowForce=${a$1.constraints.allowForce}`}):await le(a$1)),n.status==="satisfied"&&o.push(...await L({goal:a$1,run:i}));else {let d=a$1.criteria.kind==="test-coverage"?a$1.criteria.minimumPercent:a$1.baseline.target;if(d===null)throw new Error("Coverage goal does not have a valid target.");let l=await te({workspacePath:t,scope:a$1.scope,target:d,run:i,runtime:a$1.criteria.kind==="test-coverage"?a$1.criteria.runtime:void 0});n=l.measurement,o.push(k({id:"coverage",label:"Test coverage",status:n.status==="satisfied"?"passed":n.status==="unavailable"?"missing":"blocked",expected:`at least ${d}%`,actual:n.message,evidencePath:n.evidencePaths[0]})),o.push(k({id:"test",label:"Coverage test execution",status:l.executionStatus==="failed"?"failed":l.executionStatus==="unavailable"?"missing":"passed",expected:"runtime-native coverage test command completed",actual:l.executionStatus==="failed"?"coverage test command failed":l.executionStatus==="unavailable"?"coverage execution evidence unavailable":"coverage evidence produced by the test runner",evidencePath:n.evidencePaths[0]})),n.status==="satisfied"&&o.push(...await L({goal:a$1,run:i,includeTests:false}));}let s=o.filter(d=>d.status==="blocked"||d.status==="failed"||d.status==="missing").map(d=>d.message),c$1=[...new Set([...n.evidencePaths,...o.map(d=>d.evidencePath).filter(d=>typeof d=="string")])],g$1=n.status==="satisfied"&&o.every(d=>d.status==="passed"||d.status==="skipped"),f=E(t,a$1.id),p$1=g$1?[]:a$1.kind==="test-coverage"?["Inspect low-coverage files from the coverage artifact.","Add focused tests and verify again."]:a$1.kind==="dependency-security"?["Use fresh audit candidates and compatible package-manager repairs.","Reconcile lockfiles before running verified goal checks again."]:["Repair the first blocking readiness gate and verify the goal again."],m={schemaVersion:A,goalId:a$1.id,goalFingerprint:a$1.fingerprint,workspacePath:t,updatedAt:new Date().toISOString(),state:g$1?"verified":o.some(d=>d.status==="failed")?"failed":"blocked",attempt:r.attempt+1,progress:n,checks:o,blockingReasons:s,evidencePaths:c$1,nextActions:p$1,artifactPath:f.status};return a(m,$,"Verified goal status"),await C(f.status,m),await h(t,V,m),m}export{V as VERIFIED_GOAL_LAST_RUN_REPORT_PATH,J as VERIFIED_GOAL_SCHEMA_VERSION,A as VERIFIED_GOAL_STATUS_SCHEMA_VERSION,Re as planVerifiedGoal,ae as readVerifiedGoal,Ne 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-FRH7AIGY.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-BTJPTJLT.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-IPZT6WKM.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,L as LEGACY_COPILOT_GROUNDING_SKILL_PATH,x as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,N as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,m as LEGACY_CURSOR_GROUNDING_RULE_PATH,T as LEGACY_MCP_DESIGN_REPORT_PATH,V as LEGACY_VSCODE_AGENT_HOOKS_PATH,K as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,w as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,M as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,j as WORKSPAI_CURSOR_DIAGNOSE_RULE_PATH,i as WORKSPAI_CURSOR_EVIDENCE_RULE_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,l as WORKSPAI_CURSOR_RELEASE_RULE_PATH,k as WORKSPAI_CURSOR_REPAIR_RULE_PATH,S as WORKSPAI_MCP_DESIGN_REPORT_PATH,U as WORKSPAI_VSCODE_AGENT_HOOKS_PATH,n as WORKSPAI_WINDSURF_RULES_PATH}from'./chunk-QYEQVNBF.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-TVSMNF5G.js';export{f as AGENT_GROUNDING_DOC_PATH,g as LEGACY_AGENT_GROUNDING_DOC_PATH,L as LEGACY_COPILOT_GROUNDING_SKILL_PATH,x as LEGACY_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,N as LEGACY_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,m as LEGACY_CURSOR_GROUNDING_RULE_PATH,T as LEGACY_MCP_DESIGN_REPORT_PATH,V as LEGACY_VSCODE_AGENT_HOOKS_PATH,K as WORKSPAI_COPILOT_GROUNDING_SKILL_PATH,w as WORKSPAI_COPILOT_WORKSPACE_INSTRUCTIONS_PATH,M as WORKSPAI_COPILOT_WORKSPACE_INTELLIGENCE_SKILL_PATH,j as WORKSPAI_CURSOR_DIAGNOSE_RULE_PATH,i as WORKSPAI_CURSOR_EVIDENCE_RULE_PATH,h as WORKSPAI_CURSOR_GROUNDING_RULE_PATH,l as WORKSPAI_CURSOR_RELEASE_RULE_PATH,k as WORKSPAI_CURSOR_REPAIR_RULE_PATH,S as WORKSPAI_MCP_DESIGN_REPORT_PATH,U as WORKSPAI_VSCODE_AGENT_HOOKS_PATH,n as WORKSPAI_WINDSURF_RULES_PATH}from'./chunk-QYEQVNBF.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-UCNIXOTL.js';
1
+ export{b as WORKSPACE_CONTEXT_AGENT_REPORT_PATH,a as WORKSPACE_CONTEXT_SCHEMA_VERSION,c as buildWorkspaceAgentContext,d as writeWorkspaceAgentContext}from'./chunk-IUOMBLRR.js';
@@ -1 +1 @@
1
- export{g as WORKSPACE_CONTRACT_PATH,i as WORKSPACE_CONTRACT_SCHEMA_VERSION,h as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,j as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,k as WorkspaceContractVerificationError,m as buildWorkspaceContract,q as buildWorkspaceContractGraph,l as discoverProjectJsonFiles,p as readWorkspaceContract,o as syncWorkspaceContract,r as verifyWorkspaceContract,n as writeWorkspaceContract,s as writeWorkspaceContractVerifyEvidence}from'./chunk-NNQE4DS2.js';
1
+ export{g as WORKSPACE_CONTRACT_PATH,i as WORKSPACE_CONTRACT_SCHEMA_VERSION,h as WORKSPACE_CONTRACT_VERIFY_REPORT_PATH,j as WORKSPACE_CONTRACT_VERIFY_SCHEMA_VERSION,k as WorkspaceContractVerificationError,m as buildWorkspaceContract,q as buildWorkspaceContractGraph,l as discoverProjectJsonFiles,p as readWorkspaceContract,o as syncWorkspaceContract,r as verifyWorkspaceContract,n as writeWorkspaceContract,s as writeWorkspaceContractVerifyEvidence}from'./chunk-G6ADWA2B.js';
@@ -1 +1 @@
1
- export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-4JAURS76.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-QYEQVNBF.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-3SNP6M4M.js';
1
+ export{b as buildWorkspaceExplain,a as resolveWorkspaceExplainArtifactPath,c as writeWorkspaceExplainReport}from'./chunk-VLKX5U4H.js';export{c as WORKSPACE_EXPLAIN_REPORT_PATH,e as WORKSPACE_TRACE_REPORT_PATH,d as WORKSPACE_WHY_REPORT_PATH}from'./chunk-QYEQVNBF.js';export{e as WORKSPACE_MODEL_DIFF_REPORT_PATH}from'./chunk-D6BL7ARI.js';
@@ -1 +1 @@
1
- import {c as c$1}from'./chunk-J44PN2FX.js';import {a}from'./chunk-2LIVMG5C.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await c$1(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-CBZDSG6I.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
1
+ import {c as c$1}from'./chunk-773WUMFU.js';import {a}from'./chunk-252EKOR6.js';import c from'path';import u from'fs-extra';async function W(t,r){let o=await a(t),d=o?.name||c.basename(t),n,i=c.join(t,".python-version");if(await u.pathExists(i)){let a=(await u.readFile(i,"utf-8")).trim();a&&(n=a);}let e=r?.profile||"polyglot",m=e==="python-only"||e==="polyglot"||e==="enterprise",f=r?.installMethod||o?.metadata?.npm?.installMethod||(m?"poetry":"venv"),s=await c$1(t,{workspaceName:d,installMethod:f,pythonVersion:n,profile:e,writeMarker:true,writeGitignore:true,onlyIfMissing:!r?.force}),{publishWorkspaceRegistrySummary:y}=await import('./workspace-registry-summary-VKTJ7PHV.js');return await y(t),{workspacePath:t,created:s,status:s.length>0?"passed":"skipped"}}export{W as ensureWorkspaceFoundation};
@@ -1 +1 @@
1
- import {b}from'./chunk-ZZWGD3X3.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c}from'./chunk-EWZZUQBR.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c({...o,generatedAt:"<ignored>",proofs:o.proofs.map(s=>({...s,observedAt:"<ignored>"}))})}function f(o){return "observedAt"in o?{...o,observedAt:"<ignored>"}:o}function u(o,s){let e=new Map(o.map(r=>[r.id,r])),a=new Map(s.map(r=>[r.id,r])),i=s.filter(r=>!e.has(r.id)),p=s.filter(r=>{let t=e.get(r.id);return t?c(f(t))!==c(f(r)):false}),d=o.filter(r=>!a.has(r.id)).map(r=>r.id);return {added:i,updated:p,removed:d}}function E(o,s){let e=new Map(o.map(a=>[a.id,a]));return s.filter(a=>{let i=e.get(a.id);return !i||c(i)!==c(a)})}function I(o){return a(o,"contracts/workspace-intelligence/workspace-graph-stream.v1.json","Workspace graph stream event"),o}var R=class{previous=null;revision=0;generation=0;workspaceId;sessionId;now;nextCorrelationId;constructor(s){this.workspaceId=`workspace:${g.createHash("sha256").update(H.resolve(s.workspacePath)).digest("hex")}`,this.sessionId=s.sessionId??g.randomUUID(),this.now=s.now??(()=>new Date),this.nextCorrelationId=s.correlationId??(()=>g.randomUUID());}publish(s,e){b(e,s);let a=this.now().toISOString(),i=d(s),p=w(e),d$1=this.nextCorrelationId(),r={schemaVersion:M,workspaceId:this.workspaceId,sessionId:this.sessionId,generation:this.generation,modelHash:i,graphHash:p,generatedAt:a,causationId:d$1,correlationId:d$1};if(!this.previous){let S=I({...r,type:"graph.snapshot",revision:this.revision,payload:{graph:e,reason:"initial"}});return this.previous=e,S}let t=this.previous,W=this.revision,b$1=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$1=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c(t.quality)!==c(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b$1,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$1.added,entitiesUpdated:c$1.updated,entitiesRemoved:c$1.removed,relationsAdded:h.added,relationsUpdated:h.updated,relationsRemoved:h.removed,proofsAdded:l.added,proofsUpdated:l.updated,proofsRemoved:l.removed,providersUpdated:E(t.providers,e.providers),quality:G?e.quality:null,diagnostics:e.diagnostics}});return this.previous=e,A}};export{M as WORKSPACE_GRAPH_STREAM_SCHEMA_VERSION,R as WorkspaceGraphStreamPublisher};
1
+ import {b}from'./chunk-5Y4YRYZI.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c}from'./chunk-EWZZUQBR.js';import g from'crypto';import H from'path';var M="workspace-graph-stream.v1";function w(o){return c({...o,generatedAt:"<ignored>",proofs:o.proofs.map(s=>({...s,observedAt:"<ignored>"}))})}function f(o){return "observedAt"in o?{...o,observedAt:"<ignored>"}:o}function u(o,s){let e=new Map(o.map(r=>[r.id,r])),a=new Map(s.map(r=>[r.id,r])),i=s.filter(r=>!e.has(r.id)),p=s.filter(r=>{let t=e.get(r.id);return t?c(f(t))!==c(f(r)):false}),d=o.filter(r=>!a.has(r.id)).map(r=>r.id);return {added:i,updated:p,removed:d}}function E(o,s){let e=new Map(o.map(a=>[a.id,a]));return s.filter(a=>{let i=e.get(a.id);return !i||c(i)!==c(a)})}function I(o){return a(o,"contracts/workspace-intelligence/workspace-graph-stream.v1.json","Workspace graph stream event"),o}var R=class{previous=null;revision=0;generation=0;workspaceId;sessionId;now;nextCorrelationId;constructor(s){this.workspaceId=`workspace:${g.createHash("sha256").update(H.resolve(s.workspacePath)).digest("hex")}`,this.sessionId=s.sessionId??g.randomUUID(),this.now=s.now??(()=>new Date),this.nextCorrelationId=s.correlationId??(()=>g.randomUUID());}publish(s,e){b(e,s);let a=this.now().toISOString(),i=d(s),p=w(e),d$1=this.nextCorrelationId(),r={schemaVersion:M,workspaceId:this.workspaceId,sessionId:this.sessionId,generation:this.generation,modelHash:i,graphHash:p,generatedAt:a,causationId:d$1,correlationId:d$1};if(!this.previous){let S=I({...r,type:"graph.snapshot",revision:this.revision,payload:{graph:e,reason:"initial"}});return this.previous=e,S}let t=this.previous,W=this.revision,b$1=t.source.hash,y=w(t);this.revision+=1,this.generation+=1;let c$1=u(t.entities,e.entities),h=u(t.relations,e.relations),l=u(t.proofs,e.proofs),G=c(t.quality)!==c(e.quality),A=I({...r,generation:this.generation,type:"graph.delta",baseRevision:W,baseModelHash:b$1,baseGraphHash:y,revision:this.revision,payload:{entitiesAdded:c$1.added,entitiesUpdated:c$1.updated,entitiesRemoved:c$1.removed,relationsAdded:h.added,relationsUpdated:h.updated,relationsRemoved:h.removed,proofsAdded:l.added,proofsUpdated:l.updated,proofsRemoved:l.removed,providersUpdated:E(t.providers,e.providers),quality:G?e.quality:null,diagnostics:e.diagnostics}});return this.previous=e,A}};export{M as WORKSPACE_GRAPH_STREAM_SCHEMA_VERSION,R as WorkspaceGraphStreamPublisher};
@@ -0,0 +1 @@
1
+ export{a as WORKSPACE_GRAPH_TOKEN_EFFICIENCY_SCHEMA_VERSION,b as buildWorkspaceGraphTokenEfficiencyReport}from'./chunk-RPM67N7A.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-3SNP6M4M.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-D6BL7ARI.js';export{d as hashWorkspaceModel}from'./chunk-EWZZUQBR.js';
@@ -1 +1 @@
1
- export{c as WORKSPACE_INTELLIGENCE_BENCHMARK_CONTRACT_PATH,b as WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH,a as WORKSPACE_INTELLIGENCE_BENCHMARK_SCHEMA_VERSION,d as WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES,g as buildWorkspaceIntelligenceBenchmark,e as classifyWorkspaceEvaluationProvenance,f as trustedMeasuredEvaluationReduction,h as writeWorkspaceIntelligenceBenchmark}from'./chunk-OIGI7MP6.js';
1
+ export{c as WORKSPACE_INTELLIGENCE_BENCHMARK_CONTRACT_PATH,b as WORKSPACE_INTELLIGENCE_BENCHMARK_REPORT_PATH,a as WORKSPACE_INTELLIGENCE_BENCHMARK_SCHEMA_VERSION,d as WORKSPACE_INTELLIGENCE_BENCHMARK_SUITES,g as buildWorkspaceIntelligenceBenchmark,e as classifyWorkspaceEvaluationProvenance,f as trustedMeasuredEvaluationReduction,h as writeWorkspaceIntelligenceBenchmark}from'./chunk-C43NXRRE.js';
@@ -1 +1 @@
1
- export{e as WORKSPACE_EVALUATION_LAST_RUN_PATH,d as WORKSPACE_EVALUATION_LIVE_PATH,k as appendWorkspaceEvaluationEvent,n as assertWorkspaceEvaluationSourceTaxonomy,m as compareWorkspaceEvaluations,h as createWorkspaceEvaluation,l as finalizeWorkspaceEvaluation,g as normalizeWorkspaceEvaluationEvent,j as readWorkspaceEvaluation,f as summarizeWorkspaceEvaluation,i as writeWorkspaceEvaluation}from'./chunk-UNXG3ZFV.js';
1
+ export{e as WORKSPACE_EVALUATION_LAST_RUN_PATH,d as WORKSPACE_EVALUATION_LIVE_PATH,k as appendWorkspaceEvaluationEvent,n as assertWorkspaceEvaluationSourceTaxonomy,m as compareWorkspaceEvaluations,h as createWorkspaceEvaluation,l as finalizeWorkspaceEvaluation,g as normalizeWorkspaceEvaluationEvent,j as readWorkspaceEvaluation,f as summarizeWorkspaceEvaluation,i as writeWorkspaceEvaluation}from'./chunk-ZS7JHATN.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-2BCECNIW.js';
1
+ export{a as WORKSPACE_INTELLIGENCE_RUN_REPORT_PATH,b as WORKSPACE_INTELLIGENCE_RUN_SCHEMA_VERSION,c as runWorkspaceIntelligenceChain}from'./chunk-SVGUAVMG.js';
@@ -1 +1 @@
1
- export{a as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,b as assertWorkspaceKnowledgeGraphSourceBinding,e as buildWorkspaceKnowledgeGraph,c as computeWorkspaceKnowledgeGraphInputFingerprint,f as knowledgeEntityId,d as workspaceKnowledgeGraphInputsMatchLiveState}from'./chunk-ZZWGD3X3.js';
1
+ export{a as WORKSPACE_KNOWLEDGE_GRAPH_REPORT_PATH,b as assertWorkspaceKnowledgeGraphSourceBinding,e as buildWorkspaceKnowledgeGraph,c as computeWorkspaceKnowledgeGraphInputFingerprint,f as knowledgeEntityId,d as workspaceKnowledgeGraphInputsMatchLiveState}from'./chunk-5Y4YRYZI.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-7O7P4MRD.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-ZKYH44ER.js';
@@ -0,0 +1 @@
1
+ export{a as readWorkspaceKnowledgeGraphSnapshot}from'./chunk-UHT2SW7O.js';
@@ -0,0 +1 @@
1
+ export{e as createNpmWorkspaceMarker,f as isValidWorkspaceMarker,a as readWorkspaceMarker,b as resolveWorkspaceRegistrationName,d as updateWorkspaceMetadata,c as writeWorkspaceMarker}from'./chunk-252EKOR6.js';
@@ -1,3 +1,3 @@
1
- import {m,j,k}from'./chunk-SO4CGS35.js';import {d,c as c$2,f as f$1,e as e$1}from'./chunk-7O7P4MRD.js';import {b}from'./chunk-4JAURS76.js';import {c as c$1,e}from'./chunk-IVYPC36J.js';import {c as c$3,b as b$3}from'./chunk-QYEQVNBF.js';import {b as b$2}from'./chunk-UCNIXOTL.js';import {d as d$1}from'./chunk-R5OJD5K2.js';import {b as b$1}from'./chunk-ZZWGD3X3.js';import {l}from'./chunk-4HQU2GQM.js';import {h}from'./chunk-NNQE4DS2.js';import {g as g$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {p,r}from'./chunk-ODK4LCEL.js';import {w as w$1}from'./chunk-VQZ5PI5J.js';import y from'path';import z from'readline';import w from'fs-extra';var B=p.agentIndex,X=new Map(Object.keys(p).flatMap(e=>{let t=r[e];return t?[[p[e],t]]:[]}));function Y(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 Z={type:"object",properties:{data:true,error:{type:"object",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:false}},oneOf:[{required:["data"]},{required:["error"]}],additionalProperties:false},Q={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},V=[{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>"}}}},{name:"listProofCarryingChanges",description:"List proof-carrying changes with lifecycle, assurance, blockers, and integrity state",inputSchema:{type:"object",properties:{}}},{name:"getProofCarryingChange",description:"Read the ledger-derived state and architecture-aware assurance capsule for one change",inputSchema:{type:"object",properties:{changeId:{type:"string",description:"Canonical proof-carrying change id"}},required:["changeId"]}},{name:"validateProofCarryingChange",description:"Replay and validate one proof-carrying capsule and all hash-bound evidence references",inputSchema:{type:"object",properties:{changeId:{type:"string",description:"Canonical proof-carrying change id"}},required:["changeId"]}}].map(e=>({...e,title:e.name.replace(/([a-z])([A-Z])/g,"$1 $2"),inputSchema:{...e.inputSchema,additionalProperties:false},outputSchema:Z,annotations:Q}));function ee(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!y.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function c(e,t){if(!ee(t))throw new Error(`Unsafe artifact path: ${t}`);let n=await g$1(e,t)??y.join(e,t);if(!await w.pathExists(n))return null;let r=await w.readJson(n),o=w$1(t),p$1=X.get(o);if(p$1&&a(r,p$1,`MCP artifact ${o}`),o===p.knowledgeGraph){let a=y.join(e,l);if(!await w.pathExists(a))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let u=await w.readJson(a);b$1(r,u);}return r}async function te(e$1){let t=[],n=new Set,o=((await c(e$1,d$1))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$1,reasons:o});for(let i of o)n.add(i);}let p=await c(e$1,c$3);if(e(p)){let i=(p.blockingReasons??[]).filter(l=>typeof l=="string"&&l.trim().length>0);if(i.length>0){t.push({artifact:c$3,reasons:i});for(let l of i)n.add(l);}}let a=await c(e$1,h),u=(a?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(u.length>0||String(a?.status??"").toLowerCase()==="failed"){let i=u.length>0?u:["Workspace contract verification failed"];t.push({artifact:h,reasons:i});for(let l of i)n.add(l);}return {blockingReasons:[...n],sources:t}}async function D(e$2,t,n){switch(t){case "getWorkspaceModel":return c(e$2,l);case "getWorkspaceKnowledgeGraph":return c(e$2,p.knowledgeGraph);case "getWorkspaceEvaluation":return c(e$2,n.live===true?p.evaluationLive:p.evaluationLastRun);case "queryWorkspaceEntities":{let r=await c(e$2,p.knowledgeGraph);if(!r)return null;let o=String(n.kind??"").trim();return {schemaVersion:r.schemaVersion,generatedAt:r.generatedAt,entities:e$1(r,o||void 0)}}case "searchWorkspaceGraph":{let r=await c(e$2,p.knowledgeGraph);if(!r)return null;let o=typeof n.limit=="number"?n.limit:Number(n.limit??12);return f$1(r,{query:String(n.query??""),...typeof n.kind=="string"&&n.kind.trim()?{kind:n.kind.trim()}:{},...typeof n.projectId=="string"&&n.projectId.trim()?{projectId:n.projectId.trim()}:{},limit:Number.isFinite(o)?o:12,projection:"agent"})}case "getWorkspaceGraphEvidence":{let r=await c(e$2,p.knowledgeGraph);return r?c$2(r,String(n.query??"")):null}case "findWorkspaceGraphPath":{let r=await c(e$2,p.knowledgeGraph);return r?d(r,String(n.from??""),String(n.to??"")):null}case "getEvidenceIndex":return c(e$2,B);case "getBlockers":return te(e$2);case "getSafeCommands":return {safeCommands:(await c(e$2,b$2))?.safeCommands??[]};case "getProjectContext":{let r=await c(e$2,b$2);if(!r)return null;let o=String(n.project??"").trim(),p=r.scope?.activeProject??void 0,a=o||p,u=Array.isArray(r.projects)?r.projects:[],i=a&&u.find(l=>typeof l.name=="string"&&l.name.toLowerCase()===a.toLowerCase());return {workspace:r.workspace??null,scope:r.scope??null,validation:r.validation??null,project:i??null,safeCommands:r.safeCommands??[]}}case "getArtifact":{let r=String(n.relativePath??"").trim();return c(e$2,r)}case "listOperationalSkills":return c(e$2,b$3);case "getWorkspaceExplain":{let r=String(n.target??"release-blocked").trim(),o=c$1(r);if(!o)throw new Error(`Invalid explain target: ${r}`);let p=await c(e$2,c$3);return e(p)&&Y(p.target,o)?p:b({workspacePath:e$2,target:o})}case "listProofCarryingChanges":return k({workspacePath:e$2});case "getProofCarryingChange":return j({workspacePath:e$2,changeId:String(n.changeId??"").trim(),operation:"status"});case "validateProofCarryingChange":return m({workspacePath:e$2,changeId:String(n.changeId??"").trim()});default:throw new Error(`Unknown tool: ${t}`)}}var J="2026-07-28",F=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],U={name:"workspai-workspace-mcp",version:"1.0.0"};function ne(e){let t=e.params?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t["io.modelcontextprotocol/protocolVersion"];return typeof n=="string"?n:void 0}function re(e,t){return !t||!e||typeof e!="object"||Array.isArray(e)?e:{...e,_meta:{...e._meta??{},"io.modelcontextprotocol/serverInfo":U}}}function g(e,t,n=false){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:re(t,n)})}
1
+ import {m,j,k}from'./chunk-K3FXRBER.js';import {d,c as c$2,f as f$1,e as e$1}from'./chunk-ZKYH44ER.js';import {b}from'./chunk-VLKX5U4H.js';import {c as c$1,e}from'./chunk-IVYPC36J.js';import {c as c$3,b as b$3}from'./chunk-QYEQVNBF.js';import {b as b$2}from'./chunk-IUOMBLRR.js';import {d as d$1}from'./chunk-DTLLIA2C.js';import {b as b$1}from'./chunk-5Y4YRYZI.js';import {l}from'./chunk-TGDXD4CD.js';import {h}from'./chunk-G6ADWA2B.js';import {g as g$1}from'./chunk-FE5R6EUV.js';import {a}from'./chunk-AFIFZTOY.js';import {p,r}from'./chunk-ODK4LCEL.js';import {w as w$1}from'./chunk-VQZ5PI5J.js';import y from'path';import z from'readline';import w from'fs-extra';var B=p.agentIndex,X=new Map(Object.keys(p).flatMap(e=>{let t=r[e];return t?[[p[e],t]]:[]}));function Y(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 Z={type:"object",properties:{data:true,error:{type:"object",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:false}},oneOf:[{required:["data"]},{required:["error"]}],additionalProperties:false},Q={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},V=[{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>"}}}},{name:"listProofCarryingChanges",description:"List proof-carrying changes with lifecycle, assurance, blockers, and integrity state",inputSchema:{type:"object",properties:{}}},{name:"getProofCarryingChange",description:"Read the ledger-derived state and architecture-aware assurance capsule for one change",inputSchema:{type:"object",properties:{changeId:{type:"string",description:"Canonical proof-carrying change id"}},required:["changeId"]}},{name:"validateProofCarryingChange",description:"Replay and validate one proof-carrying capsule and all hash-bound evidence references",inputSchema:{type:"object",properties:{changeId:{type:"string",description:"Canonical proof-carrying change id"}},required:["changeId"]}}].map(e=>({...e,title:e.name.replace(/([a-z])([A-Z])/g,"$1 $2"),inputSchema:{...e.inputSchema,additionalProperties:false},outputSchema:Z,annotations:Q}));function ee(e){let t=e.trim().replace(/\\/g,"/");return t.length>0&&!y.isAbsolute(t)&&!t.split("/").includes("..")&&(t.startsWith(".workspai/")||t.startsWith(".rapidkit/"))}async function c(e,t){if(!ee(t))throw new Error(`Unsafe artifact path: ${t}`);let n=await g$1(e,t)??y.join(e,t);if(!await w.pathExists(n))return null;let r=await w.readJson(n),o=w$1(t),p$1=X.get(o);if(p$1&&a(r,p$1,`MCP artifact ${o}`),o===p.knowledgeGraph){let a=y.join(e,l);if(!await w.pathExists(a))throw new Error("Workspace knowledge graph cannot be consumed without its source model.");let u=await w.readJson(a);b$1(r,u);}return r}async function te(e$1){let t=[],n=new Set,o=((await c(e$1,d$1))?.blockingReasons??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(o.length>0){t.push({artifact:d$1,reasons:o});for(let i of o)n.add(i);}let p=await c(e$1,c$3);if(e(p)){let i=(p.blockingReasons??[]).filter(l=>typeof l=="string"&&l.trim().length>0);if(i.length>0){t.push({artifact:c$3,reasons:i});for(let l of i)n.add(l);}}let a=await c(e$1,h),u=(a?.violations??[]).filter(i=>typeof i=="string"&&i.trim().length>0);if(u.length>0||String(a?.status??"").toLowerCase()==="failed"){let i=u.length>0?u:["Workspace contract verification failed"];t.push({artifact:h,reasons:i});for(let l of i)n.add(l);}return {blockingReasons:[...n],sources:t}}async function D(e$2,t,n){switch(t){case "getWorkspaceModel":return c(e$2,l);case "getWorkspaceKnowledgeGraph":return c(e$2,p.knowledgeGraph);case "getWorkspaceEvaluation":return c(e$2,n.live===true?p.evaluationLive:p.evaluationLastRun);case "queryWorkspaceEntities":{let r=await c(e$2,p.knowledgeGraph);if(!r)return null;let o=String(n.kind??"").trim();return {schemaVersion:r.schemaVersion,generatedAt:r.generatedAt,entities:e$1(r,o||void 0)}}case "searchWorkspaceGraph":{let r=await c(e$2,p.knowledgeGraph);if(!r)return null;let o=typeof n.limit=="number"?n.limit:Number(n.limit??12);return f$1(r,{query:String(n.query??""),...typeof n.kind=="string"&&n.kind.trim()?{kind:n.kind.trim()}:{},...typeof n.projectId=="string"&&n.projectId.trim()?{projectId:n.projectId.trim()}:{},limit:Number.isFinite(o)?o:12,projection:"agent"})}case "getWorkspaceGraphEvidence":{let r=await c(e$2,p.knowledgeGraph);return r?c$2(r,String(n.query??"")):null}case "findWorkspaceGraphPath":{let r=await c(e$2,p.knowledgeGraph);return r?d(r,String(n.from??""),String(n.to??"")):null}case "getEvidenceIndex":return c(e$2,B);case "getBlockers":return te(e$2);case "getSafeCommands":return {safeCommands:(await c(e$2,b$2))?.safeCommands??[]};case "getProjectContext":{let r=await c(e$2,b$2);if(!r)return null;let o=String(n.project??"").trim(),p=r.scope?.activeProject??void 0,a=o||p,u=Array.isArray(r.projects)?r.projects:[],i=a&&u.find(l=>typeof l.name=="string"&&l.name.toLowerCase()===a.toLowerCase());return {workspace:r.workspace??null,scope:r.scope??null,validation:r.validation??null,project:i??null,safeCommands:r.safeCommands??[]}}case "getArtifact":{let r=String(n.relativePath??"").trim();return c(e$2,r)}case "listOperationalSkills":return c(e$2,b$3);case "getWorkspaceExplain":{let r=String(n.target??"release-blocked").trim(),o=c$1(r);if(!o)throw new Error(`Invalid explain target: ${r}`);let p=await c(e$2,c$3);return e(p)&&Y(p.target,o)?p:b({workspacePath:e$2,target:o})}case "listProofCarryingChanges":return k({workspacePath:e$2});case "getProofCarryingChange":return j({workspacePath:e$2,changeId:String(n.changeId??"").trim(),operation:"status"});case "validateProofCarryingChange":return m({workspacePath:e$2,changeId:String(n.changeId??"").trim()});default:throw new Error(`Unknown tool: ${t}`)}}var J="2026-07-28",F=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],U={name:"workspai-workspace-mcp",version:"1.0.0"};function ne(e){let t=e.params?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t["io.modelcontextprotocol/protocolVersion"];return typeof n=="string"?n:void 0}function re(e,t){return !t||!e||typeof e!="object"||Array.isArray(e)?e:{...e,_meta:{...e._meta??{},"io.modelcontextprotocol/serverInfo":U}}}function g(e,t,n=false){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,result:re(t,n)})}
2
2
  `);}function f(e,t,n=-32e3){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:e??null,error:{code:n,message:t}})}
3
3
  `);}function oe(e){let t={data:e};return {content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t,isError:false}}function A(e,t){return {content:[{type:"text",text:t}],structuredContent:{error:{code:e,message:t}},isError:true}}function ie(e,t){for(let n of e.inputSchema.required??[])if(!(n in t))return `Missing required argument: ${n}`;for(let[n,r]of Object.entries(t)){let o=e.inputSchema.properties[n];if(!o)return `Unknown argument for ${e.name}: ${n}`;if(o.type==="string"&&typeof r!="string")return `Argument ${n} must be a string`;if(o.type==="boolean"&&typeof r!="boolean")return `Argument ${n} must be a boolean`;if(o.type==="integer"&&(!Number.isInteger(r)||typeof r!="number"))return `Argument ${n} must be an integer`;if(typeof r=="number"){if(typeof o.minimum=="number"&&r<o.minimum)return `Argument ${n} must be at least ${o.minimum}`;if(typeof o.maximum=="number"&&r>o.maximum)return `Argument ${n} must be at most ${o.maximum}`}}return null}async function Ae(e){let t=y.resolve(e.workspacePath),n=z.createInterface({input:process.stdin,terminal:false});for await(let r of n){let o=r.trim();if(!o)continue;let p;try{p=JSON.parse(o);}catch{f(null,"Invalid JSON-RPC request",-32700);continue}let{id:a,method:u,params:i}=p,l=ne(p)===J;try{if(u==="server/discover"){g(a,{resultType:"complete",supportedVersions:[J],capabilities:{tools:{listChanged:false}},instructions:"Use bounded Workspai graph search before requesting complete workspace artifacts."},true);continue}if(u==="initialize"){let s=typeof i?.protocolVersion=="string"?i.protocolVersion:void 0,k=F.includes(s)?s:F.at(-1);g(a,{protocolVersion:k,capabilities:{tools:{listChanged:false}},serverInfo:U});continue}if(u==="notifications/initialized")continue;if(u==="tools/list"){g(a,{tools:V.map(s=>({name:s.name,title:s.title,description:s.description,inputSchema:s.inputSchema,outputSchema:s.outputSchema,annotations:s.annotations}))},l);continue}if(u==="tools/call"){let s=String(i?.name??""),k=V.find(m=>m.name===s);if(!k){f(a,`Unknown tool: ${s}`,-32602);continue}if(i?.arguments!==void 0&&(!i.arguments||typeof i.arguments!="object"||Array.isArray(i.arguments))){f(a,"Tool arguments must be an object",-32602);continue}let j=i?.arguments&&typeof i.arguments=="object"?i.arguments:{},v=ie(k,j);if(v){g(a,A("invalid_arguments",v),l);continue}try{let m=await D(t,s,j);g(a,m==null?A("artifact_not_found",`${s} returned no current workspace data`):oe(m),l);}catch(m){g(a,A("tool_execution_failed",m instanceof Error?m.message:String(m)),l);}continue}f(a,`Unsupported method: ${u??"unknown"}`,-32601);}catch(s){f(a,s instanceof Error?s.message:String(s));}}}async function je(e,t,n={}){return D(y.resolve(e),t,n)}export{V as WORKSPACE_MCP_READ_TOOLS,je as invokeMcpToolForTest,Ae as runWorkspaceMcpServe};
@@ -1 +1 @@
1
- export{l as WORKSPACE_MODEL_REPORT_PATH,k as WORKSPACE_MODEL_SCHEMA_VERSION,q as buildWorkspaceModel,r as buildWorkspaceModelCached,p as buildWorkspaceModelFacts,s as buildWorkspaceModelIncremental,n as createWorkspaceModelBuildProvenance,o as validateWorkspaceModelStrict,m as workspaceModelProjectTopology,t as writeWorkspaceModel}from'./chunk-4HQU2GQM.js';
1
+ export{l as WORKSPACE_MODEL_REPORT_PATH,k as WORKSPACE_MODEL_SCHEMA_VERSION,q as buildWorkspaceModel,r as buildWorkspaceModelCached,p as buildWorkspaceModelFacts,s as buildWorkspaceModelIncremental,n as createWorkspaceModelBuildProvenance,o as validateWorkspaceModelStrict,m as workspaceModelProjectTopology,t as writeWorkspaceModel}from'./chunk-TGDXD4CD.js';
@@ -1 +1 @@
1
- export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-DNKELRK6.js';
1
+ export{b as finalizeWorkspaceOnboarding,a as syncWorkspaceConsumerArtifacts}from'./chunk-IQFXLJIM.js';
@@ -1,2 +1,2 @@
1
- import {a,b}from'./chunk-2LIVMG5C.js';import {t,q}from'./chunk-VQZ5PI5J.js';import l from'fs-extra';function c(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function m(n,e,o){let s=(await Promise.all(t(n,e).map(async r=>({candidate:r,exists:await l.pathExists(r)})))).find(({exists:r})=>r)?.candidate;if(!s)return false;let t$1=q(n,e),a=c(await l.readJson(s));return await l.outputJson(t$1,o(a),{spaces:2}),await l.appendFile(t$1,`
2
- `,"utf-8"),true}async function M(n,e){let o=e.now??new Date().toISOString(),s=e.installMethod==="pip"?"venv":e.installMethod;await m(n,"workspace.json",a=>{let r=c(a.engine),i=c(r.python_core);return delete a.bootstrap_note,delete i.reason,{...a,engine:{...r,install_method:s,python_version:e.pythonVersion??r.python_version??null,python_core:{...i,status:"installed",installed_at:o,...e.coreVersion?{version:e.coreVersion}:{}}}}}),await m(n,"toolchain.lock",a=>{let r=c(a.runtime),i=c(r.python),d=c(i.core);return delete d.reason,{...a,generated_at:o,runtime:{...r,python:{...i,version:e.pythonVersion??i.version??null,install_method:s,core:{...d,status:"installed",installed_at:o,...e.coreVersion?{version:e.coreVersion}:{}}}}}});let t=await a(n);if(t){let a={...t.metadata?.python??{}};delete a.coreReason,t.metadata={...t.metadata,python:{...a,coreStatus:"installed",...e.coreVersion?{coreVersion:e.coreVersion}:{},...e.pythonVersion?{pythonVersion:e.pythonVersion}:{},...e.venvPath?{venvPath:e.venvPath}:{}},npm:{...t.metadata?.npm??{},packageVersion:t.metadata?.npm?.packageVersion??t.version,installMethod:s,lastUsedAt:o}},await b(n,t);}}export{M as markWorkspacePythonEngineInstalled};
1
+ import {a,c as c$1}from'./chunk-252EKOR6.js';import {t,q}from'./chunk-VQZ5PI5J.js';import l from'fs-extra';function c(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}async function m(n,e,o){let s=(await Promise.all(t(n,e).map(async r=>({candidate:r,exists:await l.pathExists(r)})))).find(({exists:r})=>r)?.candidate;if(!s)return false;let t$1=q(n,e),a=c(await l.readJson(s));return await l.outputJson(t$1,o(a),{spaces:2}),await l.appendFile(t$1,`
2
+ `,"utf-8"),true}async function M(n,e){let o=e.now??new Date().toISOString(),s=e.installMethod==="pip"?"venv":e.installMethod;await m(n,"workspace.json",a=>{let r=c(a.engine),i=c(r.python_core);return delete a.bootstrap_note,delete i.reason,{...a,engine:{...r,install_method:s,python_version:e.pythonVersion??r.python_version??null,python_core:{...i,status:"installed",installed_at:o,...e.coreVersion?{version:e.coreVersion}:{}}}}}),await m(n,"toolchain.lock",a=>{let r=c(a.runtime),i=c(r.python),d=c(i.core);return delete d.reason,{...a,generated_at:o,runtime:{...r,python:{...i,version:e.pythonVersion??i.version??null,install_method:s,core:{...d,status:"installed",installed_at:o,...e.coreVersion?{version:e.coreVersion}:{}}}}}});let t=await a(n);if(t){let a={...t.metadata?.python??{}};delete a.coreReason,t.metadata={...t.metadata,python:{...a,coreStatus:"installed",...e.coreVersion?{coreVersion:e.coreVersion}:{},...e.pythonVersion?{pythonVersion:e.pythonVersion}:{},...e.venvPath?{venvPath:e.venvPath}:{}},npm:{...t.metadata?.npm??{},packageVersion:t.metadata?.npm?.packageVersion??t.version,installMethod:s,lastUsedAt:o}},await c$1(n,t);}}export{M as markWorkspacePythonEngineInstalled};
@@ -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-TIZCESKY.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-KCIET26G.js';
@@ -0,0 +1,3 @@
1
+ import {a as a$2}from'./chunk-H333GKL4.js';import {a,c,i,b,f as f$1,k as k$1,h,e}from'./chunk-V4LCPLV6.js';import {c as c$2}from'./chunk-SVGUAVMG.js';import {m}from'./chunk-SAZXL36B.js';import {l,p}from'./chunk-TBOIXIQA.js';import {h as h$1,m as m$1,n,o,l as l$1,q,r,s}from'./chunk-NCZJUPG5.js';import {a as a$5}from'./chunk-7Q7X4X5I.js';import {a as a$4}from'./chunk-AO2ZI42U.js';import {a as a$3}from'./chunk-UHT2SW7O.js';import {p as p$2}from'./chunk-G6ADWA2B.js';import {B}from'./chunk-5EVBOUYW.js';import {f}from'./chunk-FE5R6EUV.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c as c$3,d}from'./chunk-EWZZUQBR.js';import {p as p$1}from'./chunk-ODK4LCEL.js';import {c as c$4,b as b$1}from'./chunk-25AWHAB5.js';import {randomUUID,createHash}from'crypto';import {hostname}from'os';import c$1 from'path';import {execa}from'execa';import k from'fs-extra';var Ge=".workspai/repair",La="transaction.json",Ga="source-plan.json",ba="checkpoint",za="engine.lock",Aa=5*1024*1024,Ka=25*1024*1024,Va=25*1024*1024,Ea=4*1024*1024,Ja=900*1e3,Ua=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"]),G={safe:0,guarded:1,invasive:2},Xa=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 Za(e){return [e.kind,e.id,e.projectPath??"",e.adapterId??"",e.executable??""].join("\0")}function H(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 $a(e){let a=new Map,r=t=>a.set(Za(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=Ce(t);(t.status==="blocked"||t.status==="guidance-only"||!o&&!t.invocation)&&r({kind:"source-repair-required",id:`action:${t.id}`,message:t.blocker||`${t.id} requires a bounded source repair proposal.`,...t.projectPath?{projectPath:t.projectPath}:{}}),G[t.risk]>G[e.maxRisk]&&r({kind:"risk-approval",id:`risk:${t.id}`,message:`${t.id} exceeds the approved ${e.maxRisk} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});}for(let t of e.preconditions.filter(o=>o.status==="failed")){if(t.id==="structured-execution"){r({kind:"source-repair-required",id:`precondition:${t.id}`,message:t.message});continue}if(t.id.startsWith("tool:")){let o=e.stages.find(i=>i.invocation&&`tool:${i.invocation.cwd}:${i.invocation.executable}`===t.id);if(o?.invocation){r({kind:"missing-executable",id:t.id,message:t.message,projectPath:o.invocation.cwd,executable:o.invocation.executable});continue}}r({kind:"failed-precondition",id:`precondition:${t.id}`,message:t.message});}if(e.decisionOptions.has("allow-force")&&r({kind:"policy-exception",id:"policy:allow-force",message:"The proposed repair requires an explicit force-install policy exception."}),e.decisionOptions.has("allow-breaking")&&r({kind:"policy-exception",id:"policy:allow-breaking",message:"The proposed repair requires an explicit breaking-change policy exception."}),a.size===0){let t=e.fallbackReasons.find(o=>o.trim().length>0);t&&r({kind:"failed-precondition",id:`decision:${$(t).slice(0,16)}`,message:t});}return [...a.values()]}function M(e){return (e?.()??new Date).toISOString()}function $(e){return createHash("sha256").update(e).digest("hex")}function V(e){return Array.isArray(e)?`[${e.map(V).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,a])=>a!==void 0).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>`${JSON.stringify(a)}:${V(r)}`).join(",")}}`:e===void 0?"null":JSON.stringify(e)}function va(e){return $(V({target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(({backupRef:a,...r})=>r)},stages:e.stages.map(({startedAt:a,completedAt:r,...t})=>t),decision:e.decision}))}async function Sa(e,a){if(a.state!=="decision-required"||a.checkpoint.status==="captured")return;let r=va(a),t=(await jt(e)).find(o=>o.state==="decision-required"&&o.checkpoint.status!=="captured"&&va(o)===r);if(t)return await re(c$1.join(e,b),t),t}var _e="causal-action-integrity:";function Wa(e){return $(V([...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 Ca(e){if(e.length===0)return;let a=Wa(e);return {id:`${_e}${a}`,status:"passed",message:`${e.length} causal action(s) are semantically pinned to this approval (${a.slice(0,12)}).`}}function Qa(e){return V({cardId:e.cardId,projectName:e.projectName??null,projectPath:e.projectPath??null,findingId:e.findingId,causalKey:e.causalKey})}function Pa(e){return new Set(e.map(Qa))}function x(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 K(e,a){let r=await k.realpath(e).catch(()=>c$1.resolve(e)),t=c$1.resolve(a);for(;!await k.pathExists(t);){let i=c$1.dirname(t);if(i===t)return false;t=i;}let o=await k.realpath(t).catch(()=>c$1.resolve(t));return x(r,o)}function Y(e,a,r){let t=c$1.isAbsolute(a)?c$1.resolve(a):c$1.resolve(e,a);if(!x(e,t)&&!(r&&x(c$1.resolve(r),t)))throw new Error(`Repair path escapes workspace boundary: ${a}`);if(!x(e,t)&&r){let o=c$1.resolve(r),i=c$1.relative(o,t).split(c$1.sep).join("/"),n=`external/${c$1.basename(o)}`;return i&&i!=="."?`${n}/${i}`:n}return c$1.relative(e,t).split(c$1.sep).join("/")||"."}function z(e){let a=e.replaceAll("\\","/").replace(/^\.\//,""),r=/^external\/([^/]+)(?:\/(.*))?$/.exec(a);if(!r)return;let t=r[2]??"";if(!t.split("/").some(o=>o===".."))return {root:`external/${r[1]}`,suffix:t}}async function T(e){if(c$1.isAbsolute(e.value))return c$1.resolve(e.value);let a=z(e.value);if(!a)return c$1.resolve(e.workspacePath,e.value);if(e.projectBoundary)return c$1.resolve(e.projectBoundary,a.suffix||".");let{contract:r}=await p$2({workspacePath:e.workspacePath}),t=r.projects.find(o=>o.relativePath.replaceAll("\\","/")===a.root||o.externalPath!==void 0&&c$1.basename(c$1.resolve(o.externalPath))===a.root.slice(9)||e.projectName!==void 0&&o.slug===e.projectName);if(!t?.externalPath)throw new Error(`Portable external project reference is not canonically registered: ${a.root}`);return c$1.resolve(t.externalPath,a.suffix||".")}function Re(e,a,r,t){let o=Y(e,a,r),i=z(o);return !i||!t?o:i.suffix?`${t}/${i.suffix}`:t}async function et(e){if(!e.proposal.projectName&&!e.proposal.projectPath)return;let a=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0,r=e.proposal.projectPath?.replaceAll("\\","/").replace(/^\.\//,"");if(a&&x(e.workspacePath,a)&&!z(e.proposal.projectPath??""))return a;let{contract:t}=await p$2({workspacePath:e.workspacePath}),o=t.projects.find(i=>{let n=i.externalPath?c$1.resolve(i.externalPath):c$1.resolve(e.workspacePath,i.relativePath),s=!e.proposal.projectName||i.slug===e.proposal.projectName,h=!a||n===a||i.relativePath.replaceAll("\\","/")===r;return s&&h});if(!o)throw new Error("Repair proposal project must match one canonical registered project.");return o.externalPath?c$1.resolve(o.externalPath):c$1.resolve(e.workspacePath,o.relativePath)}function de(e,a){if(!/^[A-Za-z0-9_-]{12,128}$/.test(a))throw new Error("Invalid repair transaction id.");return c$1.join(e,Ge,"transactions",a)}async function ee(e,a){return a.target.projectPath?T({workspacePath:e,value:a.target.projectPath,projectName:a.target.projectName}):void 0}function Se(e,a){return c$1.join(de(e,a),La)}function ze(e,a){return c$1.join(de(e,a),Ga)}async function re(e,a){await k.ensureDir(c$1.dirname(e));let r=`${e}.${process.pid}.${randomUUID()}.tmp`;await k.writeJson(r,a,{spaces:2}),await k.move(r,e,{overwrite:true});}function A(e,a,r,t={}){let o={sequence:e.events.length+1,at:M(t.now),type:a,...t.stageId?{stageId:t.stageId}:{},...t.status?{status:t.status}:{},message:r};e.events.push(o);let i=t.status??a,n=a==="failed"||i==="failed"?"failed":a==="cancelled"?"cancelled":a==="closed"||i==="passed"||i==="completed"?"succeeded":a==="rollback"?"rolled-back":i==="blocked"?"blocked":"running";t.stageId?c$4({blockId:`repair.${t.stageId}`,status:n,message:r,component:"workspace-repair",attributes:{transactionId:e.transactionId,repairEventType:a}}):b$1({kind:n==="failed"?"operation.failed":n==="succeeded"||n==="rolled-back"?"operation.completed":"operation.started",status:n,component:"workspace-repair",message:r,correlationId:e.transactionId,attributes:{repairEventType:a}});}async function j(e,a,r){a.revision+=1,a.updatedAt=M(r),a$1(a,c,"Workspace repair transaction"),await re(Se(e,a.transactionId),a),await re(c$1.join(e,b),a);}async function pe(e){let a$2=await k.readJson(Se(e.workspacePath,e.transactionId));if(a$2.schemaVersion!==a)throw new Error(`Unsupported repair transaction schema: ${a$2.schemaVersion}`);return a$1(a$2,c,"Workspace repair transaction"),a$2}async function We(e,a){return await k.readJson(ze(e,a))}function ce(e$1){return e$1.schemaVersion===e}async function le(e,a,r){let t=a.scope==="project"&&a.projectPath?a.projectPath:".",o=await T({workspacePath:e,value:t,projectBoundary:r,projectName:a.projectName});if(!x(e,o)&&!z(t)&&!(r&&c$1.resolve(r)===o))throw new Error(`Repair project scope escapes workspace: ${t}`);return o}function v(e){return {cwd:e.projectReference??Y(e.workspacePath,e.projectPath,e.projectPath),executable:e.executable,args:[...e.args],purpose:e.purpose,timeoutMs:e.timeoutMs??6e5}}async function Me(e){return k.readFile(e,"utf8").catch(()=>"")}async function at(e){return k.readJson(e).catch(()=>({}))}function ya(e){let a=e.manager==="yarn"?[e.script]:["run",e.script];return v({...e,executable:e.manager,args:a,purpose:e.purpose})}async function Ta(e){let a=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary});return e.toolAvailable?e.toolAvailable(e.invocation.executable,a):a$5({executable:e.invocation.executable,cwd:a})}async function Ke(e){let a=new Set;for(let i of e.stages){if(i.kind!=="repair"||!i.invocation)continue;let n=Te(i.invocation.executable);if(!["python","python3","py"].includes(n)||!i.invocation.args.includes("venv")||!i.invocation.args.includes(".venv"))continue;let s=await T({workspacePath:e.workspacePath,value:i.invocation.cwd});a.add(c$1.normalize(c$1.join(s,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python")));}let r=e.stages.filter(i=>i.required&&i.status!=="skipped"&&i.invocation).map(i=>i.invocation),t=new Map;for(let i of r)t.set(`${i.cwd}\0${i.executable}`,i);let o=[];for(let i of t.values()){let n=await T({workspacePath:e.workspacePath,value:i.cwd}),s=c$1.isAbsolute(i.executable)?c$1.normalize(i.executable):c$1.normalize(c$1.resolve(n,i.executable));if(a.has(s)){o.push({id:`tool:${i.cwd}:${i.executable}`,status:"passed",message:`Repair stage will create the isolated executable before use: ${i.executable} (${i.cwd}).`});continue}let h=await Ta({workspacePath:e.workspacePath,invocation:i,toolAvailable:e.toolAvailable});o.push({id:`tool:${i.cwd}:${i.executable}`,status:h?"passed":"failed",message:h?`Required repair executable is available: ${i.executable} (${i.cwd}).`:`Required repair executable is unavailable: ${i.executable} (${i.cwd}). Install or configure it, then create a fresh plan.`});}return o}function se(e,a,r){return {id:e,kind:a,status:"skipped",required:false,risk:"safe",summary:r}}function R(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 tt(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 rt(e){let a=await le(e.workspacePath,e.action,e.authorizedProjectRoot),r=z(e.action.projectPath??"")?.root??Y(e.workspacePath,a,a),t=async f=>k.pathExists(c$1.join(a,f)),o=new Set,i=[],n=[],s=f=>`${r}:${e.adapterId}:${f}`,h$1=f=>f.forEach(m=>o.add(Y(e.workspacePath,c$1.join(a,m),a))),l=f=>{i.push(f),f.required&&f.status==="blocked"&&n.push(f.summary);},d=tt(e.workspacePath,a,e.action),g=()=>{let f=h.find(m=>m.id===e.adapterId);if(!f)throw new Error(`Unknown workspace repair adapter: ${e.adapterId}`);return {stages:i,checkpointFiles:[...o],blockers:n,adapters:[{adapterId:f.id,ecosystem:f.ecosystem,projectPath:r,manifests:f.manifests,support:f.support,status:n.length>0?"partial":"ready",requiredExecutables:[...new Set(i.filter(m=>m.required&&m.invocation).map(m=>m.invocation.executable))],missingExecutables:[],message:n.length>0?[...new Set(n)].join(" "):`${f.ecosystem} repair stages are deterministically planned.`}]}};if(e.adapterId==="node"&&await t("package.json")){let f=await at(c$1.join(a,"package.json")),m=f.scripts&&typeof f.scripts=="object"&&!Array.isArray(f.scripts)?f.scripts:{},w=await t("bun.lock")||await t("bun.lockb")?"bun":await t("pnpm-lock.yaml")?"pnpm":await t("yarn.lock")?"yarn":"npm",D=w==="bun"?await t("bun.lock")?"bun.lock":"bun.lockb":w==="pnpm"?"pnpm-lock.yaml":w==="yarn"?"yarn.lock":await t("npm-shrinkwrap.json")?"npm-shrinkwrap.json":"package-lock.json";h$1(["package.json",D]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${w} manifest, lockfile, and installed tree.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:["install"],purpose:"reconcile"})}));let J=v(w==="npm"?{workspacePath:e.workspacePath,projectPath:a,executable:"npm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="pnpm"?{workspacePath:e.workspacePath,projectPath:a,executable:"pnpm",args:["audit","--audit-level=moderate","--json"],purpose:"audit"}:w==="yarn"?{workspacePath:e.workspacePath,projectPath:a,executable:"yarn",args:["npm","audit","--json","--severity","moderate"],purpose:"audit"}:{workspacePath:e.workspacePath,projectPath:a,executable:"bun",args:["audit","--json"],purpose:"audit"});return l(R({id:s("audit"),kind:"audit",summary:"Prove the dependency advisory graph is clean.",invocation:d??J})),l(typeof m.test=="string"&&m.test.trim()?R({id:s("test"),kind:"test",summary:"Run the declared project test contract.",invocation:ya({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"test",purpose:"test"})}):se(s("test"),"test","No test script is declared.")),l(typeof m.build=="string"&&m.build.trim()?R({id:s("build"),kind:"build",summary:"Run the declared project build contract.",invocation:ya({workspacePath:e.workspacePath,projectPath:a,manager:w,script:"build",purpose:"build"})}):se(s("build"),"build","No build script is declared.")),g()}if(e.adapterId==="python"&&(await t("pyproject.toml")||await t("requirements.txt"))){h$1(["pyproject.toml","requirements.txt","uv.lock","poetry.lock"]);let f=e.action.transaction?.ecosystem.toLowerCase(),m=c$1.basename(e.action.invocation?.executable??"").toLowerCase().replace(/\.(?:cmd|bat|exe)$/i,""),w=m==="uv"||f==="uv"||await t("uv.lock"),D=!w&&(m==="poetry"||f==="poetry"||await t("poetry.lock")),J=!w&&!D&&["python","python3","py"].includes(m)&&(e.action.invocation?.args??[]).some(L=>L==="venv")&&(e.action.invocation?.args??[]).some(L=>L===".venv"),W=process.platform==="win32"?"python":"python3",F=c$1.join(a,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python");(await k.pathExists(F)||J)&&(W=F);let B=w?v({workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["sync"],purpose:"reconcile"}):D?v({workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["install","--no-interaction"],purpose:"reconcile"}):await t("requirements.txt")&&x(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-r","requirements.txt"],purpose:"reconcile"}):await t("pyproject.toml")&&x(e.workspacePath,W)?v({workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pip","install","-e","."],purpose:"reconcile"}):void 0;l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Reconcile the isolated Python dependency environment.",invocation:B})),l(R({id:s("audit"),kind:"audit",summary:"Prove the Python advisory graph is clean.",invocation:d}));let oe=await Me(c$1.join(a,"pyproject.toml")),X=await t("tests")||/\[tool\.pytest/i.test(oe),ue=v(D?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["run","python","-m","pytest"],purpose:"test"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["run","python","-m","pytest"],purpose:"test"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","pytest"],purpose:"test"}),Z=v(D?{workspacePath:e.workspacePath,projectPath:a,executable:"poetry",args:["build"],purpose:"build"}:w?{workspacePath:e.workspacePath,projectPath:a,executable:"uv",args:["build"],purpose:"build"}:{workspacePath:e.workspacePath,projectPath:a,executable:W,args:["-m","build"],purpose:"build"});return l(X?R({id:s("test"),kind:"test",summary:"Run the Python test contract.",invocation:ue}):se(s("test"),"test","No Python test surface is declared.")),l(/\[build-system\]/i.test(oe)?R({id:s("build"),kind:"build",summary:"Build the declared Python package.",invocation:Z}):se(s("build"),"build","No Python build contract is declared.")),g()}let b=[{adapterId:"go",manifest:"go.mod",files:["go.mod","go.sum"],reconcile:["go",["mod","tidy"]],audit:["govulncheck",["-json","./..."]],test:["go",["test","./..."]],build:["go",["build","./..."]]},{adapterId:"rust",manifest:"Cargo.toml",files:["Cargo.toml","Cargo.lock"],reconcile:["cargo",["check"]],audit:["cargo",["audit","--json"]],test:["cargo",["test"]],build:["cargo",["build"]]},{adapterId:"php-composer",manifest:"composer.json",files:["composer.json","composer.lock"],reconcile:["composer",["install","--no-interaction"]],audit:["composer",["audit","--format=json"]],test:["composer",["run-script","test"]],build:["composer",["run-script","build"]]},{adapterId:"ruby-bundler",manifest:"Gemfile",files:["Gemfile","Gemfile.lock"],reconcile:["bundle",["install"]],audit:["bundle-audit",["check","--format","json"]],test:["bundle",["exec","rake","test"]],build:["bundle",["exec","rake","build"]]},{adapterId:"elixir-mix",manifest:"mix.exs",files:["mix.exs","mix.lock"],reconcile:["mix",["deps.get"]],audit:["mix",["hex.audit"]],test:["mix",["test"]],build:["mix",["compile","--warnings-as-errors"]]},{adapterId:"deno",manifest:"deno.json",alternateManifest:"deno.jsonc",files:["deno.json","deno.lock"],reconcile:["deno",["install"]],audit:["deno",["audit"]],test:["deno",["task","test"]],build:["deno",["task","build"]]}];for(let f of b){if(f.adapterId!==e.adapterId)continue;let m=await t(f.manifest)?f.manifest:f.alternateManifest&&await t(f.alternateManifest)?f.alternateManifest:void 0;if(!m)continue;h$1(f.files),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Reconcile ${m} and its lock/baseline.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.reconcile[0],args:f.reconcile[1],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the runtime-native dependency audit.",invocation:d??(f.audit?v({workspacePath:e.workspacePath,projectPath:a,executable:f.audit[0],args:f.audit[1],purpose:"audit"}):void 0)}));let w=await Me(c$1.join(a,m)),D=f.manifest==="composer.json"||f.adapterId==="deno"?/["']test["']\s*:/.test(w):f.manifest==="Gemfile"?await t("Rakefile"):true,J=f.manifest==="composer.json"||f.manifest==="deno.json"?/["']build["']\s*:/.test(w):f.manifest==="Gemfile"?(await k.readdir(a)).some(W=>W.endsWith(".gemspec")):true;return l(D?R({id:s("test"),kind:"test",summary:"Run the runtime-native test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.test[0],args:f.test[1],purpose:"test"})}):se(s("test"),"test","No test contract is declared.")),l(J?R({id:s("build"),kind:"build",summary:"Run the runtime-native build contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f.build[0],args:f.build[1],purpose:"build"})}):se(s("build"),"build","No build contract is declared.")),g()}let y=await k.readdir(a).catch(()=>[]);if(e.adapterId==="dotnet"&&y.some(f=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(f)))return h$1(["Directory.Packages.props","packages.lock.json",...y.filter(f=>/\.(?:cs|fs|vb)proj$|\.sln$/i.test(f))]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Restore the NuGet dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["restore"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Prove the NuGet advisory graph is clean.",invocation:d??v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["package","list","--vulnerable","--include-transitive","--format","json"],purpose:"audit"})})),l(R({id:s("test"),kind:"test",summary:"Run .NET tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["test","--no-restore"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the .NET project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"dotnet",args:["build","--no-restore"],purpose:"build"})})),g();let P=await t("mvnw")?"./mvnw":await t("mvnw.cmd")?".\\mvnw.cmd":"mvn";if(e.adapterId==="jvm-maven"&&await t("pom.xml"))return h$1(["pom.xml"]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Maven dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["dependency:resolve"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run Maven tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the Maven artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:P,args:["package","-DskipTests"],purpose:"build"})})),g();let E=await t("build.gradle.kts")?"build.gradle.kts":await t("build.gradle")?"build.gradle":void 0;if(e.adapterId==="jvm-gradle"&&E){let f=await t("gradlew")?"./gradlew":await t("gradlew.bat")?".\\gradlew.bat":"gradle";return h$1([E,"gradle.lockfile","gradle/libs.versions.toml"]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve the Gradle dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["dependencies"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared JVM dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run Gradle tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the Gradle project.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:f,args:["build","-x","test"],purpose:"build"})})),g()}let q=await t("deps.edn")?"deps.edn":await t("project.clj")?"project.clj":void 0;if(e.adapterId==="clojure"&&q){let f=q==="deps.edn",m=await Me(c$1.join(a,q)),w=f?"clojure":"lein";h$1([q]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:`Resolve the ${q} dependency graph.`,invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:f?["-P"]:["deps"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared Clojure dependency audit.",invocation:d}));let D=!f||/:test\b/.test(m);return l(D?R({id:s("test"),kind:"test",summary:"Run the declared Clojure test contract.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:w,args:f?["-M:test"]:["test"],purpose:"test"})}):se(s("test"),"test","No Clojure :test alias is declared.")),l(f?se(s("build"),"build","No portable Clojure CLI build entrypoint is declared."):R({id:s("build"),kind:"build",summary:"Build the Leiningen project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"lein",args:["uberjar"],purpose:"build"})})),g()}return e.adapterId==="scala-sbt"&&await t("build.sbt")?(h$1(["build.sbt"]),l(R({id:s("reconcile"),kind:"reconcile",risk:"guarded",summary:"Resolve and compile the sbt dependency graph.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["compile"],purpose:"reconcile"})})),l(R({id:s("audit"),kind:"audit",summary:"Run the declared Scala dependency audit.",invocation:d})),l(R({id:s("test"),kind:"test",summary:"Run sbt tests.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["test"],purpose:"test"})})),l(R({id:s("build"),kind:"build",summary:"Build the sbt project artifact.",invocation:v({workspacePath:e.workspacePath,projectPath:a,executable:"sbt",args:["package"],purpose:"build"})})),g()):(n.push(`The ${e.adapterId} repair adapter no longer matches the source at ${r}; refresh evidence and create a fresh plan.`),l(R({id:s("reconcile"),kind:"reconcile",required:true,summary:n[0]})),g())}async function Na(e){let a=i=>k.pathExists(c$1.join(e,i)),r=await k.readdir(e).catch(()=>[]),t=[];await a("package.json")&&t.push("node"),(await a("pyproject.toml")||await a("requirements.txt"))&&t.push("python"),await a("go.mod")&&t.push("go"),await a("Cargo.toml")&&t.push("rust"),await a("composer.json")&&t.push("php-composer"),await a("Gemfile")&&t.push("ruby-bundler"),await a("mix.exs")&&t.push("elixir-mix"),(await a("deno.json")||await a("deno.jsonc"))&&t.push("deno"),r.some(i=>/\.(?:cs|fs|vb)proj$|\.slnx?$/i.test(i))&&t.push("dotnet"),await a("pom.xml")&&t.push("jvm-maven"),(await a("build.gradle.kts")||await a("build.gradle"))&&t.push("jvm-gradle"),(await a("deps.edn")||await a("project.clj"))&&t.push("clojure"),await a("build.sbt")&&t.push("scala-sbt");for(let i of B(e).units){let n=qa(i.ecosystem);n&&t.push(n);}let o=new Map(h.map((i,n)=>[i.id,n]));return [...new Set(t)].sort((i,n)=>(o.get(i)??999)-(o.get(n)??999))}function qa(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 Da(e,a={}){let r=await le(e.workspacePath,e.action,e.authorizedProjectRoot),t=z(e.action.projectPath??"")?.root??Y(e.workspacePath,r,r),o=await Na(r),i=qa(e.action.transaction?.ecosystem),n=i?[i]:o;if(i&&!o.includes(i)){let d=`Doctor declared the ${i} repair adapter for ${t}, but its canonical manifest is not present. Refresh Doctor evidence before repair.`;return {stages:[R({id:`${t}:${i}:reconcile`,kind:"reconcile",required:true,summary:d})],checkpointFiles:[],blockers:[d],adapters:[{adapterId:i,ecosystem:h.find(g=>g.id===i)?.ecosystem??i,projectPath:t,manifests:[],support:"conditional",status:"partial",requiredExecutables:[],missingExecutables:[],message:d}]}}if(n.length===0){let d=`No deterministic dependency transaction adapter exists for ${t}.`;return {stages:[R({id:`${t}:unsupported:reconcile`,kind:"reconcile",required:true,summary:d})],checkpointFiles:[],blockers:[d],adapters:[{adapterId:"unsupported",ecosystem:"Unknown",projectPath:t,manifests:[],support:"unsupported",status:"unsupported",requiredExecutables:[],missingExecutables:[],message:d}]}}let s={stages:[],checkpointFiles:[],blockers:[],adapters:[]};for(let d of n){let g=await rt({...e,adapterId:d});s.stages.push(...g.stages),s.checkpointFiles.push(...g.checkpointFiles),s.blockers.push(...g.blockers),s.adapters.push(...g.adapters);}s.stages=[...new Map(s.stages.map(d=>[d.id,d])).values()],s.checkpointFiles=[...new Set(s.checkpointFiles)].sort(),s.blockers=[...new Set(s.blockers)];let h$1=Y(e.workspacePath,r,r);if(h$1!==t){let d=g=>g===h$1?t:g.startsWith(`${h$1}/`)?`${t}/${g.slice(h$1.length+1)}`:g;s.stages=s.stages.map(g=>({...g,...g.invocation?{invocation:{...g.invocation,cwd:d(g.invocation.cwd)}}:{}})),s.checkpointFiles=s.checkpointFiles.map(d);}let l=new Set;if(e.action.transaction?.kind==="dependency-materialization"){let d=new Set(e.action.transaction.requiredStages),g=Te(e.action.invocation?.executable??""),b=e.action.invocation?.args??[],y=e.action.transaction.ecosystem==="python"&&["python","python3","py"].includes(g)&&b.includes("venv")&&b.includes(".venv");y&&l.add(c$1.normalize(c$1.join(r,".venv",process.platform==="win32"?"Scripts/python.exe":"bin/python"))),s.stages=s.stages.filter(P=>P.kind==="reconcile"?y&&d.has("reconcile"):d.has(P.kind)),s.blockers=s.stages.filter(P=>P.required&&P.status==="blocked").map(P=>P.summary);}for(let d of s.adapters){let g=s.stages.filter(y=>y.id.startsWith(`${d.projectPath}:${d.adapterId}:`)),b=[];d.requiredExecutables=[...new Set(g.filter(y=>y.required&&y.invocation).map(y=>y.invocation.executable))];for(let y of g){if(!y.required||!y.invocation)continue;let P=await T({workspacePath:e.workspacePath,value:y.invocation.cwd,projectBoundary:r}),E=c$1.isAbsolute(y.invocation.executable)?c$1.normalize(y.invocation.executable):c$1.normalize(c$1.resolve(P,y.invocation.executable));l.has(E)||await Ta({workspacePath:e.workspacePath,invocation:y.invocation,projectBoundary:r,toolAvailable:a.toolAvailable})||b.push(y.invocation.executable);}d.missingExecutables=[...new Set(b)],d.missingExecutables.length>0&&(d.status="partial",d.message=`Required executable(s) unavailable: ${d.missingExecutables.join(", ")}.`);}if(n.length===1){let d=`:${n[0]}:`;for(let g of s.stages)g.id=g.id.replace(d,":");}return s}async function Zt(e={}){let a=i();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 i=e.project.trim(),n=await m(r),s=i.replace(/\\/g,"/").replace(/^\.\//,""),h=c$1.resolve(r,i),l=n.resolved.filter(d=>{let g=x(r,d.projectPath)?Y(r,d.projectPath):void 0;return d.name===i||g===s||c$1.resolve(d.projectPath)===h});if(l.length===0){let d=n.skipped.find(g=>g.name===i);throw d?new Error(`Registered project is unavailable for repair capability inspection: ${i} (${d.reason}).`):new Error(`Registered project not found for repair capability inspection: ${i}.`)}if(l.length>1)throw new Error(`Project reference is ambiguous for repair capability inspection: ${i}.`);t=c$1.resolve(l[0].projectPath),o=l[0].name;}else if(t=c$1.resolve(r,e.projectPath??"."),x(r,t))o=Y(r,t);else {let n=(await m(r)).resolved.find(s=>c$1.resolve(s.projectPath)===t);if(!n)throw new Error("Repair capability inspection external project is not registered in the workspace.");o=n.name;}return {...a,inspection:{projectPath:o,detectedAdapters:await Na(t)}}}function Ce(e){if(e.command){let a=h$1(e.command);if(a)return a}return a$4(e.operation)??void 0}async function ot(e){let a=new Set,r=e.actions[0]?await le(e.workspacePath,e.actions[0]):void 0,t=z(e.actions[0]?.projectPath??"")?e.actions[0]?.projectPath:void 0;for(let o of e.dependencyFiles){let i=await T({workspacePath:e.workspacePath,value:o,projectBoundary:r,projectName:e.actions[0]?.projectName});a.add(Re(e.workspacePath,i,r,t));}for(let o of e.actions){let i=await le(e.workspacePath,o),n=z(o.projectPath??"")?i:e.workspacePath;if(!await K(n,i))throw new Error(`Repair project scope escapes workspace through a symbolic link: ${i}`);let s=o.transaction?.kind==="dependency-materialization"&&o.transaction.sourceMutationRequired===false;for(let d of s?[]:o.files){let g=await T({workspacePath:e.workspacePath,value:d,projectBoundary:z(d)?i:void 0,projectName:o.projectName});if(!await K(n,g))throw new Error(`Repair checkpoint path escapes its canonical project boundary through a symbolic link: ${d}`);a.add(Re(e.workspacePath,g,i,z(o.projectPath??"")?o.projectPath:void 0));}let h=Ce(o);if(!h)continue;let l="path"in h?h.path:void 0;if(l){let d=c$1.resolve(i,l);if(!await K(n,d))throw new Error(`Repair operation target escapes its canonical project boundary through a symbolic link: ${l}`);a.add(Re(e.workspacePath,d,i,z(o.projectPath??"")?o.projectPath:void 0));}}return [...a].filter(o=>o!==".").sort()}async function st(e,a){if(!a.invocation)return;let r=await le(e,a);return v({workspacePath:e,projectPath:r,projectReference:z(a.projectPath??"")?.root,executable:a.invocation.executable,args:a.invocation.args,purpose:"repair"})}function Ve(e){return $(V({sourceEvidenceHash:e.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations??[],stages:e.stages.map(a=>({id:a.id,kind:a.kind,required:a.required,risk:a.risk,...a.invocation?{invocation:a.invocation}:{}})),checkpointFiles:e.checkpointFiles.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,...a.mode!==void 0?{mode:a.mode}:{}}))}))}function Je(e){return Ve({sourceEvidenceHash:e.integrity.sourceEvidenceHash,target:e.target,policy:e.policy,preconditions:e.preconditions,adapterEvaluations:e.adapterEvaluations,stages:e.stages.filter(a=>a.kind!=="rollback"),checkpointFiles:e.checkpoint.files})}function Ba(e){return $(V({transactionId:e.transactionId,state:e.state,planHash:e.integrity.planHash,sourceEvidenceHash:e.integrity.sourceEvidenceHash,approvedPlanHash:e.approval.approvedPlanHash,checkpoint:{status:e.checkpoint.status,files:e.checkpoint.files.map(a=>({path:a.path,existed:a.existed,beforeHash:a.beforeHash,afterHash:a.afterHash??null,...a.mode!==void 0?{mode:a.mode}:{}}))},verification:e.verification}))}async function Qt(e){let a=c$1.resolve(e.workspacePath),r=await pe({workspacePath:a,transactionId:e.transactionId}),t=await We(a,e.transactionId);if(r.state!=="closed"||r.approval.status!=="approved"||r.approval.approvedPlanHash!==r.integrity.planHash||Je(r)!==r.integrity.planHash||!r.integrity.closureHash||Ba(r)!==r.integrity.closureHash||$(V(t))!==r.integrity.sourceEvidenceHash||!ce(t)||t.goalId!==e.goalId||r.verification?.status!=="passed"||r.verification.targetStatus!=="passed"||!r.verification.sourceBinding||r.checkpoint.status!=="captured")throw new Error(`Goal repair transaction is not a current, closed, integrity-bound source transition: ${e.transactionId}`);let o=await ee(a,r);for(let i of r.checkpoint.files){let n=await T({workspacePath:a,value:i.path,projectBoundary:o,projectName:r.target.projectName});if(!x(a,n)&&!(o&&x(o,n)))throw new Error(`Goal repair checkpoint escaped its canonical source boundary: ${i.path}`);let s=await k.lstat(n).catch(()=>{});if(!s){if(i.afterHash!==null)throw new Error(`Goal repair output is no longer current: ${i.path}`);continue}if(!s.isFile()||s.isSymbolicLink())throw new Error(`Goal repair output is no longer a regular source file: ${i.path}`);let h=await k.readFile(n);if(i.afterHash!==$(h))throw new Error(`Goal repair output changed after transaction closure: ${i.path}`);if(i.mode!==void 0&&s.mode!==i.mode)throw new Error(`Goal repair output mode changed after transaction closure: ${i.path}`)}return r.verification.sourceBinding}async function $e(e,a,r){let t=[],o=[],i=0;for(let n of a){let s=await T({workspacePath:e,value:n,projectBoundary:r}),h=r&&x(c$1.resolve(r),s)?c$1.resolve(r):e;if(!x(h,s)){o.push(`Checkpoint path escapes authorized workspace/project boundaries: ${n}`);continue}if(!await K(h,s)){o.push(`Checkpoint path resolves through a link outside its authorized boundary: ${n}`);continue}let l=await k.lstat(s).catch(()=>{});if(l?.isSymbolicLink()){o.push(`Checkpoint refuses symbolic link mutation: ${n}`);continue}if(l&&!l.isFile()){o.push(`Checkpoint target is not a regular file: ${n}`);continue}if(l&&l.size>Aa){o.push(`Checkpoint file exceeds 5 MiB: ${n}`);continue}if(i+=l?.size??0,i>Ka){o.push("Checkpoint exceeds the 25 MiB transaction limit.");break}let d=l?await k.readFile(s):void 0;t.push({path:n,existed:!!l,beforeHash:d?$(d):null,...l?{mode:l.mode}:{}});}return {entries:t,errors:o}}function Fa(e){let a=e.replaceAll("\\","/"),r=a.split("/"),t=r.at(-1)??a;if(a===".workspai-workspace"||a.startsWith(".workspai/"))return "Canonical workspace state and evidence cannot be edited through a model proposal.";if(a===".git"||a.startsWith(".git/"))return "Git internals cannot be edited through a model proposal.";if(r.includes("node_modules"))return "Installed dependency trees cannot be edited through a model proposal.";if(/^\.env(?:\.|$)/i.test(t)&&!/^\.env\.(?:example|sample|template)$/i.test(t))return "Secret-bearing environment files cannot be edited through a model proposal.";if(/\.(?:pem|key|p12|pfx|jks|keystore)$/i.test(t))return "Private key and credential containers cannot be edited through a model proposal."}function it(e,a){if(!(!/\.json$/i.test(e)||a===void 0))try{JSON.parse(a);return}catch{return `${e} must contain valid JSON; comments and trailing syntax are not allowed.`}}async function nt(e){let a=await k.readJson(c$1.join(e,".workspai-workspace")).catch(()=>{});return typeof a?.name=="string"&&a.name.trim()?a.name.trim():c$1.basename(e)}function ct(e){return Ua.has(e)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(e)}async function dt(e,a){let r=c$1.resolve(e,a),t=c$1.dirname(r);for(;x(e,t);){if((await k.readdir(t).catch(()=>[])).some(ct))return t;if(c$1.resolve(t)===c$1.resolve(e))break;t=c$1.dirname(t);}return e}function lt(e,a,r){return r.some(t=>{let o=c$1.resolve(e,t.path);if(!x(a,o))return false;let i=c$1.basename(o);return Ya.has(i)||/\.(?:cs|fs|vb)proj$|\.sln$/i.test(i)})}function pt(e){let a=!x(e.workspacePath,e.projectPath)&&e.proposal.projectName?`external/${e.proposal.projectName}`:Y(e.workspacePath,e.projectPath,e.projectPath);return {id:`proposal:${e.proposal.cardId}:${a}`,artifactKind:"workspace-repair-proposal",cardId:e.proposal.cardId,findingId:e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal",findingStatus:"blocking",causalKey:[e.proposal.cardId,e.proposal.projectName??a,e.proposal.targetActionIds?.[0]??e.proposal.blockerSignature??"proposal"].map(r=>r.trim().toLowerCase()).join(":"),title:"Validate model-proposed repair",order:1,phase:"source-repair",scope:a==="."?"workspace":"project",...e.proposal.projectName?{projectName:e.proposal.projectName}:{},...a!=="."?{projectPath:a}:{},status:"ready",mode:"edit-file",risk:"guarded",requiresApproval:true,blocker:"",summary:e.proposal.rationale,verifyCommand:"workspai workspace intelligence run --for-agent generic --strict --json",cwd:a==="."?"workspace":"project",files:e.proposal.changes.map(r=>r.path),rollback:{available:true,strategy:"idempotent"},notes:["Source changes are applied only by the CLI Repair Engine after hash-bound approval."]}}function ut(e,a){let r=Te(a.executable),[t="",o=""]=a.args;if(a.args.some(s=>/^(?:-e|--eval|-c|--command|-command)$/i.test(s)))throw new Error(`Validation ${e.id} cannot execute inline program text.`);let i=["npm","pnpm","yarn","bun"].includes(r);if(!(i&&e.kind==="audit"&&a.args.some(s=>/audit/i.test(s))||i&&["test","build"].includes(e.kind)&&(t==="run"||t===e.kind||o===e.kind)||["pytest","pip-audit","govulncheck","bundle-audit"].includes(r)||["python","python3","py"].includes(r)&&t==="-m"&&["pytest","unittest","build","pip_audit"].includes(o.replaceAll("-","_"))||r==="poetry"&&["run","check"].includes(t)||r==="uv"&&t==="run"||r==="go"&&["test","build","vet"].includes(t)||r==="cargo"&&["test","build","check","audit"].includes(t)||r==="composer"&&["audit","run-script","validate"].includes(t)||r==="bundle"&&t==="exec"&&o==="rake"||r==="dotnet"&&["test","build"].includes(t)||["mvn","mvnw","gradle","gradlew"].includes(r)&&a.args.some(s=>/^(?:test|build|check|verify|package)$/i.test(s))||r==="mix"&&(t==="test"||t==="compile"||t==="hex.audit"&&e.kind==="audit")||r==="clojure"&&t==="-M:test"&&e.kind==="test"||r==="lein"&&(t==="test"&&e.kind==="test"||t==="uberjar"&&e.kind==="build")||r==="sbt"&&(t==="test"&&e.kind==="test"||t==="package"&&e.kind==="build")||r==="deno"&&(t==="test"||t==="task"&&["test","build"].includes(o))))throw new Error(`Validation ${e.id} must use a runtime-native audit, test, or build command; arbitrary executables are not accepted from a model.`)}async function ht(e){let a=[],r=new Set,t=[],o=[],i=new Set,n=e.proposal.projectPath?c$1.resolve(e.workspacePath,e.proposal.projectPath):void 0;for(let s of e.proposal.validation??[]){let h=c$1.resolve(e.workspacePath,s.cwd),l=Y(e.workspacePath,h,n),d=await k.lstat(h).catch(()=>{});if(!d?.isDirectory()||d.isSymbolicLink()||!await K(n??e.workspacePath,h)){t.push(`Validation ${s.id} requires a real directory inside the workspace.`);continue}if(n&&!x(n,h)){t.push(`Validation ${s.id} escapes the declared project scope.`);continue}if(G[s.risk]>G[e.maxRisk]){t.push(`Validation ${s.id} exceeds the approved ${e.maxRisk} risk ceiling.`);continue}let g=v({workspacePath:e.workspacePath,projectPath:h,executable:s.executable,args:s.args,purpose:s.kind,timeoutMs:s.timeoutMs});try{Ue(e.workspacePath,g,e.policy,e.projectRoots),ut(s,g);}catch(b){t.push(b instanceof Error?b.message:String(b));continue}a.push(R({id:`validation:${s.id}`,kind:s.kind,risk:s.risk,required:s.required,summary:s.summary,invocation:g})),i.add(`${l}:${s.kind}`);}for(let s of e.projectRoots){let h=pt({workspacePath:e.workspacePath,projectPath:s,proposal:e.proposal}),l=await Da({workspacePath:e.workspacePath,action:h,authorizedProjectRoot:s},e.dependencies);o.push(...l.adapters);let d=lt(e.workspacePath,s,e.proposal.changes);if(d){for(let b of l.checkpointFiles)r.add(b);t.push(...l.blockers);}let g=Y(e.workspacePath,s,s);for(let b of l.stages)!d&&!["test","build"].includes(b.kind)||i.has(`${g}:${b.kind}`)||a.push(b);}return {stages:[...new Map(a.map(s=>[s.id,s])).values()],checkpointFiles:[...r],blockers:[...new Set(t)],adapters:[...new Map(o.map(s=>[`${s.projectPath}:${s.adapterId}`,s])).values()]}}async function gt(e,a$3={}){let r=c$1.resolve(e.workspacePath),t=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true,toolAvailable:a$3.toolAvailable}),o=t.actions.filter(u=>u.cardId===e.cardId).filter(u=>!e.projectName||!u.projectName||u.projectName===e.projectName).sort((u,C)=>u.order-C.order||u.id.localeCompare(C.id)),i=e.actionId?o.filter(u=>u.id===e.actionId):o,n=t.actions.filter(u=>!e.projectName||!u.projectName||u.projectName===e.projectName).sort((u,C)=>u.order-C.order||u.id.localeCompare(C.id)),s=new Map(n.map(u=>[u.id,u])),h=u=>{let C=new Set(u.map(ae=>ae.id)),O=[...u];for(;O.length>0;){let ae=O.pop();for(let _ of ae?.dependsOn??[]){let te=s.get(_);!te||C.has(te.id)||(C.add(te.id),O.push(te));}}return n.filter(ae=>C.has(ae.id))},l=i.filter(u=>u.findingStatus==="blocking"||u.notes.includes("Doctor finding status: blocking")),d=l.length>0?l:i.filter(u=>u.findingStatus!=="informational"),g=e.actionId?i.filter(u=>u.id===e.actionId):[],b$1=[...d].sort((u,C)=>{let O=u.status==="ready"||u.status==="review-required"?0:1,ae=C.status==="ready"||C.status==="review-required"?0:1;return O-ae||u.order-C.order||u.id.localeCompare(C.id)})[0],y=b$1?d.filter(u=>u.cardId===b$1.cardId&&u.findingId===b$1.findingId&&u.causalKey===b$1.causalKey&&u.projectName===b$1.projectName&&u.projectPath===b$1.projectPath):[],P=h(e.actionId?g:y),E=e.maxRisk??"guarded",q={maxRisk:E,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},f=[{id:"workspace-root",status:await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"))?"passed":"failed",message:"Workspace root markers must exist."},{id:"actions-selected",status:P.length>0?"passed":"failed",message:P.length>0?`${P.length} governed action(s) selected.`:"No governed remediation action matches this target."}],m=Ca(P);m&&f.push(m);let w=[],D=[],J=[],W=[],F=[],B=new Set(["replan","manual-repair","cancel"]);for(let u of P){let C=Ce(u),O=await st(r,u);if(G[u.risk]<=G[E]||(W.push(`${u.id} exceeds the approved ${E} risk ceiling.`),B.add(u.risk==="invasive"?"approve-invasive":"approve-guarded")),(u.status==="blocked"||u.status==="guidance-only")&&W.push(`${u.id} is ${u.status}: ${u.blocker}`),!C&&!O&&(u.mode==="run-command"||u.mode==="edit-file")&&(W.push(`${u.id} has no typed operation or structured invocation.`),F.push(u.id)),O)try{Ue(r,O,q);}catch(_){let te=_ instanceof Error?_.message:String(_);W.push(te),/Force-based/.test(te)&&B.add("allow-force"),/Breaking dependency/.test(te)&&B.add("allow-breaking");}if(w.push({id:`action:${u.id}`,kind:"repair",status:C||O?"pending":"blocked",required:true,risk:u.risk,summary:u.summary,...O?{invocation:O}:{}}),u.transaction){let _=await Da({workspacePath:r,action:u},a$3);w.push(..._.stages),D.push(..._.checkpointFiles),W.push(..._.blockers),J.push(..._.adapters);}}let oe=[...new Map(w.map(u=>[u.id,u])).values()];w.splice(0,w.length,...oe),w.unshift({id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."}),w.push({id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."}),w.push({id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}),f.push(...await Ke({workspacePath:r,stages:w,toolAvailable:a$3.toolAvailable}));let X=await ot({workspacePath:r,actions:P,dependencyFiles:D}),ue=P[0]?await le(r,P[0]):void 0,Z=await $e(r,X,ue);f.push({id:"rollback-coverage",status:P.some(u=>u.mode==="edit-file"||u.mode==="run-command")&&X.length===0?"failed":"passed",message:X.length>0?`${X.length} bounded rollback candidate(s) identified.`:"No source file mutation is declared."}),f.push({id:"structured-execution",status:F.length>0?"failed":"passed",message:F.length>0?`Executable actions without typed execution: ${F.join(", ")}.`:"Every executable action uses a typed operation or structured invocation."}),f.push({id:"checkpoint-boundary",status:Z.errors.length===0?"passed":"failed",message:Z.errors.length===0?"Every mutable path is bounded, regular, size-limited, and hash-pinned.":Z.errors.join(" ")});let L=$(V(t)),je=[...new Set(P.map(u=>u.projectPath).filter(Boolean))],ie=[...new Set(P.map(u=>u.projectName).filter(Boolean))],ke=ie.length===1?ie[0]:void 0,he=je.length===1&&ie.length<=1,we={cardId:e.cardId,scope:he?"project":"workspace",...ke?{projectName:ke}:{},...je.length===1?{projectPath:je[0]}:{},actionIds:P.map(u=>u.id)},xe=M(a$3.now),U=`repair_${randomUUID().replaceAll("-","")}`,ge=f.some(u=>u.status==="failed")||W.length>0,Ie=[...W,...f.filter(u=>u.status==="failed").map(u=>u.message)],p=[...new Map(J.map(u=>[`${u.projectPath}:${u.adapterId}`,u])).values()],N=$a({actions:P,adapters:p,preconditions:f,stages:w,decisionOptions:B,maxRisk:E,fallbackReasons:Ie}),S={schemaVersion:a,transactionId:U,revision:1,createdAt:xe,updatedAt:xe,workspace:{name:t.workspace.name,rootRef:"."},target:we,state:ge?"decision-required":"awaiting-approval",policy:q,approval:{required:true,status:"pending"},preconditions:f,adapterEvaluations:p,checkpoint:{status:X.length>0?"pending":"unavailable",files:Z.entries},stages:w,...ge?{decision:{reason:[...new Set(Ie)].join(" "),options:[...B],causes:N}}:{},events:[],integrity:{sourceEvidenceHash:L,planHash:Ve({sourceEvidenceHash:L,target:we,policy:q,preconditions:f,adapterEvaluations:p,stages:w,checkpointFiles:Z.entries})}};A(S,"planned",ge?"Repair plan requires an engineering decision.":"Repair plan is ready for explicit approval.",{now:a$3.now}),a$1(S,c,"Workspace repair transaction");let ne=await Sa(r,S);if(ne)return ne;let Ne=de(r,U);return await k.ensureDir(Ne),await re(ze(r,U),t),await re(Se(r,U),S),await re(c$1.join(r,b),S),S}async function ft(e,a={}){let r=e.proposal.goalId;if(!r)return Ra(e,a);let t=c$1.resolve(e.workspacePath);return f(t,`.workspai/goals/${r}/repair-proposal`,()=>Ra({...e,workspacePath:t},a))}async function Ra(e,a$3={}){a$1(e.proposal,f$1,"Workspace repair proposal");let r=c$1.resolve(e.workspacePath),t=JSON.parse(JSON.stringify(e.proposal));if(t.goalId){let p=await l({workspacePath:r,goalId:t.goalId});if(!p.active||p.index.activeGoalId!==t.goalId)throw new Error(`Repair proposal Goal Pack is not active: ${t.goalId}`);if(p.goalPack?.state!=="ready-to-plan")throw new Error(`Repair proposal Goal Pack is not ready for proposal execution: ${p.goalPack?.state??"missing"}`);if((p.active.repairTransactionIds??(p.active.repairTransactionId?[p.active.repairTransactionId]:[])).length>=p.goalPack.policy.maxAttempts)throw new Error(`Goal ${t.goalId} exhausted its repair proposal budget (${p.goalPack.policy.maxAttempts}). Review the latest evidence before creating another Goal Pack.`);if(p.goalPack.scope.kind==="project"||p.goalPack.scope.kind==="project-set"){let S=p.goalPack.scope.projects;if(!t.projectName||!S.includes(t.projectName))throw new Error(p.goalPack.scope.kind==="project"?`Goal-bound repair must declare the exact permitted projectName (${S[0]}).`:`Goal-bound repair must declare a projectName inside the permitted Goal scope (${S.join(", ")}).`)}}let o=e.maxRisk??"guarded",i={maxRisk:o,allowForce:e.allowForce===true,allowBreaking:e.allowBreaking===true,autoRollback:e.autoRollback!==false,strictVerify:true},n=[],s=[],h=new Set(["replan","manual-repair","cancel"]),l$1=await k.pathExists(c$1.join(r,".workspai-workspace"))||await k.pathExists(c$1.join(r,".workspai"));n.push({id:"workspace-root",status:l$1?"passed":"failed",message:l$1?"Canonical workspace root markers exist.":"Workspace root markers must exist."});let d;try{d=await et({workspacePath:r,proposal:t});}catch(p){s.push(p instanceof Error?p.message:String(p));}let g=d&&!x(r,d)&&t.projectName?`external/${t.projectName}`:void 0;if(d&&(t.projectName||t.projectPath)&&(t.projectPath=g??c$1.relative(r,d).split(c$1.sep).join("/")),t.projectPath){let p=d??c$1.resolve(r,t.projectPath),N=await k.lstat(p).catch(()=>{});(!N?.isDirectory()||N.isSymbolicLink())&&s.push("The declared project path must be a real canonical registered project directory.");}t.validation=t.validation?.map(p=>({...p,cwd:Re(r,p.cwd,d,g)}));let b$1=new Set,y=new Set,P=0;for(let p of t.changes){p.path=Re(r,p.path,d,g),p.path==="."&&s.push(`${p.id} cannot replace the workspace root.`),b$1.has(p.id)&&s.push(`Duplicate proposal change id: ${p.id}.`),y.has(p.path)&&s.push(`Multiple proposal changes target ${p.path}.`),b$1.add(p.id),y.add(p.path),P+=Buffer.byteLength(p.content??"","utf8"),P>Va&&s.push("The model proposal exceeds the 25 MiB source-change limit.");let N=Fa(p.path);if(N&&s.push(`${p.path}: ${N}`),p.operation==="write"){let S=it(p.path,p.content);S&&s.push(S);}if(G[p.risk]>G[o]&&(s.push(`${p.id} exceeds the approved ${o} risk ceiling.`),h.add(p.risk==="invasive"?"approve-invasive":"approve-guarded")),t.projectPath){let S=d??await T({workspacePath:r,value:t.projectPath,projectName:t.projectName}),ne=await T({workspacePath:r,value:p.path,projectBoundary:S,projectName:t.projectName});x(S,ne)||s.push(`${p.path} escapes the declared project scope.`);}}let E=[...y].sort(),q=await $e(r,E,d);s.push(...q.errors);let f=new Map(q.entries.map(p=>[p.path,p]));for(let p of t.changes){let N=f.get(p.path);if(!N||N.beforeHash!==p.expectedBeforeHash){s.push(`${p.path} no longer matches the model's expected source hash; refresh context and re-propose.`);continue}p.operation==="delete"&&!N.existed&&s.push(`${p.path} cannot be deleted because it does not exist.`),p.operation==="write"&&N.beforeHash!==null&&$(p.content??"")===N.beforeHash&&s.push(`${p.path} is a no-op and cannot prove source progress.`);}n.push({id:"proposal-boundary",status:s.length===0?"passed":"failed",message:s.length===0?`${t.changes.length} unique, bounded, hash-pinned source change(s) validated.`:[...new Set(s)].join(" ")});let m=new Set;if(t.projectPath)m.add(d??c$1.resolve(r,t.projectPath));else for(let p of t.changes)m.add(await dt(r,p.path));let w=await ht({workspacePath:r,proposal:t,projectRoots:[...m].sort(),maxRisk:o,policy:i,dependencies:a$3});s.push(...w.blockers);let D=w.stages,J=D.some(p=>p.status!=="skipped"&&["audit","test","build"].includes(p.kind));n.push({id:"validation-coverage",status:J?"passed":"unknown",message:J?"Runtime-native validation is included before canonical verification.":"No runtime-native test, build, or audit command was discovered; strict canonical verification remains mandatory."});let W=[...new Set([...E,...w.checkpointFiles])].sort(),F=await $e(r,W,d);s.push(...F.errors),n.push({id:"checkpoint-boundary",status:F.errors.length===0?"passed":"failed",message:F.errors.length===0?`${F.entries.length} mutable path(s) are bounded and hash-pinned for rollback.`:F.errors.join(" ")});let B=[{id:"target-precondition",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer and prove the approved causal target is still current before mutation."},...t.changes.map(p=>({id:`proposal:${p.id}`,kind:"repair",status:G[p.risk]<=G[o]?"pending":"blocked",required:true,risk:p.risk,summary:p.summary,changedPaths:[p.path]})),...D,{id:"target-producer-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Refresh the exact producer that owns the selected repair card."},{id:"canonical-verify",kind:"verify",status:"pending",required:true,risk:"safe",summary:"Run the complete canonical Workspace Intelligence loop in strict mode."}];n.push(...await Ke({workspacePath:r,stages:B,toolAvailable:a$3.toolAvailable}));let oe=new Set(B.map(p=>p.id));oe.size!==B.length&&s.push("Repair proposal stage ids must be unique."),n.push({id:"stage-identity",status:oe.size===B.length?"passed":"failed",message:oe.size===B.length?"Every repair and validation stage has a stable unique identity.":"Repair proposal stage ids collide."});try{let p=false,N=await a$2({workspacePath:r,includeAbsolutePaths:false,ciMode:true}),S=N.actions.filter(I=>I.cardId===t.cardId&&(!t.projectName||I.projectName===t.projectName)&&(!t.projectPath||I.projectPath===t.projectPath));if(!t.targetActionIds?.length){let I=Pa(S);I.size===1?t.targetActionIds=S.map(Ma=>Ma.id).sort():I.size>1&&(p=true,s.push(`Repair proposal target is ambiguous: ${I.size} independent causal finding families match card ${t.cardId}. Select one canonical action set before proposing source changes.`));}let ne=[...new Set(t.targetActionIds??[])],Ne=new Set(ne),u=N.actions.filter(I=>Ne.has(I.id)),C=new Set(u.map(I=>I.id)),O=ne.filter(I=>!C.has(I));O.length>0&&(p=true,s.push(`Repair proposal references stale or unknown causal action ids: ${O.join(", ")}.`)),u.filter(I=>I.cardId!==t.cardId||t.projectName!==void 0&&I.projectName!==t.projectName||t.projectPath!==void 0&&I.projectPath!==t.projectPath).length>0&&(p=true,s.push("Repair proposal causal actions do not belong to the declared card and project scope."));let _=Pa(u);_.size>1&&(p=true,s.push(`Repair proposal combines ${_.size} independent causal finding families. Create one transaction per finding family.`)),u.length>0&&!t.blockerSignature&&(p=true,s.push("Repair proposal must include the blockerSignature generation inspected by the model.")),new Set(u.map(I=>I.projectName??I.projectPath).filter(I=>!!I)).size>0&&!t.projectName&&!t.projectPath&&(p=true,s.push("Project-scoped causal actions require an explicit canonical projectName or projectPath.")),u.length>0&&u.every(I=>I.mode==="run-command"&&I.transaction?.kind==="dependency-materialization"&&I.transaction.sourceMutationRequired===false)&&(p=true,s.push("The selected causal action is command-owned and declares that source mutation is not required. Execute the canonical action instead of submitting a model source proposal.")),n.push({id:"causal-target-binding",status:!p&&(u.length>0||S.length===0)?"passed":"failed",message:u.length>0?`${u.length} action(s) bind this proposal to one canonical causal target.`:S.length===0?"No canonical remediation action exists; the bounded source proposal remains the explicit target.":"A single canonical causal target is required before source mutation."});let Ye=Ca(u);Ye&&n.push(Ye);}catch{}let X=$(V(t)),ue={cardId:t.cardId,scope:t.projectPath||t.projectName?"project":"workspace",...t.projectName?{projectName:t.projectName}:{},...t.projectPath?{projectPath:t.projectPath}:{},...t.blockerSignature?{blockerSignature:t.blockerSignature}:{},actionIds:t.targetActionIds&&t.targetActionIds.length>0?[...new Set(t.targetActionIds)].sort():t.changes.map(p=>`proposal:${p.id}`)},Z=M(a$3.now),L=`repair_${randomUUID().replaceAll("-","")}`,ie=n.some(p=>p.status==="failed")||s.length>0,ke=[...s,...n.filter(p=>p.status==="failed"&&p.id!=="proposal-boundary").map(p=>p.message)],he=$a({adapters:w.adapters,preconditions:n,stages:B,decisionOptions:h,maxRisk:o,fallbackReasons:ke});for(let p of t.changes)G[p.risk]<=G[o]||he.push({kind:"risk-approval",id:`risk:${p.id}`,message:`${p.id} exceeds the approved ${o} risk ceiling.`,...t.projectPath?{projectPath:t.projectPath}:{}});let we=he.length>0&&he.every(p=>p.kind==="failed-precondition")&&n.some(p=>p.id==="proposal-boundary"&&p.status==="failed"),xe=we?["replan","cancel"]:[...h],U={schemaVersion:a,transactionId:L,revision:1,createdAt:Z,updatedAt:Z,workspace:{name:await nt(r),rootRef:"."},target:ue,state:ie?"decision-required":"awaiting-approval",policy:i,approval:{required:true,status:"pending"},preconditions:n,adapterEvaluations:w.adapters,checkpoint:{status:"pending",files:F.entries},stages:B,...ie?{decision:{reason:[...new Set(ke)].join(" "),options:xe,causes:he}}:{},events:[],integrity:{sourceEvidenceHash:X,planHash:Ve({sourceEvidenceHash:X,target:ue,policy:i,preconditions:n,adapterEvaluations:w.adapters,stages:B,checkpointFiles:F.entries})}};A(U,"planned",ie?we?"Model-proposed repair was rejected before mutation and requires causal replanning.":"Model-proposed repair requires an engineering decision.":"Model-proposed source repair is bounded and ready for explicit approval.",{now:a$3.now}),a$1(U,c,"Workspace repair transaction");let ge=await Sa(r,U);if(ge)return ge;let Ie=de(r,L);return await k.ensureDir(Ie),await re(ze(r,L),t),await re(Se(r,L),U),await re(c$1.join(r,b),U),t.goalId&&await p({workspacePath:r,goalId:t.goalId,transactionId:L}),U}async function er(e,a={}){let r=await pe(e);if(r.state!=="awaiting-approval")throw new Error(`Repair transaction is not awaiting approval: ${r.state}`);if(Je(r)!==r.integrity.planHash)return r.approval.status="expired",r.state="decision-required",r.decision=H("The compiled repair plan changed after planning.",["cancel"]),await j(e.workspacePath,r,a.now),r;let t=await We(e.workspacePath,e.transactionId);return $(V(t))!==r.integrity.sourceEvidenceHash?(r.approval.status="expired",r.state="decision-required",r.decision=H("The persisted source plan changed after planning.",["cancel"]),await j(e.workspacePath,r,a.now),r):(r.approval={required:true,status:"approved",approvedAt:M(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 j(e.workspacePath,r,a.now),r)}async function Oa(e,a){let r=c$1.join(e,Ge,za);await k.ensureDir(c$1.dirname(r));try{let t=await k.stat(r),o=await k.readJson(r).catch(()=>({})),i=typeof o.host=="string"?o.host:void 0,n=typeof o.pid=="number"&&Number.isSafeInteger(o.pid)&&o.pid>0?o.pid:void 0,s=false;if((!i||i===hostname())&&n)try{process.kill(n,0),s=true;}catch(l){s=l!==null&&typeof l=="object"&&"code"in l&&l.code==="EPERM";}let h=!!(i&&i!==hostname());!s&&!h&&Date.now()-t.mtimeMs>Ja&&await k.remove(r);}catch{}try{await k.outputFile(r,`${JSON.stringify({transactionId:a,pid:process.pid,host:hostname(),acquiredAt:new Date().toISOString()})}
2
+ `,{flag:"wx"});}catch{throw new Error("Another workspace repair transaction currently owns the engine lock.")}return async()=>{(await k.readJson(r).catch(async()=>{let o=await k.readFile(r,"utf8").catch(()=>"");try{return JSON.parse(o)}catch{return {}}})).transactionId===a&&await k.remove(r);}}async function Ha(e){let a=await ee(e.workspacePath,e.transaction),r=await $e(e.workspacePath,e.transaction.checkpoint.files.map(o=>o.path),a);if(r.errors.length>0)throw new Error(r.errors.join(" "));let t=new Map(r.entries.map(o=>[o.path,o]));for(let o of e.transaction.checkpoint.files){let i=t.get(o.path);if(!i||o.existed!==i.existed||o.beforeHash!==i.beforeHash||o.mode!==i.mode)throw new Error(`Checkpoint precondition changed after planning: ${o.path}. Create and approve a fresh plan.`)}}async function mt(e){if(e.transaction.checkpoint.status==="captured")return;await Ha(e);let a=c$1.join(de(e.workspacePath,e.transaction.transactionId),ba);await k.ensureDir(a);for(let r=0;r<e.transaction.checkpoint.files.length;r+=1){let t=e.transaction.checkpoint.files[r],o=await ee(e.workspacePath,e.transaction),i=await T({workspacePath:e.workspacePath,value:t.path,projectBoundary:o,projectName:e.transaction.target.projectName}),n=t.existed?await k.readFile(i):void 0;if(n&&$(n)!==t.beforeHash)throw new Error(`Checkpoint source changed while it was being captured: ${t.path}. Create and approve a fresh plan.`);let s=`${ba}/${String(r).padStart(4,"0")}.bin`;if(n){let h=c$1.join(de(e.workspacePath,e.transaction.transactionId),s),l=`${h}.${process.pid}.${randomUUID()}.tmp`;await k.writeFile(l,n,{flag:"wx"});let d=await k.readFile(l);if($(d)!==t.beforeHash)throw await k.remove(l),new Error(`Checkpoint backup verification failed for ${t.path}.`);await k.move(l,h,{overwrite:true}),t.backupRef=s;}}e.transaction.checkpoint.status="captured",e.transaction.checkpoint.capturedAt=M(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 ja(e,a){let r=await ee(e,a);for(let t of a.checkpoint.files){let o=await T({workspacePath:e,value:t.path,projectBoundary:r,projectName:a.target.projectName}),i=await k.readFile(o).catch(()=>{});t.afterHash=i?$(i):null;}}function Te(e){return c$1.posix.basename(e.replaceAll("\\","/")).toLowerCase().replace(/\.(?:bat|cmd|exe)$/i,"")}function Ue(e,a,r,t=[]){let o=c$1.resolve(e,a.cwd);if(!(x(e,o)||t.some(l=>x(l,o))))throw new Error(`Invocation cwd escapes authorized repair boundaries: ${a.cwd}`);if(a.args.length>100||a.args.some(l=>!l||/[\0\r\n]/.test(l)))throw new Error("Invocation contains invalid arguments.");let n=Te(a.executable),s=c$1.isAbsolute(a.executable),h=/^\.{1,2}[\\/]/.test(a.executable);if(s&&!x(e,a.executable)&&!t.some(l=>x(l,a.executable)))throw new Error(`Invocation executable escapes authorized repair boundaries: ${a.executable}`);if(!s&&!h&&!Xa.has(n))throw new Error(`Invocation executable is not governed: ${a.executable}`);if(!r.allowForce&&a.args.some(l=>/^(?:--force|-f)$/i.test(l)))throw new Error("Force-based repair requires explicit allowForce policy approval.");if(!r.allowBreaking&&a.args.some(l=>/(?:breaking|legacy-peer-deps)/i.test(l)))throw new Error("Breaking dependency repair requires explicit allowBreaking policy approval.");if(["npx","pnpx","bunx"].includes(n)&&!a.args.includes("--no-install")&&!a.args.includes("--no"))throw new Error(`${n} cannot fetch an unreviewed package during autonomous repair.`);return {cwd:o,executable:a.executable}}async function Le(e){let a=e.projectBoundary?[c$1.resolve(e.projectBoundary)]:[],r=await T({workspacePath:e.workspacePath,value:e.invocation.cwd,projectBoundary:e.projectBoundary}),t=Ue(e.workspacePath,{...e.invocation,cwd:r},e.policy,a),o=await k.lstat(t.cwd).catch(()=>{});if(!o?.isDirectory()||o.isSymbolicLink()||!await K(e.projectBoundary??e.workspacePath,t.cwd))throw new Error(`Invocation cwd is not a real workspace directory: ${e.invocation.cwd}`);if(c$1.isAbsolute(t.executable)||/^\.{1,2}[\\/]/.test(t.executable)){let s=c$1.isAbsolute(t.executable)?t.executable:c$1.resolve(t.cwd,t.executable);if(!await K(e.projectBoundary??e.workspacePath,s))throw new Error(`Invocation executable resolves outside the workspace: ${e.invocation.executable}`)}let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(s))),n=await execa(t.executable,e.invocation.args,{cwd:t.cwd,shell:false,reject:false,timeout:e.invocation.timeoutMs,maxBuffer:Ea,stdin:"ignore",extendEnv:false,env:{...i,NO_COLOR:"1",CI:process.env.CI??"1"}});return {exitCode:n.exitCode??null,stdout:n.stdout??"",stderr:n.stderr??""}}function kt(e){let a=k$1.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 wt(e){let a=k$1.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 k.pathExists(r))throw new Error("The running Workspai CLI entrypoint is unavailable for target verification.");let t=a.scope==="project"&&e.transaction.target.projectPath?await T({workspacePath:e.workspacePath,value:e.transaction.target.projectPath,projectName:e.transaction.target.projectName}):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.`);let o=a.scope==="project"?t:e.workspacePath;if(!await K(o,t))throw new Error("The target producer working directory escapes the workspace boundary.");let i=c$1.resolve(t,a.producerArtifact);if(!x(t,i)||!await K(t,c$1.dirname(i)))throw new Error("The target producer artifact escapes its canonical scope.");let n=await k.stat(i).catch(()=>{}),s=Object.fromEntries(Object.entries(process.env).filter(([d])=>!/(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|COOKIE|AUTH)/i.test(d))),h=await execa(process.execPath,[r,...kt(a.cardId)],{cwd:t,shell:false,reject:false,timeout:15*6e4,maxBuffer:Ea,stdin:"ignore",extendEnv:false,env:{...s,NO_COLOR:"1",CI:process.env.CI??"1"}}),l=await k.stat(i).catch(()=>{});return {exitCode:h.exitCode??null,stdout:h.stdout??"",stderr:h.stderr??"",evidenceProduced:!!(l?.isFile()&&(!n||l.mtimeMs!==n.mtimeMs||l.ctimeMs!==n.ctimeMs||l.size!==n.size))}}async function bt(e){if(e.dependencies.targetVerify)return e.dependencies.targetVerify({workspacePath:e.workspacePath,transaction:e.transaction});if(e.dependencies.verify)return {status:e.workspaceStatus==="passed"?"passed":"failed",remainingActionIds:e.workspaceStatus==="passed"?[]:[...e.transaction.target.actionIds]};if(e.workspaceStatus==="failed")return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]};try{let a=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),r=new Set(e.transaction.target.actionIds),t=ce(e.sourcePlan)&&Array.isArray(e.sourcePlan.targetActionIds)&&e.sourcePlan.targetActionIds.length>0,o=ce(e.sourcePlan)?a.actions.filter(i=>t?r.has(i.id):i.cardId===e.transaction.target.cardId&&(!e.transaction.target.projectName||i.projectName===e.transaction.target.projectName)&&(!e.transaction.target.projectPath||i.projectPath===e.transaction.target.projectPath)):a.actions.filter(i=>r.has(i.id));return {status:o.length===0?"passed":"failed",remainingActionIds:o.map(i=>i.id).sort()}}catch{return {status:"unknown",remainingActionIds:[...e.transaction.target.actionIds]}}}async function vt(e){if(e.dependencies.verify||e.dependencies.targetVerify)return {current:true,missingActionIds:[],semanticDrift:false};let a=e.transaction.target.actionIds.filter(h=>!h.startsWith("proposal:"));if(a.length===0)return {current:true,missingActionIds:[],semanticDrift:false};let r=await a$2({workspacePath:e.workspacePath,includeAbsolutePaths:false,ciMode:true}),t=new Set(r.actions.map(h=>h.id)),o=a.filter(h=>!t.has(h)),i=e.transaction.preconditions.map(h=>h.id).find(h=>h.startsWith(_e))?.slice(_e.length),n=r.actions.filter(h=>t.has(h.id)&&a.includes(h.id)),s=o.length===0&&!!i&&Wa(n)!==i;return {current:o.length===0&&!s,missingActionIds:o,semanticDrift:s}}function Q(e,a=8e3){return e.length<=a?e:`\u2026[truncated]\u2026
3
+ ${e.slice(-a)}`}async function Pt(e,a){if(a.type==="file-create")return m$1({projectPath:e,operation:a});if(a.type==="file-append")return n({projectPath:e,operation:a});if(a.type==="file-copy")return o({projectPath:e,operation:a});if(a.type==="package-json-script")return l$1({projectPath:e,packageJsonPath:a.path,scriptName:a.scriptName,scriptValue:a.scriptValue});if(a.type==="json-edit")return q({projectPath:e,operation:a});if(a.type==="env-key-add")return r({projectPath:e,operation:a});if(a.type==="makefile-target")return s({projectPath:e,operation:a})}async function yt(e){let a=await ee(e.workspacePath,e.transaction)??e.workspacePath,r=await T({workspacePath:e.workspacePath,value:e.change.path,projectBoundary:a,projectName:e.transaction.target.projectName});if(!x(a,r)||!await K(a,r))throw new Error(`Proposal target escaped the canonical repair boundary: ${e.change.path}`);let t=Fa(e.change.path);if(t)throw new Error(`${e.change.path}: ${t}`);let o=e.transaction.checkpoint.files.find(g=>g.path===e.change.path);if(!o)throw new Error(`Proposal target is missing from the checkpoint: ${e.change.path}`);let i=await k.readFile(r).catch(()=>{}),n=i?$(i):null;if(n!==o.beforeHash||n!==e.change.expectedBeforeHash)throw new Error(`Proposal target changed before execution: ${e.change.path}`);let s=await k.lstat(r).catch(()=>{});if(s?.isSymbolicLink()||s&&!s.isFile())throw new Error(`Proposal target must be a regular file: ${e.change.path}`);if(e.change.operation==="delete"){if(!s)throw new Error(`Proposal delete target does not exist: ${e.change.path}`);await k.remove(r);return}let h=e.change.content??"";if(Buffer.byteLength(h,"utf8")>Aa)throw new Error(`Proposal write exceeds the 5 MiB file limit: ${e.change.path}`);await k.ensureDir(c$1.dirname(r));let l=c$1.join(c$1.dirname(r),`.${c$1.basename(r)}.${process.pid}.${randomUUID()}.repair-tmp`);await k.writeFile(l,h,{encoding:"utf8",flag:"wx"}),await k.move(l,r,{overwrite:true});let d=await k.readFile(r);if($(d)!==$(h))throw new Error(`Proposal write could not be verified: ${e.change.path}`)}async function xa(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=M(e.dependencies.now),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"running",now:e.dependencies.now}),await j(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:""}):wt))({workspacePath:e.workspacePath,transaction:e.transaction});e.stage.exitCode=r.exitCode,e.stage.stdoutTail=Q(r.stdout),e.stage.stderrTail=Q(r.stderr);let t=r.exitCode===2||r.exitCode===1&&"evidenceProduced"in r&&r.evidenceProduced===true;if(r.exitCode!==0&&!t){let o=Q(r.stderr||r.stdout,600).replace(/\s+/g," ").trim();throw new Error(o?`Exact card producer failed with exit ${String(r.exitCode)}: ${o}`:`Exact card producer failed with exit ${String(r.exitCode)} without refreshing its canonical artifact.`)}if(e.stage.id==="target-precondition"){let o=await vt({workspacePath:e.workspacePath,transaction:e.transaction,dependencies:e.dependencies});if(!o.current){let i=o.semanticDrift?"The selected action semantics changed after approval.":`Missing action(s): ${o.missingActionIds.join(", ")}.`;throw new Error(`The approved causal repair target changed before mutation. ${i} Create and approve a fresh plan.`)}}}else if(e.stage.kind==="repair"){let a=e.actions.get(e.stage.id);if(!a)throw new Error(`Persisted repair action is missing: ${e.stage.id}`);if(a.kind==="proposal")await yt({workspacePath:e.workspacePath,transaction:e.transaction,change:a.change});else {let r=Ce(a.action);if(r){let t=await le(e.workspacePath,a.action),o=await ee(e.workspacePath,e.transaction)??e.workspacePath;if(!await K(o,t))throw new Error(`Repair project scope escapes its approved canonical boundary through a symbolic link: ${a.action.projectPath??"."}`);await Pt(t,r);}else if(e.stage.invocation){let t=await(e.dependencies.runInvocation??Le)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});if(e.stage.exitCode=t.exitCode,e.stage.stdoutTail=Q(t.stdout),e.stage.stderrTail=Q(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??Le)({workspacePath:e.workspacePath,invocation:e.stage.invocation,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});if(e.stage.exitCode=a.exitCode,e.stage.stdoutTail=Q(a.stdout),e.stage.stderrTail=Q(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=M(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 ja(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"passed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),true}catch(a){return e.stage.status="failed",e.stage.completedAt=M(e.dependencies.now),e.stage.summary=a instanceof Error?a.message:String(a),await ja(e.workspacePath,e.transaction),A(e.transaction,"stage",e.stage.summary,{stageId:e.stage.id,status:"failed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false}}async function ye(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 j(e.workspacePath,e.transaction,e.dependencies.now);let r=async n=>(e.transaction.checkpoint.status="conflicted",e.transaction.state="decision-required",e.transaction.decision=H(n,["manual-repair","cancel"]),A(e.transaction,"decision",n,{status:"conflicted",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false),t=[],o=await ee(e.workspacePath,e.transaction)??e.workspacePath;for(let n of e.transaction.checkpoint.files){let s=await T({workspacePath:e.workspacePath,value:n.path,projectBoundary:o,projectName:e.transaction.target.projectName});if(!x(o,s)||!await K(o,s))return r(`Rollback refused because ${n.path} escaped the canonical repair boundary.`);let h=await k.lstat(s).catch(()=>{});if(h?.isSymbolicLink()||h&&!h.isFile())return r(`Rollback refused because ${n.path} is no longer a regular file.`);let l=h?await k.readFile(s):void 0,d=l?$(l):null,g=n.afterHash!==void 0&&d===n.afterHash,b=a&&d===n.beforeHash;if(!g&&!b)return r(`Rollback refused because ${n.path} changed outside this transaction.`);if(!n.existed){t.push({entry:n,absolute:s});continue}if(!n.backupRef)return r(`Rollback refused because the checkpoint backup is missing for ${n.path}.`);let y=c$1.join(de(e.workspacePath,e.transaction.transactionId),n.backupRef),P=await k.lstat(y).catch(()=>{});if(!P?.isFile()||P.isSymbolicLink())return r(`Rollback refused because the checkpoint backup is invalid for ${n.path}.`);let E=await k.readFile(y);if($(E)!==n.beforeHash)return r(`Rollback refused because the checkpoint backup hash is invalid for ${n.path}.`);t.push({entry:n,absolute:s,backup:E});}for(let n of t){if(!n.entry.existed){await k.remove(n.absolute);continue}let s=n.backup;if(s===void 0)throw new Error(`Validated checkpoint backup disappeared for ${n.entry.path}.`);let h=c$1.join(c$1.dirname(n.absolute),`.${c$1.basename(n.absolute)}.${process.pid}.${randomUUID()}.rollback-tmp`);await k.ensureDir(c$1.dirname(n.absolute)),await k.writeFile(h,s,{flag:"wx"}),n.entry.mode!==void 0&&await k.chmod(h,n.entry.mode),await k.move(h,n.absolute,{overwrite:true});}e.transaction.checkpoint.status="restored",e.transaction.checkpoint.restoredAt=M(e.dependencies.now);let i=e.transaction.stages.filter(n=>n.kind==="reconcile"&&n.invocation);for(let n of i){let s=n.invocation;if(!s)continue;let h=`rollback:${n.id}`,l=e.transaction.stages.find(b=>b.id===h&&b.kind==="rollback"),d=l??{id:h,kind:"rollback",status:"pending",required:true,risk:n.risk,summary:"Reconcile the installed dependency tree with the restored manifest and lockfile.",invocation:s};l||e.transaction.stages.push(d),d.status="running",d.startedAt=M(e.dependencies.now),delete d.completedAt,delete d.exitCode,delete d.stdoutTail,delete d.stderrTail,A(e.transaction,"rollback",d.summary,{stageId:d.id,status:"running",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now);let g;try{g=await(e.dependencies.runInvocation??Le)({workspacePath:e.workspacePath,invocation:s,policy:e.transaction.policy,projectBoundary:await ee(e.workspacePath,e.transaction)});}catch(b){g={exitCode:null,stdout:"",stderr:b instanceof Error?b.message:String(b)};}if(d.exitCode=g.exitCode,d.stdoutTail=Q(g.stdout),d.stderrTail=Q(g.stderr),d.completedAt=M(e.dependencies.now),g.exitCode!==0)return d.status="failed",d.summary=g.stderr||g.stdout||`Rollback reconciliation exited with ${g.exitCode}.`,e.transaction.state="decision-required",e.transaction.decision=H(`Source files were restored, but the installed dependency tree could not be reconciled: ${d.summary}`,["manual-repair","cancel"]),A(e.transaction,"decision",e.transaction.decision.reason,{stageId:d.id,status:"rollback-reconcile-failed",now:e.dependencies.now}),await j(e.workspacePath,e.transaction,e.dependencies.now),false;d.status="passed",d.summary="Installed dependency tree reconciled with the restored source state.",A(e.transaction,"rollback",d.summary,{stageId:d.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 j(e.workspacePath,e.transaction,e.dependencies.now),true}async function ar(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Oa(r,e.transactionId);try{let o=await pe({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(Je(o)!==o.integrity.planHash)return o.approval.status="expired",o.state="decision-required",o.decision=H("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 j(r,o,a.now),o;let i=await We(r,e.transactionId);if($(V(i))!==o.integrity.sourceEvidenceHash)return o.approval.status="expired",o.state="decision-required",o.decision=H("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 j(r,o,a.now),o;if(o.state==="approved"&&ce(i)&&i.goalId){let m=await l({workspacePath:r,goalId:i.goalId}),w=m.active?.repairTransactionIds??(m.active?.repairTransactionId?[m.active.repairTransactionId]:[]);if(m.index.activeGoalId!==i.goalId||!w.includes(o.transactionId))throw new Error(`Goal-bound repair transaction is not linked to the active Goal Pack: ${o.transactionId}`)}let s=(await Ke({workspacePath:r,stages:o.stages,toolAvailable:a.toolAvailable})).find(m=>m.status==="failed");if(s){let m=o.stages.find(w=>w.invocation&&`tool:${w.invocation.cwd}:${w.invocation.executable}`===s.id)?.invocation?.executable;return o.approval.status="expired",o.state="decision-required",o.decision=H(`${s.message} The approved plan cannot execute against a changed toolchain.`,["manual-repair","cancel"],{kind:"missing-executable",id:s.id,message:s.message,...m?{executable:m}:{}}),A(o,"decision",o.decision.reason,{status:"tool-precondition-failed",now:a.now}),await j(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 ye({workspacePath:r,transaction:o,dependencies:a}),o}let h=new Map(ce(i)?i.changes.map(m=>[`proposal:${m.id}`,{kind:"proposal",change:m}]):i.actions.map(m=>[`action:${m.id}`,{kind:"canonical",action:m}]));try{await Ha({workspacePath:r,transaction:o});}catch(m){return o.approval.status="expired",o.state="decision-required",o.decision=H(m instanceof Error?m.message:String(m),["cancel"]),A(o,"decision",o.decision.reason,{status:"source-precondition-failed",now:a.now}),await j(r,o,a.now),o}let l$1=o.stages.find(m=>m.id==="target-precondition");if(!l$1)return o.approval.status="expired",o.state="decision-required",o.decision=H("The approved plan has no exact target precondition. Create and approve a fresh transaction.",["cancel"]),await j(r,o,a.now),o;if(!await xa({workspacePath:r,transaction:o,stage:l$1,actions:h,dependencies:a}))return o.approval.status="expired",o.state="decision-required",o.decision=H(`Target precondition failed before checkpoint: ${l$1.summary}`,["cancel"]),A(o,"decision",o.decision.reason,{status:"target-precondition-failed",now:a.now}),await j(r,o,a.now),o;try{await mt({workspacePath:r,transaction:o,now:a.now});}catch(m){return o.approval.status="expired",o.state="decision-required",o.decision=H(m instanceof Error?m.message:String(m),["cancel"]),A(o,"decision",o.decision.reason,{status:"precondition-failed",now:a.now}),await j(r,o,a.now),o}o.state="executing",await j(r,o,a.now);for(let m of o.stages.filter(w=>w.id!=="target-precondition"&&w.id!=="canonical-verify"&&w.kind!=="rollback"))if(!await xa({workspacePath:r,transaction:o,stage:m,actions:h,dependencies:a})&&m.required)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H(`Required stage ${m.id} failed: ${m.summary}`,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o;o.state="verifying";let g=o.stages.find(m=>m.id==="canonical-verify");if(!g)return o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H("The approved plan has no canonical verification stage.",o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o;g.status="running",g.startedAt=M(a.now),A(o,"verification","Canonical Workspace Intelligence verification started.",{stageId:g.id,status:"running",now:a.now}),await j(r,o,a.now);let b;try{b=a.verify?await a.verify(r):await c$2({workspacePath:r,strict:true,agent:"generic"});}catch(m){b={status:"failed",exitCode:1,artifactPath:p$1.intelligenceRun},g.stderrTail=Q(m instanceof Error?m.message:String(m));}let y=b.status==="passed"&&b.exitCode===0?"passed":b.status==="failed"||b.exitCode===1?"failed":"blocked",P=await bt({workspacePath:r,transaction:o,sourcePlan:i,dependencies:a,workspaceStatus:y}),E=P.status==="passed"&&y!=="failed",q,f;if(E&&ce(i)&&i.goalId){let m=await a$3(r);if(m.status==="miss")E=false,f=`Goal-bound repair could not seal its post-repair Model/Graph source state (${m.reason}).`;else {let w=m.graph.source.inputs?.hash;w?q={modelHash:d(m.model),modelHashSemantics:"workspace-model-structural-v1",graphHash:c$3(m.graph),graphHashSemantics:"canonical-json-v1",graphInputHash:w}:(E=false,f="Goal-bound repair could not seal its post-repair Graph input fingerprint.");}}return g.status=E?"passed":"failed",g.completedAt=M(a.now),g.exitCode=b.exitCode,g.summary=E&&y==="passed"?"Selected repair target and canonical workspace verification passed.":E?"Selected repair target passed; canonical workspace verification remains blocked by other governed findings.":f||(P.status==="unknown"?"Canonical verification could not establish the selected repair target outcome.":`Selected repair target remains unresolved; canonical workspace verification is ${y}.`),o.verification={status:E?"passed":"failed",targetStatus:P.status,workspaceStatus:y,remainingActionIds:P.remainingActionIds,artifact:p$1.intelligenceRun,exitCode:b.exitCode,summary:g.summary,...q?{sourceBinding:q}:{}},A(o,"verification",g.summary,{stageId:g.id,status:g.status,now:a.now}),E?(o.state="closed",delete o.decision,A(o,"closed",g.summary,{status:"passed",now:a.now}),o.integrity.closureHash=Ba(o),await j(r,o,a.now),o):(o.state=o.policy.autoRollback?"rollback-required":"decision-required",o.decision=H(g.summary,o.policy.autoRollback?["rollback","manual-repair","cancel"]:["manual-repair","rollback","cancel"]),await j(r,o,a.now),o.policy.autoRollback&&await ye({workspacePath:r,transaction:o,dependencies:a}),o)}finally{await t();}}async function Rt(e,a={}){let r=c$1.resolve(e.workspacePath),t=await Oa(r,e.transactionId);try{let o=await pe({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 ye({workspacePath:r,transaction:o,dependencies:a}),o}finally{await t();}}async function tr(e,a={}){let r=await pe(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 j(e.workspacePath,r,a.now),r}async function rr(e,a={}){let r=c$1.resolve(e.workspacePath),t=await pe({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 Rt({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 j(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 We(r,e.transactionId),i={maxRisk:e.decision==="approve-invasive"?"invasive":e.decision==="approve-guarded"&&t.policy.maxRisk==="safe"?"guarded":t.policy.maxRisk,allowForce:t.policy.allowForce||e.decision==="allow-force",allowBreaking:t.policy.allowBreaking||e.decision==="allow-breaking",autoRollback:t.policy.autoRollback},n=async()=>{if(ce(o))return ft({workspacePath:r,proposal:o,...i},a);let l=t.target.actionIds.map(d=>d.startsWith("action:")?d.slice(7):d);return gt({workspacePath:r,cardId:t.target.cardId,...l.length===1?{actionId:l[0]}:{},projectName:t.target.projectName,...i},a)},s=t.decision.causes?.some(l=>l.kind==="missing-executable"),h=e.decision==="replan"&&s?await n():void 0;return h?.transactionId===t.transactionId?t:(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 j(r,t,a.now),h??n())}async function jt(e){let a=c$1.join(e,Ge,"transactions"),r=await k.readdir(a).catch(()=>[]);return (await Promise.all(r.map(o=>pe({workspacePath:e,transactionId:o}).catch(()=>{})))).filter(o=>!!o).sort((o,i)=>i.updatedAt.localeCompare(o.updatedAt))}export{er as approveWorkspaceRepair,Qt as assertClosedGoalRepairTransactionCurrent,tr as cancelWorkspaceRepair,rr as decideWorkspaceRepair,kt as exactCardProducerArgs,ar as executeWorkspaceRepair,Zt as inspectWorkspaceRepairCapabilities,jt as listWorkspaceRepairTransactions,gt as planWorkspaceRepair,ft as planWorkspaceRepairProposal,pe as readWorkspaceRepairTransaction,Rt as rollbackWorkspaceRepair};
@@ -0,0 +1 @@
1
+ export{a as resolveWorkspaceRunStageTimeoutMs,b as runWorkspaceStage}from'./chunk-LEEOZRWR.js';export{a as WORKSPACE_RUN_LAST_REPORT_FILENAME}from'./chunk-37SWTS2B.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-R5OJD5K2.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-DTLLIA2C.js';