workspai 0.72.1 → 0.73.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 (79) hide show
  1. package/dist/analyze-WC2TY5AT.js +1 -0
  2. package/dist/autopilot-release-LJDRECFW.js +1 -0
  3. package/dist/{chunk-I7P6XQJI.js → chunk-2BCECNIW.js} +1 -1
  4. package/dist/{chunk-U3RX7KDY.js → chunk-3GO7BJ5J.js} +1 -1
  5. package/dist/{chunk-QVUVJU56.js → chunk-3SNP6M4M.js} +1 -1
  6. package/dist/chunk-4HQU2GQM.js +1 -0
  7. package/dist/{chunk-T6KHOIEY.js → chunk-4JAURS76.js} +1 -1
  8. package/dist/chunk-7O7P4MRD.js +1 -0
  9. package/dist/{chunk-L5ZD2GD3.js → chunk-AQNU5RXV.js} +1 -1
  10. package/dist/{chunk-TDQ2PRHV.js → chunk-D3N2WFDV.js} +1 -1
  11. package/dist/{chunk-FYIPYGMW.js → chunk-DNKELRK6.js} +1 -1
  12. package/dist/{chunk-T6LCDLJ7.js → chunk-EDDGQ6LM.js} +1 -1
  13. package/dist/{chunk-LLEKVSMX.js → chunk-F6CTGVJA.js} +1 -1
  14. package/dist/{chunk-JPPZDLY3.js → chunk-FRH7AIGY.js} +2 -2
  15. package/dist/{chunk-KVPTZMEV.js → chunk-HAZGSAKP.js} +1 -1
  16. package/dist/{chunk-ISGLADQI.js → chunk-IPZT6WKM.js} +1 -1
  17. package/dist/{chunk-4PDEWMOG.js → chunk-J44PN2FX.js} +1 -1
  18. package/dist/{chunk-4AW5QP5J.js → chunk-K3O3HENC.js} +1 -1
  19. package/dist/{chunk-SS7X2YF5.js → chunk-LDJAUIAG.js} +1 -1
  20. package/dist/{chunk-SATPH22S.js → chunk-LGC4CRUF.js} +1 -1
  21. package/dist/{chunk-IX5Z6EK6.js → chunk-ND5YAC4T.js} +1 -1
  22. package/dist/{chunk-WPZUKU2B.js → chunk-NNQE4DS2.js} +1 -1
  23. package/dist/chunk-NSMRQOWP.js +157 -0
  24. package/dist/{chunk-WMC2H7MJ.js → chunk-OIGI7MP6.js} +1 -1
  25. package/dist/{chunk-S66NO5BX.js → chunk-R5OJD5K2.js} +1 -1
  26. package/dist/{chunk-L4WG3NI7.js → chunk-SO4CGS35.js} +1 -1
  27. package/dist/{chunk-RQKDJVX3.js → chunk-T5NBSCVX.js} +2 -2
  28. package/dist/{chunk-2RF75G5T.js → chunk-TIZCESKY.js} +1 -1
  29. package/dist/{chunk-62YBFWHY.js → chunk-TSYDTKXO.js} +1 -1
  30. package/dist/{chunk-N2PAAQKI.js → chunk-TZK2R6RD.js} +1 -1
  31. package/dist/{chunk-JQINCVK5.js → chunk-UCNIXOTL.js} +1 -1
  32. package/dist/{chunk-5NL53T5C.js → chunk-VBMWFT7Q.js} +1 -1
  33. package/dist/chunk-YYELANJO.js +7 -0
  34. package/dist/{chunk-QYXX6G5O.js → chunk-ZZWGD3X3.js} +1 -1
  35. package/dist/{create-FOPYAWAR.js → create-XYKXS3JB.js} +1 -1
  36. package/dist/{doctor-Z3Z5L67W.js → doctor-LQ7FT6AZ.js} +1 -1
  37. package/dist/{goal-lifecycle-ZH7AQIOX.js → goal-lifecycle-BIX2JVNO.js} +1 -1
  38. package/dist/{goal-pack-OP453Q6U.js → goal-pack-SUWH6K7U.js} +1 -1
  39. package/dist/index.js +22 -22
  40. package/dist/{pipeline-LPZHMO7S.js → pipeline-NSPPWD7U.js} +1 -1
  41. package/dist/{project-agent-entry-QGPM7CU7.js → project-agent-entry-Y3NEHZED.js} +1 -1
  42. package/dist/{project-intelligence-lens-U7PLWYXX.js → project-intelligence-lens-6Q6XSUDJ.js} +1 -1
  43. package/dist/{project-test-coverage-4BGDDBBL.js → project-test-coverage-5PXAHBYQ.js} +1 -1
  44. package/dist/{proof-carrying-change-6LQ6JO5J.js → proof-carrying-change-456TYEDW.js} +1 -1
  45. package/dist/{verified-goal-JIRVX7KO.js → verified-goal-GRH5UOJR.js} +1 -1
  46. package/dist/{workspace-3K2YGPU7.js → workspace-ROUEA3RT.js} +1 -1
  47. package/dist/{workspace-agent-sync-TFQNKRD3.js → workspace-agent-sync-6UYG33EQ.js} +1 -1
  48. package/dist/{workspace-context-ZDXF6S7S.js → workspace-context-H7ZXR6VI.js} +1 -1
  49. package/dist/{workspace-contract-E7GVWM7W.js → workspace-contract-2V2BI6A3.js} +1 -1
  50. package/dist/{workspace-explain-YB66UFAS.js → workspace-explain-IBMTRUSF.js} +1 -1
  51. package/dist/{workspace-foundation-J62BMOQS.js → workspace-foundation-H5B3TTZD.js} +1 -1
  52. package/dist/{workspace-graph-stream-SJUCBPS4.js → workspace-graph-stream-YDEET5LK.js} +1 -1
  53. package/dist/workspace-graph-token-efficiency-XM3LYFUC.js +1 -0
  54. package/dist/{workspace-intelligence-3IAAM3H3.js → workspace-intelligence-DXKQXTTM.js} +1 -1
  55. package/dist/{workspace-intelligence-benchmark-UCGDKMDF.js → workspace-intelligence-benchmark-L46EGZZM.js} +1 -1
  56. package/dist/{workspace-intelligence-runner-OELXKX3D.js → workspace-intelligence-runner-SCB44IXU.js} +1 -1
  57. package/dist/{workspace-knowledge-graph-WNQMNAVL.js → workspace-knowledge-graph-BNEVFEOW.js} +1 -1
  58. package/dist/{workspace-knowledge-graph-query-3GPXGWYN.js → workspace-knowledge-graph-query-GOC365ZR.js} +1 -1
  59. package/dist/workspace-knowledge-graph-snapshot-2NMV7LEJ.js +1 -0
  60. package/dist/{workspace-mcp-serve-X7ZYJA3X.js → workspace-mcp-serve-JLZTTEVG.js} +1 -1
  61. package/dist/{workspace-model-5FA2636K.js → workspace-model-XSNLDUI2.js} +1 -1
  62. package/dist/{workspace-onboarding-CZSQDNKO.js → workspace-onboarding-IRBVZTT4.js} +1 -1
  63. package/dist/{workspace-registry-summary-WKENOFEA.js → workspace-registry-summary-CBZDSG6I.js} +1 -1
  64. package/dist/{workspace-repair-engine-RXHJX4CQ.js → workspace-repair-engine-TDUNQSFJ.js} +1 -1
  65. package/dist/workspace-run-I2W5PIPK.js +1 -0
  66. package/dist/{workspace-verify-37QL2JYE.js → workspace-verify-QTRY7WW3.js} +1 -1
  67. package/dist/{workspace-watch-P5X6TAFK.js → workspace-watch-PDQKYBYQ.js} +1 -1
  68. package/docs/SECURITY.md +16 -59
  69. package/docs/ci-workflows.md +43 -11
  70. package/package.json +2 -2
  71. package/dist/analyze-5ENZTHOT.js +0 -1
  72. package/dist/autopilot-release-QMZSHOLF.js +0 -1
  73. package/dist/chunk-6WOFOOM7.js +0 -7
  74. package/dist/chunk-BVWDG66W.js +0 -1
  75. package/dist/chunk-LLSY6L7E.js +0 -157
  76. package/dist/chunk-X5ZNFXFI.js +0 -1
  77. package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +0 -1
  78. package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +0 -1
  79. package/dist/workspace-run-IDRHBKEB.js +0 -1
@@ -1 +1 @@
1
- import {b,c,d as d$1}from'./chunk-SS7X2YF5.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-37SWTS2B.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-QVUVJU56.js';import {q as q$1,m as m$1,d as d$5}from'./chunk-BVWDG66W.js';import {d as d$2}from'./chunk-WPZUKU2B.js';import {g,h}from'./chunk-FE5R6EUV.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r,s}from'./chunk-ODK4LCEL.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=m$1(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e,t){if(e.id==="workspace.doctor")return m.join(t,p.doctor);if(e.id==="workspace.contract.verify")return m.join(t,p.contractVerify);if(e.id==="workspace.readiness")return m.join(t,p.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t$1)return true;let k=Date.parse(o),u=Date.parse(t$1);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return r.doctor;if(e.id==="workspace.readiness")return r.readiness;if(e.id==="workspace.contract.verify")return r.contractVerify;if(e.id==="workspace.analyze")return r.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s$1){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await g(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g$1=Be(e);if(g$1)try{a$2(d,g$1,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s$1,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s$1);else {let n=R(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=Ae(t,e.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g$1);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g$1,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:m$1(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(m$1(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p=await Le(o$1,t),B=qe(V,p),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p}}async function Le(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return h(t,G,d$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
1
+ import {b,c,d as d$1}from'./chunk-LDJAUIAG.js';import {a as a$3}from'./chunk-X7FYEKLI.js';import {c as c$2}from'./chunk-37SWTS2B.js';import {c as c$1,d as d$4}from'./chunk-N4B2M44I.js';import {a as a$1,b as b$1}from'./chunk-PYCJWW4B.js';import {p as p$1,a,o,g as g$1,d as d$3,f}from'./chunk-3SNP6M4M.js';import {q as q$1,m as m$1,d as d$5}from'./chunk-4HQU2GQM.js';import {d as d$2}from'./chunk-NNQE4DS2.js';import {g,h}from'./chunk-FE5R6EUV.js';import {a as a$2}from'./chunk-AFIFZTOY.js';import {d}from'./chunk-EWZZUQBR.js';import {q,p,t,r,s}from'./chunk-ODK4LCEL.js';import m from'path';import v from'fs-extra';var fe="rapidkit-blocker-resolution-v1";function pe(e){let t=e.blockers.map(s=>s.trim()).filter(Boolean).slice(0,12),r=e.stderrTail?.trim().slice(-400)??"";return d$5({blockers:t,exitCode:e.exitCode??null,stderrTail:r})}function we(e){let t=e.trim().toLowerCase();return t?t.includes("missing evidence")||t.includes(": missing")||t.includes("artifact missing")||t.includes("not found on disk")?"artifact-missing":t.includes("policy.")||t.includes("contract")?"config-fixable":t.includes("impact")||t.includes("untracked")||t.includes("grounding")?"semantic-attention":t.includes("failed")||t.includes("blocked")||t.includes(": fail")?"command-failed-repeat":"config-fixable":"unresolvable-without-human"}function me(e){let t=we(e.reason),r=pe({blockers:[e.reason]}),s=t==="artifact-missing"?[{actionKind:"run-once",detail:e.sourceCommand?`Run the source command once: ${e.sourceCommand}`:"Run the mapped workspace intelligence command once to generate the missing artifact.",...e.sourceCommand?{}:{studioActionId:"run-analyze"}}]:t==="semantic-attention"?[{actionKind:"commit-files",detail:"Review workspace-level grounding files (AGENTS.md, agent-sync outputs) and commit or refresh the impact baseline."},{actionKind:"refresh-baseline",detail:"Refresh snapshot + diff + impact before re-running verify."}]:[{actionKind:"edit-file",detail:"Apply the smallest safe file or policy fix for this blocker before re-running verification.",studioActionId:"fix-lens"}];return {schemaVersion:fe,blockerId:e.blockerId,sourceCommand:e.sourceCommand,sourceArtifact:e.sourceArtifact,resolutionClass:t,blockerSignature:r,commandRetryHint:t==="artifact-missing"?e.sourceCommand?`Run the source command once: ${e.sourceCommand}, then verify.`:"Run the source command once, then verify.":"Do not re-run the same failing command; fix the source issue first, then verify.",fixHints:s,verifyCommand:e.verifyCommand,verifyArtifact:e.verifyArtifact}}function Re(e){let t=e.toLowerCase();return t.includes("stale")||t.includes("missing evidence")||t.includes("no projects")||t.includes("projects.empty")||t.includes("projects discovered")||t.includes("projects.missing")||t.includes("not yet run")||t.includes("doctor-last-run")||t.includes("doctor-project-last-run")||t.includes("doctor-remediation-plan-last-run")||t.includes("doctor-fix-result-last-run")||t.includes("pipeline-last-run")||t.includes("release-readiness")||t.includes("analyze-last-run")||t.includes("analyze reported")||t.includes("analyze verdict")||t.includes("analyze needs attention")||t.includes("toolchain.lock")||t.includes("not pinned")||t.includes("readiness:")||t.includes("env:")||t.includes("workspace-run-last")||t.includes("pre-project")||t.includes("before adding projects")||t.includes("workspace.projects.missing")||t.includes("no backend projects")||t.includes("index.json")||t.includes("workspace-intelligence-history")||t.includes("validation warning")||t.includes("workspace model validation")||t.includes("workspace.marker")||t.includes("no project roots")||t.includes("no infrastructure services")||t.includes("infra/overrides")||t.includes("infra dependencies")||t.includes("contract verify")||t.includes("contract inspect")||t.includes("publish verify evidence")}function Ce(e){return e.length===0||e.every(t=>Re(t))}function ge(e){return e.projectCount>0||e.policyErrorCount>0?{verdict:e.verdict,exitCode:e.exitCode}:e.verdict==="blocked"&&Ce(e.blockingReasons)?{verdict:"needs-attention",exitCode:1}:{verdict:e.verdict,exitCode:e.exitCode}}function tt(e,t){let r=t&&t!=="ready"?` (${t.replace(/-/g," ")})`:"";return e===0?`Workspace scaffold ready${r} \u2014 add your first project to continue.`:`Workspace scaffold${r}: ${e} pre-project signal(s) \u2014 add your first project to continue.`}var ye=q.verify,G=p.verify;function Ae(e,t){return m.isAbsolute(t)?t:m.join(e,t)}async function ke(e){let t=await v.readJson(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Workspace impact input is not a JSON object: ${e}`);let r=t;if(r.schemaVersion!==f)throw new Error(`Unsupported workspace impact schema: ${String(r.schemaVersion)}`);a$2(t,"contracts/workspace-intelligence/workspace-impact.v1.json",`Workspace impact ${e}`);let s=r;a$2(s.diff,"contracts/workspace-intelligence/workspace-model-diff.v1.json",`Embedded workspace diff in ${e}`);let i=[];s.summary.affectedProjects!==s.affectedProjects.length&&i.push("summary.affectedProjects does not match affectedProjects.length"),s.summary.workspaceItems!==s.workspaceImpact.length&&i.push("summary.workspaceItems does not match workspaceImpact.length"),s.summary.recommendedCommands!==s.verificationPlan.length&&i.push("summary.recommendedCommands does not match verificationPlan.length"),s.summary.blastRadius.directlyAffected!==s.affectedProjects.length&&i.push("blastRadius.directlyAffected does not match affectedProjects.length"),s.summary.blastRadius.transitivelyAffected!==s.transitiveImpact.length&&i.push("blastRadius.transitivelyAffected does not match transitiveImpact.length");let o=s.transitiveImpact.reduce((u,d)=>Math.max(u,d.distance??0),0);s.summary.blastRadius.maxDistance!==o&&i.push("blastRadius.maxDistance does not match transitive impact distances");let k=m$1(s.diff.currentModel)?.edges.length??0;if(s.summary.blastRadius.graphEdges!==k&&i.push("blastRadius.graphEdges does not match the embedded model graph"),s.summary.changed!==s.diff.summary.changed&&i.push("summary.changed does not match embedded diff summary"),s.fromRef!==s.diff.fromRef&&i.push("fromRef does not match embedded diff fromRef"),s.workspace.name!==s.diff.currentModel.workspace.name&&i.push("workspace.name does not match the embedded model"),s.diff.toHash!==d(s.diff.currentModel)&&i.push("embedded diff current-model hash does not match toHash"),i.length>0)throw new Error(`Workspace impact semantic integrity failed: ${i.join("; ")} (${e})`);return s}function Ee(e){let t=new Set,r=[];for(let s of e){let i=`${s.scope}:${s.project??""}:${s.display}`;t.has(i)||(t.add(i),r.push(s));}return r}function Se(e,t){if(!e||e==="workspace")return true;let r=(e.startsWith("project:")?e.slice(8):e).trim().toLowerCase();return t.scope==="workspace"?true:(t.project??"").trim().toLowerCase()===r}function We(e,t){if(e.id==="workspace.doctor")return m.join(t,p.doctor);if(e.id==="workspace.contract.verify")return m.join(t,p.contractVerify);if(e.id==="workspace.readiness")return m.join(t,p.readiness);if(e.id==="workspace.analyze")return m.join(t,".workspai","reports","analyze-last-run.json");if(e.id==="workspace.pipeline")return m.join(t,".workspai","reports","pipeline-last-run.json");if(e.id==="workspace.doctor-fix")return m.join(t,".workspai","reports","doctor-fix-result-last-run.json");if(e.id.startsWith("project.")&&e.id.includes("."))return m.join(t,".workspai","reports","workspace-run-last.json")}function C(e){return !e||typeof e!="object"||Array.isArray(e)?null:e}function je(e){if(!c$1(e,"workspace"))return {status:"fail",message:"Doctor evidence contract is missing or unsupported."};try{d$4(e);}catch(s){return {status:"fail",message:`Doctor evidence semantic validation failed: ${s instanceof Error?s.message:String(s)}`}}let t=a$3(e);return t.hasSystemErrors||t.blockingFindings>0?{status:"fail",message:`Doctor evidence reports ${t.blockingFindings} canonical blocking finding(s).`}:t.advisoryFindings+t.unknownFindings+t.contradictionCount+t.missingDiagnosisProjects>0||t.staleEvidence||t.unknownFreshness||t.minimumDiagnosisCompleteness<100?{status:"warn",message:`Doctor evidence needs attention (${t.advisoryFindings} advisory, ${t.unknownFindings} unknown, ${t.contradictionCount} contradictory; ${t.minimumDiagnosisCompleteness}% complete).`}:{status:"pass",message:"Canonical Doctor evidence is complete, fresh, and healthy."}}function xe(e){let t=typeof e.overallStatus=="string"?e.overallStatus:"unknown";return t==="fail"?{status:"fail",message:"Release readiness evidence reports blocking failures."}:t==="warn"?{status:"warn",message:"Release readiness evidence reports warnings."}:t==="pass"?{status:"pass",message:"Release readiness evidence passed."}:{status:"warn",message:`Release readiness evidence status is ${t}.`}}function Pe(e){let t=typeof e.status=="string"?e.status:"unknown";return t==="failed"||t==="fail"?{status:"fail",message:"Workspace contract verify evidence failed."}:t==="passed"||t==="pass"?{status:"pass",message:"Workspace contract verify evidence passed."}:{status:"warn",message:`Workspace contract verify evidence status is ${t}.`}}function Ie(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Analyze evidence reports blocking findings."}:r==="needs-attention"?{status:"warn",message:"Analyze evidence reports warnings."}:{status:"pass",message:"Analyze evidence is ready."}}function Ve(e){let t=e.schemaVersion===s.doctorFixResult.schemaVersion?e:e.fixResult;if(!t||typeof t!="object"||Array.isArray(t))return {status:"skipped",message:"Doctor fix result not present; run doctor workspace --fix --json to record fixes."};let r=t,s$1=Array.isArray(r.remainingBlockers)?r.remainingBlockers:[];if(s$1.length>0)return {status:"fail",message:`Doctor fix result reports ${s$1.length} remaining blocker(s).`};let i=Array.isArray(r.appliedFixes)?r.appliedFixes:[];return i.length===0?{status:"pass",message:"Doctor fix result recorded with no remaining blockers."}:{status:"pass",message:`Doctor fix result recorded ${i.length} applied fix(es) with no remaining blockers.`}}async function Fe(e,t$1){let r=await g(e,t.doctorRemediationPlan);if(!r)return false;try{let s=C(await v.readJson(r));if(!s||(Array.isArray(s.steps)?s.steps:[]).length>0)return false;let o=typeof s.generatedAt=="string"?s.generatedAt:void 0;if(!o||!t$1)return true;let k=Date.parse(o),u=Date.parse(t$1);return !Number.isFinite(k)||!Number.isFinite(u)?true:k>=u}catch{return false}}function $e(e){return e.id.endsWith(".init")?"init":e.id.endsWith(".test")?"test":e.id.endsWith(".build")?"build":e.id.endsWith(".start")?"start":null}function Oe(e){let t=C(e.summary),r=typeof t?.verdict=="string"?t.verdict:void 0;return r==="blocked"?{status:"fail",message:"Pipeline evidence is blocked."}:r==="needs-attention"?{status:"warn",message:"Pipeline evidence needs attention."}:r==="ready"?{status:"pass",message:"Pipeline evidence is ready."}:{status:"warn",message:"Pipeline evidence status is unknown."}}function De(e,t,r){let s=$e(t),i=c$2(e,s??void 0);if(!i)return {status:"missing",message:"Workspace run evidence is missing or unreadable."};let o=i.stage;if(s&&o!==s)return {status:"missing",message:`Workspace run evidence is for stage "${o}", expected "${s}".`};let k=Array.isArray(i.projects)?i.projects:[],u=t.project?.toLowerCase();if(!u)return {status:"missing",message:"Project-scoped workspace run evidence is missing a project identifier."};let d=k.find(g=>{let c=C(g);if(!c)return false;let n=typeof c.projectName=="string"?c.projectName.toLowerCase():"",a=["projectPath","relativePath","path"].map(f=>c[f]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.replace(/\\/g,"/").toLowerCase());return n===u||a.some(f=>f.endsWith(`/${u}`)||f===u)});if(d){let g=R(i.generatedAt,r,`Workspace run evidence for ${t.project??t.id}`);if(g)return {status:"fail",message:g};let c=C(d),n=typeof c?.status=="string"?c.status:"unknown";return n==="failed"?{status:"fail",message:`Workspace run evidence failed for ${t.project}.`}:n==="passed"?{status:"pass",message:`Workspace run evidence passed for ${t.project}.`}:n==="skipped"?{status:"warn",message:`Workspace run evidence skipped for ${t.project}.`}:{status:"warn",message:`Workspace run evidence status is ${n} for ${t.project}.`}}return {status:"missing",message:`Workspace run evidence does not include project ${t.project}.`}}function R(e,t,r){if(!t)return null;if(typeof e!="string"||e.trim().length===0)return `${r} is stale: missing generatedAt timestamp (required after impact ${t}).`;let s=Date.parse(e),i=Date.parse(t);return Number.isFinite(s)?Number.isFinite(i)&&s<i?`${r} is stale: generated at ${e}, before impact ${t}.`:null:`${r} is stale: invalid generatedAt timestamp (required after impact ${t}).`}function Be(e){if(e.id==="workspace.doctor")return r.doctor;if(e.id==="workspace.readiness")return r.readiness;if(e.id==="workspace.contract.verify")return r.contractVerify;if(e.id==="workspace.analyze")return r.analyze;if(e.id==="workspace.pipeline")return "contracts/pipeline-last-run.v1.json"}async function _e(e,t,r,s$1){let i=We(e,t),o=i?m.relative(t,i).split(m.sep).join("/"):void 0;if(e.id==="workspace.contract.verify"&&!r)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"skipped",required:e.required,message:"Workspace contract is not present; contract verify skipped."};let k=i?await g(t,o??""):null;if(!i||!k)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"missing",required:e.required,evidencePath:o,message:o?`Missing evidence report: ${o}`:"No evidence mapping exists for this command."};let u;try{u=await v.readJson(k);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is unreadable JSON: ${n instanceof Error?n.message:String(n)}`}}let d=C(u);if(!d)return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:"Evidence report is not a JSON object."};let g$1=Be(e);if(g$1)try{a$2(d,g$1,`${e.label} evidence`);}catch(n){return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:"fail",required:e.required,evidencePath:o,message:`Evidence report is invalid: ${n instanceof Error?n.message:String(n)}`}}let c;if(e.id==="workspace.doctor"){let n=R(d.generatedAt,s$1,"Doctor evidence");n?c={status:"fail",message:n}:c=je(d);}else if(e.id==="workspace.readiness"){let n=R(d.generatedAt,s$1,"Release readiness evidence");n?c={status:"fail",message:n}:c=xe(d);}else if(e.id==="workspace.contract.verify"){let n=R(d.generatedAt,s$1,"Workspace contract verify evidence");n?c={status:"fail",message:n}:c=Pe(d);}else if(e.id==="workspace.analyze"){let n=R(d.generatedAt,s$1,"Analyze evidence");n?c={status:"fail",message:n}:c=Ie(d);}else if(e.id==="workspace.pipeline"){let n=R(d.generatedAt,s$1,"Pipeline evidence");n?c={status:"fail",message:n}:c=Oe(d);}else if(e.id==="workspace.doctor-fix"){let n=d.schemaVersion===s.doctorFixResult.schemaVersion?d:d.fixResult,a=C(n),f=typeof a?.generatedAt=="string"?a.generatedAt:void 0,y=R(f,s$1,"Doctor fix result");y?c={status:"fail",message:y}:await Fe(t,f)?c={status:"skipped",message:"No current doctor remediation steps are pending."}:c=Ve(d);}else if(e.id.startsWith("project."))c=De(d,e,s$1);else {let n=R(d.generatedAt,s$1,"Evidence report");n?c={status:"fail",message:n}:c={status:"pass",message:"Evidence report is present."};}return {id:e.id,label:e.label,scope:e.scope,project:e.project,command:e,status:c.status,required:e.required,evidencePath:o,message:c.message}}function Ne(e,t={blockingReasons:[],needsAttention:false}){let r=e.filter(n=>n.status==="pass").length,s=e.filter(n=>n.status==="warn").length,i=e.filter(n=>n.status==="fail").length,o=e.filter(n=>n.status==="missing").length,k=e.filter(n=>n.status==="skipped").length,u=e.filter(n=>n.required&&(n.status==="fail"||n.status==="missing")).map(n=>`${n.id}: ${n.message}`),d=e.filter(n=>n.required&&n.status==="missing").length,g="ready",c=0;return u.length>0||t.blockingReasons.length>0?(g="blocked",c=2):(s>0||e.some(n=>!n.required&&n.status==="fail")||d>0||t.needsAttention)&&(g="needs-attention",c=1),{verdict:g,exitCode:c,stepsPassed:r,stepsWarn:s,stepsFailed:i,stepsMissing:o,stepsSkipped:k}}function He(e,t){let r=x(e.affectedProjects.map(a=>a.project?.name).filter(a=>typeof a=="string")),s=new Set(r.map(a=>a.toLowerCase())),i=x(e.transitiveImpact.map(a=>a.project?.name).filter(a=>typeof a=="string").filter(a=>!s.has(a.toLowerCase()))),o=new Map;for(let a of t){if(a.scope!=="project"||!a.project)continue;let f=a.project.toLowerCase(),y=o.get(f)??[];y.push(a),o.set(f,y);}let k=[],u=[],d=[],g=[],c=false,n=(a,f)=>{let y=o.get(a.toLowerCase())??[];if(y.length===0){d.push(a);return}let P=y.filter(p=>p.status==="fail"),b=P.filter(p=>p.required),I=y.filter(p=>p.status==="missing"),E=I.filter(p=>p.required),V=y.some(p=>p.status==="pass"||p.status==="warn");if(b.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has failed verification evidence (${b.map(p=>p.id).join(", ")}).`);return}if(P.length>0){u.push(a),c=true;return}if(E.length>0){u.push(a),g.push(`graph.subgraph.${a}: ${f} has missing required verification evidence (${E.map(p=>p.id).join(", ")}).`);return}if(I.length>0){u.push(a),c=true;return}if(V){k.push(a);return}d.push(a);};for(let a of r)n(a,"directly-changed");for(let a of i)n(a,"transitive dependent");return {subgraph:{totalProjects:r.length+i.length,directlyChanged:r,transitiveDependents:i,covered:x(k),uncovered:x(u),unverifiable:x(d)},blockingReasons:g,needsAttention:c}}function x(e){return [...new Set(e)].sort((t,r)=>t.localeCompare(r))}async function Me(e){let t=m.resolve(e.workspacePath);if(e.fromImpactPath){let o=Ae(t,e.fromImpactPath);return {impact:await ke(o),fromImpactRef:m.relative(t,o).split(m.sep).join("/"),impactFromDisk:true}}let r=m.join(t,g$1);if(await v.pathExists(r))return {impact:await ke(r),fromImpactRef:g$1,impactFromDisk:true};let s=m.join(t,d$3);if(await v.pathExists(s))return {impact:await p$1({workspacePath:t,fromPath:d$3,scope:e.scope,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}),fromImpactRef:d$3,impactFromDisk:false};let i=await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now});return {impact:{schemaVersion:f,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",diffRef:p.diff,workspace:{name:i.workspace.name,profile:i.workspace.profile,type:i.workspace.type},summary:{changed:false,risk:"none",affectedProjects:0,workspaceItems:0,recommendedCommands:0,blastRadius:{directlyAffected:0,transitivelyAffected:0,maxDistance:0,graphEdges:m$1(i)?.edges.length??0}},affectedProjects:[],transitiveImpact:[],criticalPathHotspots:[],workspaceImpact:[],verificationPlan:[],agentBrief:{headline:"Baseline workspace verify run.",bullets:["No impact report or snapshot was available; baseline gates were evaluated."],unsafeAssumptions:["Do not claim runtime verification passed unless evidence exists."]},diff:{schemaVersion:q.diff,generatedAt:(e.now??new Date).toISOString(),fromRef:"baseline",toRef:p.model,fromHash:"baseline",toHash:"baseline",summary:{changed:false,addedProjects:0,removedProjects:0,changedProjects:0,workspaceChanges:0,validationChanges:0,gitChangedFiles:0},git:{available:false,dirty:false,changedFiles:0,untrackedFiles:0,deletedFiles:0},changes:[],currentModel:i}},impactFromDisk:false}}function Te(e,t){if(t)return e.generatedAt}async function bt(e){let t=m.resolve(e.workspacePath),{impact:r,fromImpactRef:s,impactFromDisk:i}=await Me(e),o$1=r.diff.currentModel,k=i?await q$1({workspacePath:t,includeAbsolutePaths:e.includeAbsolutePaths,includeEvidence:e.includeEvidence,observableScanDepth:e.observableScanDepth,now:e.now}):o$1,u=[];if(i){let l=await p$1({workspacePath:t,fromPath:r.diff.fromRef,diff:r.diff,scope:e.scope,now:e.now}),W=[r.affectedProjects,r.transitiveImpact,r.verificationPlan],A=[l.affectedProjects,l.transitiveImpact,l.verificationPlan];JSON.stringify(W)!==JSON.stringify(A)&&u.push("workspace.impact: Persisted impact semantics do not match the impact re-derived from the embedded diff. Regenerate diff and impact.");}i&&d(k)!==r.diff.toHash&&u.push("workspace.impact: Impact evidence is stale because the current workspace model no longer matches the embedded model. Regenerate diff and impact.");let d$2=r.diff.git;if(i&&d$2?.available){let l=a(t,{ref:d$2.ref}),W=r.diff.changes.filter(h=>h.type.startsWith("git.")).map(h=>`${h.type}:${h.target.replace(/^git:/,"")}`).sort(),A=[...l.changedFiles.map(h=>`git.file.changed:${h}`),...l.untrackedFiles.map(h=>`git.untracked:${h}`),...l.deletedFiles.map(h=>`git.deleted:${h}`)].sort();(!l.available||l.commit!==d$2.commit||JSON.stringify(A)!==JSON.stringify(W))&&u.push("workspace.impact: Impact evidence is stale because Git changes no longer match the diff observation. Regenerate diff and impact.");}let g=Te(r,i),c$1=Ee([...o(),...r.verificationPlan]).filter(l=>Se(e.scope,l)),n=[];for(let l of c$1)n.push(await _e(l,t,o$1.contracts.exists===true,g));let a$2=He(r,n),f=a$1(m$1(o$1)??{nodes:[],edges:[]}),y=b(o$1),P=await Ke(t),b$2=c(y,P?.freshness?.projectHashes),I={verdict:b$2.verdict,baseline:b$2.baseline,changed:b$2.changed,added:b$2.added,removed:b$2.removed,projectHashes:d$1(y)},E=b$1(f),V=o$1.policies?.mode??"warn",p=await Le(o$1,t),B=qe(V,p),S=Ne(n,{blockingReasons:[...a$2.blockingReasons,...E,...B.blockingReasons,...u],needsAttention:a$2.needsAttention||B.needsAttention}),he=n.filter(l=>l.status==="missing"&&l.evidencePath).map(l=>l.evidencePath),_=[...n.filter(l=>l.required&&(l.status==="fail"||l.status==="missing")).map(l=>`${l.id}: ${l.message}`),...a$2.blockingReasons,...E,...B.blockingReasons,...u],ve=p.filter(l=>l.severity==="error").length,be=o$1.summary?.projectCount??o$1.projects.length,U=ge({projectCount:be,verdict:S.verdict,exitCode:S.exitCode,blockingReasons:_,policyErrorCount:ve});S.verdict=U.verdict,S.exitCode=U.exitCode;let Y=Array.from(new Set(_.map(l=>l.trim()).filter(Boolean))).slice(0,12).map((l,W)=>{let A=n.find(h=>l.startsWith(`${h.id}:`));return me({reason:l,blockerId:`blocker-${W+1}`,sourceCommand:A?.command.display,sourceArtifact:A?.evidencePath,verifyCommand:"npx workspai workspace verify --from-impact .workspai/reports/workspace-impact-last-run.json --json",verifyArtifact:G})});return {schemaVersion:ye,generatedAt:(e.now??new Date).toISOString(),workspacePath:t,mode:"evidence",fromImpactRef:s,scope:e.scope,impact:{changed:r.summary.changed,risk:r.summary.risk,affectedProjects:r.summary.affectedProjects,recommendedCommands:r.summary.recommendedCommands},summary:S,steps:n,missingEvidence:he,blockingReasons:_,...Y.length>0?{resolutionHints:Y}:{},verificationPlan:c$1,affectedSubgraph:a$2.subgraph,graphIntegrity:f,freshness:I,policyMode:V,policyViolations:p}}async function Le(e,t){let r=[];for(let i of e.validation?.issues??[])r.push({source:"model",severity:i.severity,code:i.code,message:i.message,target:i.target});let s=await g(t,p.contractVerify);try{if(s&&await v.pathExists(s)){let i=await v.readJson(s);if(Array.isArray(i.violations))for(let o of i.violations)typeof o=="string"&&o.trim().length>0&&r.push({source:"contract",severity:"error",code:"contract.violation",message:o});}}catch{}return r.sort((i,o)=>i.source!==o.source?i.source.localeCompare(o.source):i.code!==o.code?i.code.localeCompare(o.code):i.message.localeCompare(o.message))}function qe(e,t){let r=t.filter(s=>s.severity==="error");return e==="enforce"&&r.length>0?{blockingReasons:r.map(s=>`policy.${s.code}: ${s.message}`),needsAttention:false}:{blockingReasons:[],needsAttention:r.length>0}}async function Ke(e){let t=m.join(e,G);try{if(!await v.pathExists(t))return null;let r=await v.readJson(t);return r&&r.schemaVersion===ye?r:null}catch{return null}}async function wt(e,t){return h(t,G,d$2(e))}function ze(e,t){let r=t?.strict?"strict":"default",s=[];if(e.summary.verdict==="blocked")return s.push(...e.blockingReasons),s.length===0&&s.push("verify verdict is blocked."),{passed:false,mode:r,exitCode:2,reasons:s};if(r==="strict"){if(e.summary.verdict!=="ready"&&s.push(`verify verdict is ${e.summary.verdict} (strict requires ready).`),e.freshness.verdict==="stale"){let i=[...e.freshness.changed,...e.freshness.added].slice(0,5);s.push(`freshness is stale${i.length>0?`: ${i.join(", ")}`:""} (strict requires fresh).`);}if(s.length>0)return {passed:false,mode:r,exitCode:1,reasons:s}}return {passed:true,mode:r,exitCode:0,reasons:s}}function Rt(e,t){return ze(e,t).exitCode}export{fe as a,tt as b,ye as c,G as d,He as e,bt as f,wt as g,ze as h,Rt as i};
@@ -1,4 +1,4 @@
1
- import {a}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-I7P6XQJI.js';import {l,q}from'./chunk-5NL53T5C.js';import {f as f$1,g,h as h$2}from'./chunk-S66NO5BX.js';import {a as a$2}from'./chunk-TDQ2PRHV.js';import {i,h as h$1,d,b as b$1,c as c$2,a as a$3,k as k$2}from'./chunk-FE5R6EUV.js';import {b as b$3}from'./chunk-K33JJVQZ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {h,i as i$1,m,k as k$1,n,o,l as l$1,j,s,f as f$2,g as g$1,e}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {randomUUID,createHash}from'crypto';import C from'path';import N from'fs-extra';var Xe=new Set(["committed","rejected","aborted","superseded"]);function f(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function Qe(e){return [...new Set(e)].sort()}function _e(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function je(e,t,a){f(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function Ze(e,t){je(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return f(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function et(e,t,a){return je(e.verifications,t.id,"verification"),f(t.target.effectHeadDigest===_e(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function tt(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function at(e$1,t,a){if(t.kind==="created"){f(e$1===null,"created must be the first event");let y=t.payload.references?.[0];f(y,"created must bind an intent artifact");let h=t.payload.references?.filter(g=>g.role==="success-criterion").map(g=>g.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:y,requiredCriteria:Qe(h),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}f(e$1,`${t.kind} cannot occur before created`),f(!Xe.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,i=e$1.scope,n=e$1.evidence,s=e$1.plans,c=e$1.authorization,d=e$1.effects,o=e$1.verifications,l=e$1.blockers,w=e$1.terminalReason;switch(t.kind){case "scope-bound":f(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),f(t.payload.scope,"scope-bound requires scope"),i=t.payload.scope,r="scoped";break;case "evidence-attached":f(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),f((t.payload.references?.length??0)>0,"evidence-attached requires references"),n=[...n,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":f(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),f((t.payload.references?.length??0)>0,"plan-attached requires references"),s=[...s,...t.payload.references??[]];break;case "authorized":f(e$1.state==="evidence-ready","authorization requires evidence-ready state"),f(t.payload.authorization,"authorized requires a bounded authorization grant"),c=t.payload.authorization,r="authorized";break;case "effect-requested":f(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":f(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),f(t.payload.effect,"effect-recorded requires a receipt"),f(c?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),d=Ze(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(l=[...l,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":f(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",l=[...l,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":f(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{f(e$1.state==="verifying","verification-recorded requires verifying state"),f(t.payload.verification,"verification-recorded requires a receipt"),o=et(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":f(t.payload.blocker,"blocked requires a structured blocker"),l=[...l,t.payload.blocker],r="blocked";break;case "resumed":f(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),f(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,l=[];break;case "committed":f(e$1.state==="verifying","commit requires verifying state"),f(tt(e$1),"every required criterion needs a latest passing receipt"),f(!e$1.effects.some(y=>y.status!=="succeeded"),"all effects must be certainly successful"),r="committed",w=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,w=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:i,evidence:n,plans:s,authorization:c,effects:d,verifications:o,blockers:l,...w?{terminalReason:w}:{}}}function Ke(e,t,a,r){let i=(t?.sequence??0)+1,n={schemaVersion:f$2,transactionId:e,sequence:i,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...n,digest:r.digestCanonical(n)}}function U(e,t){f(e.length>0,"at least one event is required");let a=null,r=null;for(let i of e){f(i.schemaVersion===f$2,`unsupported event schema ${i.schemaVersion}`),f(i.sequence===(r?.sequence??0)+1,`event sequence ${i.sequence} is not contiguous`),f(i.previousEventDigest===(r?.digest??null),`event ${i.sequence} has an invalid previous digest`);let{digest:n,...s}=i;f(i.digest===t.digestCanonical(s),`event ${i.sequence} digest is invalid`),f(!r||i.transactionId===r.transactionId,"events cross transaction boundaries"),a=at(a,i,t),r=i;}return a}function ie(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function B(e,t){return _e(e,t)}var T={digestCanonical:c};function it(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function z(e){let a=`.workspai/decisions/${it(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function nt(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,i)=>{try{return JSON.parse(r)}catch(n){throw new Error(`Decision event log is corrupt at ${t}:${i+1}: ${n.message}`)}})}async function qe(e,t){let a=z(t),r=await b$1(e,a.events);return r?nt(await N.readFile(r,"utf8"),r):[]}function ze(e,t){let a=z(t);return {directory:a$3(e,a.directory),transaction:a$3(e,a.transaction),checkpoint:a$3(e,a.checkpoint),events:a$3(e,a.events)}}async function st(e,t,a,r){let i=z(t.id),n=ie(t,r,T);for(let[s,c]of a.entries())a$1(c,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${s+1}`);return b$3(i.transaction,t),b$3(i.checkpoint,n),await k$2(e,i.events,`${a.map(s=>JSON.stringify(s)).join(`
1
+ import {a}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-2BCECNIW.js';import {l,q}from'./chunk-VBMWFT7Q.js';import {f as f$1,g,h as h$2}from'./chunk-R5OJD5K2.js';import {a as a$2}from'./chunk-D3N2WFDV.js';import {i,h as h$1,d,b as b$1,c as c$2,a as a$3,k as k$2}from'./chunk-FE5R6EUV.js';import {b as b$3}from'./chunk-K33JJVQZ.js';import {a as a$1}from'./chunk-AFIFZTOY.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {h,i as i$1,m,k as k$1,n,o,l as l$1,j,s,f as f$2,g as g$1,e}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {randomUUID,createHash}from'crypto';import C from'path';import N from'fs-extra';var Xe=new Set(["committed","rejected","aborted","superseded"]);function f(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function Qe(e){return [...new Set(e)].sort()}function _e(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function je(e,t,a){f(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function Ze(e,t){je(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return f(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function et(e,t,a){return je(e.verifications,t.id,"verification"),f(t.target.effectHeadDigest===_e(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function tt(e){return e.requiredCriteria.every(t=>{let a=e.verifications.filter(r=>r.criterionId===t);return a.length>0&&a.at(-1)?.status==="passed"})}function at(e$1,t,a){if(t.kind==="created"){f(e$1===null,"created must be the first event");let y=t.payload.references?.[0];f(y,"created must bind an intent artifact");let h=t.payload.references?.filter(g=>g.role==="success-criterion").map(g=>g.artifact)??[];return {schemaVersion:e,id:t.transactionId,purpose:"proof-carrying-change",createdAt:t.occurredAt,updatedAt:t.occurredAt,state:"draft",generation:1,eventCount:t.sequence,eventHeadDigest:t.digest,intent:y,requiredCriteria:Qe(h),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}f(e$1,`${t.kind} cannot occur before created`),f(!Xe.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,i=e$1.scope,n=e$1.evidence,s=e$1.plans,c=e$1.authorization,d=e$1.effects,o=e$1.verifications,l=e$1.blockers,w=e$1.terminalReason;switch(t.kind){case "scope-bound":f(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),f(t.payload.scope,"scope-bound requires scope"),i=t.payload.scope,r="scoped";break;case "evidence-attached":f(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),f((t.payload.references?.length??0)>0,"evidence-attached requires references"),n=[...n,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":f(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),f((t.payload.references?.length??0)>0,"plan-attached requires references"),s=[...s,...t.payload.references??[]];break;case "authorized":f(e$1.state==="evidence-ready","authorization requires evidence-ready state"),f(t.payload.authorization,"authorized requires a bounded authorization grant"),c=t.payload.authorization,r="authorized";break;case "effect-requested":f(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":f(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),f(t.payload.effect,"effect-recorded requires a receipt"),f(c?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),d=Ze(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(l=[...l,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":f(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",l=[...l,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":f(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{f(e$1.state==="verifying","verification-recorded requires verifying state"),f(t.payload.verification,"verification-recorded requires a receipt"),o=et(e$1,t.payload.verification,a),r=t.payload.verification.status==="failed"?"blocked":t.payload.verification.status==="inconclusive"?"awaiting-human":"verifying";break}case "human-required":r="awaiting-human";break;case "blocked":f(t.payload.blocker,"blocked requires a structured blocker"),l=[...l,t.payload.blocker],r="blocked";break;case "resumed":f(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),f(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,l=[];break;case "committed":f(e$1.state==="verifying","commit requires verifying state"),f(tt(e$1),"every required criterion needs a latest passing receipt"),f(!e$1.effects.some(y=>y.status!=="succeeded"),"all effects must be certainly successful"),r="committed",w=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,w=t.payload.reason??t.payload.summary;break;default:throw new Error(`Decision protocol violation: unsupported event ${t.kind}`)}return {...e$1,updatedAt:t.occurredAt,state:r,generation:e$1.generation+1,eventCount:t.sequence,eventHeadDigest:t.digest,scope:i,evidence:n,plans:s,authorization:c,effects:d,verifications:o,blockers:l,...w?{terminalReason:w}:{}}}function Ke(e,t,a,r){let i=(t?.sequence??0)+1,n={schemaVersion:f$2,transactionId:e,sequence:i,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...n,digest:r.digestCanonical(n)}}function U(e,t){f(e.length>0,"at least one event is required");let a=null,r=null;for(let i of e){f(i.schemaVersion===f$2,`unsupported event schema ${i.schemaVersion}`),f(i.sequence===(r?.sequence??0)+1,`event sequence ${i.sequence} is not contiguous`),f(i.previousEventDigest===(r?.digest??null),`event ${i.sequence} has an invalid previous digest`);let{digest:n,...s}=i;f(i.digest===t.digestCanonical(s),`event ${i.sequence} digest is invalid`),f(!r||i.transactionId===r.transactionId,"events cross transaction boundaries"),a=at(a,i,t),r=i;}return a}function ie(e,t,a){return {schemaVersion:g$1,transactionId:e.id,generatedAt:t,generation:e.generation,eventCount:e.eventCount,eventHeadDigest:e.eventHeadDigest,state:e.state,transactionDigest:a.digestCanonical(e)}}function B(e,t){return _e(e,t)}var T={digestCanonical:c};function it(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid decision transaction id: ${e}`);return t}function z(e){let a=`.workspai/decisions/${it(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function nt(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,i)=>{try{return JSON.parse(r)}catch(n){throw new Error(`Decision event log is corrupt at ${t}:${i+1}: ${n.message}`)}})}async function qe(e,t){let a=z(t),r=await b$1(e,a.events);return r?nt(await N.readFile(r,"utf8"),r):[]}function ze(e,t){let a=z(t);return {directory:a$3(e,a.directory),transaction:a$3(e,a.transaction),checkpoint:a$3(e,a.checkpoint),events:a$3(e,a.events)}}async function st(e,t,a,r){let i=z(t.id),n=ie(t,r,T);for(let[s,c]of a.entries())a$1(c,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${s+1}`);return b$3(i.transaction,t),b$3(i.checkpoint,n),await k$2(e,i.events,`${a.map(s=>JSON.stringify(s)).join(`
2
2
  `)}
3
3
  `),await h$1(e,i.transaction,t),await h$1(e,i.checkpoint,n),{transaction:t,checkpoint:n,events:a,paths:ze(e,t.id)}}async function Ge(e){let t=z(e.transactionId),a=a$3(e.workspacePath,t.lock);return a$4(a,async()=>{let r=await qe(e.workspacePath,e.transactionId),i=r.at(-1)??null;if((i?.digest??null)!==e.expectedHeadDigest)throw new Error(`Decision transaction head changed: expected ${e.expectedHeadDigest??"<empty>"}, observed ${i?.digest??"<empty>"}`);r.length>0&&U(r,T);let n=Ke(e.transactionId,i,e.event,T),s=[...r,n],c=U(s,T);return st(e.workspacePath,c,s,e.event.occurredAt)},{purpose:`decision:${e.transactionId}`,timeoutMs:3e4,staleMs:6e4})}async function Ne(e,t){let a=await qe(e,t);if(a.length===0)throw new Error(`Decision transaction not found: ${t}`);let r=U(a,T),i=ie(r,r.updatedAt,T);return {transaction:r,checkpoint:i,events:a,paths:ze(e,t)}}function G(e){return z(e).directory}var oe={digestCanonical:c},dt="workspai.deleted-artifact-tombstone.v1";function lt(e){let t=e.trim();if(!/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(t))throw new Error(`Invalid proof-carrying change id: ${e}`);return t}function P(e){let a=`.workspai/changes/${lt(e)}`;return {directory:a,lease:`${a}/lease.json`,prediction:`${a}/predicted-overlay.json`,actualOverlay:`${a}/actual-overlay.json`,surprises:`${a}/architecture-surprises.json`,capsule:`${a}/capsule.json`,privateBaselineGraph:`${a}/private/baseline-graph.json`}}function gt(e,t){return {kind:e,id:t}}function $(e){return {role:e.role,artifact:e.artifact,schemaVersion:e.schemaVersion,digest:{algorithm:"sha256",semantics:e.semantics??"canonical-json-v1",value:e.value}}}async function I(e,t){let a=await b$1(e,t);return a?await N.readJson(a):null}async function ft(e){let a=(await I(e,s.workspaceContract.artifactPath))?.workspace?.name;if(typeof a=="string"&&a.trim())return a.trim();let r=await I(e,".workspai/workspace.json"),i=r?.workspace_name??r?.name;return typeof i=="string"&&i.trim()?i.trim():C.basename(e)}async function ce(e,t){let a=await c$2(e,t.artifact);if(!a)return false;if(t.digest.semantics==="raw-bytes-v1"){let n=await N.readFile(a);return createHash("sha256").update(n).digest("hex")===t.digest.value}let r=await N.readJson(a).catch(()=>null);return r?(t.digest.semantics==="workspace-model-structural-v1"?d$1(r):c(r))===t.digest.value:false}function Me(e){return c({schemaVersion:dt,artifact:H(e),deleted:true})}function ht(e){let t=H(e.artifact);if(!t||t==="."||t===".."||t.startsWith("../"))throw new Error(`Deleted artifact identity must be a contained relative path: ${e.artifact}`);return {artifact:t,observedAt:e.observedAt??new Date().toISOString(),digest:{algorithm:"sha256",semantics:"deletion-tombstone-v1",value:Me(t)}}}async function Le(e,t){if(t.digest.algorithm!=="sha256"||t.digest.semantics!=="deletion-tombstone-v1"||t.digest.value!==Me(t.artifact))return false;let a=await d(e,t.artifact);return a!==null&&!await N.pathExists(a)}async function pt(e,t){let a=await I(e,P(t).lease);if(!a||a.schemaVersion!==h)throw new Error(`Architecture lease is missing or unsupported for ${t}.`);if(a.changeId!==t)throw new Error(`Architecture lease binding failed for ${t}.`);return a}async function F(e){let t=await a$2(e);if(t.status==="miss")throw new Error(`A current canonical Model and Graph are required (${t.reason}). Run workspai workspace intelligence run --for-agent generic --strict --json.`);return t}function ut(e,t,a){return c({modelHash:e,graphHash:t,inputHash:a})}function Y(e){let t=d$1(e.model),a=c(e.graph),r=e.graph.source.inputs?.hash;if(!r)throw new Error("The canonical Graph has no live input fingerprint.");return {modelHash:t,graphHash:a,inputHash:r,generation:ut(t,a,r)}}async function Ue(e,t){let a=await F(e),r=Y(a);if(r.generation!==t.generation)throw new Error(`Architecture lease ${t.changeId} is stale. Expected generation ${t.generation}, observed ${r.generation}. Abort or begin a new change from current evidence.`);return a}function v(e,t,a,r,i=new Date().toISOString()){return {kind:e,payload:t,occurredAt:i,actor:gt(a,r)}}async function k(e,t,a,r){return Ge({workspacePath:e,transactionId:a,expectedHeadDigest:t?.transaction.eventHeadDigest??null,event:r})}function S(e,t,a){return `${e}\0${t}\0${a}`}function mt(e){let t=[];for(let[a,r]of [["entity",e.entities],["relation",e.relations],["proof",e.proofs]])t.push(...r.added.map(i=>({operation:"add",targetKind:a,targetId:i.id}))),t.push(...r.removed.map(i=>({operation:"remove",targetKind:a,targetId:i.id}))),t.push(...r.changed.map(i=>({operation:"change",targetKind:a,targetId:i.id})));return t.push(...e.changedArtifacts.map(a=>({operation:"change",targetKind:"artifact",targetId:a}))),t.sort((a,r)=>S(a.operation,a.targetKind,a.targetId).localeCompare(S(r.operation,r.targetKind,r.targetId)))}function yt(e){let t=e.prediction?.operations.map(o=>({operation:o.operation,targetKind:o.targetKind,targetId:o.targetId}))??[],a=mt(e.actual),r=new Set(t.map(o=>S(o.operation,o.targetKind,o.targetId))),i=new Set(a.map(o=>S(o.operation,o.targetKind,o.targetId))),n=a.filter(o=>r.has(S(o.operation,o.targetKind,o.targetId))),s=a.filter(o=>!r.has(S(o.operation,o.targetKind,o.targetId))),c=t.filter(o=>!i.has(S(o.operation,o.targetKind,o.targetId))),d=e.prediction?s.length===0&&c.length===0?"exact":s.length===0?"within-expectation":"surprising":"no-prediction";return {schemaVersion:j,changeId:e.changeId,generatedAt:e.generatedAt,prediction:e.predictionReference,actual:e.actualReference,matched:n,unpredicted:s,missing:c,summary:{predicted:t.length,actual:a.length,matched:n.length,unpredicted:s.length,missing:c.length,verdict:d}}}async function ne(e){let t=await I(e.workspacePath,e.relativePath);return t?$({role:e.role,artifact:e.relativePath,schemaVersion:e.schemaVersion,value:c(t)}):null}function wt(e){let{integrity:t,...a}=e;return a}async function de(e){let t=P(e.lease.changeId),[a,r,i]=await Promise.all([ne({workspacePath:e.workspacePath,relativePath:t.prediction,role:"prediction",schemaVersion:i$1}),ne({workspacePath:e.workspacePath,relativePath:t.actualOverlay,role:"actual-architecture-overlay",schemaVersion:a$5}),ne({workspacePath:e.workspacePath,relativePath:t.surprises,role:"architecture-surprises",schemaVersion:j})]),n=$({role:"decision-transaction",artifact:`${G(e.lease.changeId)}/transaction.json`,schemaVersion:e.record.transaction.schemaVersion,value:c(e.record.transaction)}),s=e.record.transaction.effects.flatMap(p=>p.artifacts),c$1=e.record.transaction.effects.flatMap(p=>p.deletedArtifacts??[]),d=e.record.transaction.verifications.flatMap(p=>p.artifacts),o=await I(e.workspacePath,t.actualOverlay),l=o?!se(o):false,w=[{id:"intent-bound",status:"passed",summary:"The transaction is hash-bound to its immutable Goal Pack."},{id:"baseline-pinned",status:"passed",summary:"The architecture lease pins exact Model, Graph, and live-input identities."},{id:"effects-receipted",status:e.record.transaction.effects.length>0&&e.record.transaction.effects.every(p=>p.status==="succeeded")||e.record.transaction.effects.length===0&&l?"passed":e.record.transaction.effects.length===0?"pending":"failed",summary:e.record.transaction.effects.length===0&&l?"Fresh Graph observation proves this was a no-effect change.":`${e.record.transaction.effects.length} typed effect receipt(s) are bound to the transaction ledger.`},{id:"architecture-reobserved",status:r?"passed":"pending",summary:r?"The actual architecture delta was derived from a fresh canonical Graph.":"No post-effect architecture overlay has been observed yet."},{id:"independently-verified",status:e.record.transaction.state==="committed"?"passed":e.record.transaction.verifications.some(p=>p.status==="failed")?"failed":"pending",summary:`${e.record.transaction.verifications.length} independent verification receipt(s) are recorded.`}],y=await I(e.workspacePath,t.surprises),h=[...e.record.transaction.effects.length===0&&o&&se(o)?["No typed effect receipt explains the observed architecture generation."]:[],...y?.summary.unpredicted?[`${y.summary.unpredicted} actual architecture operation(s) were not predicted.`]:[],...e.record.transaction.blockers.map(p=>p.details??p.code)],g=e.record.transaction.state==="committed"?"sealed":e.record.transaction.state==="aborted"?"aborted":e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="verifying"&&e.record.transaction.verifications.some(p=>p.status==="passed")?"verified":"open",m={schemaVersion:k$1,changeId:e.lease.changeId,goalId:e.lease.goalId,generatedAt:e.record.transaction.updatedAt,status:g,workspace:e.lease.workspace,scope:e.lease.scope,decision:{transaction:n,eventHeadDigest:e.record.transaction.eventHeadDigest,effectHeadDigest:B(e.record.transaction,oe),state:e.record.transaction.state,generation:e.record.transaction.generation},intent:e.record.transaction.intent,baseline:e.lease.baseline,prediction:a,actualOverlay:r,surpriseReport:i,effects:s,deletedArtifacts:c$1,verification:d,assurances:w,remainingUncertainty:[...new Set(h)]};return {...m,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(m)}}}async function D(e,t,a){let r=await de({workspacePath:e,lease:t,record:a});return await h$1(e,P(t.changeId).capsule,r),r}function b(e){let t=P(e.lease.changeId),a={schemaVersion:l$1,operation:e.operation,changeId:e.lease.changeId,state:e.record.transaction.state,capsule:e.capsule,artifacts:{lease:t.lease,prediction:e.capsule.prediction?.artifact??null,actualOverlay:e.capsule.actualOverlay?.artifact??null,surpriseReport:e.capsule.surpriseReport?.artifact??null,transaction:`${G(e.lease.changeId)}/transaction.json`,events:`${G(e.lease.changeId)}/events.jsonl`,capsule:t.capsule},nextActions:e.nextActions};return a$1(a,"contracts/workspace-intelligence/change-operation-result.v1.json","Proof-Carrying Change operation result"),b$2({kind:"operation.completed",status:e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="aborted"?"cancelled":"succeeded",component:"proof-carrying-change",correlationId:e.lease.changeId,message:`${e.operation}: ${e.record.transaction.state}`,evidenceBindings:[{kind:"artifact",ref:t.capsule,role:"output",provenance:"authoritative"},{kind:"artifact",ref:`${G(e.lease.changeId)}/transaction.json`,role:"subject",provenance:"authoritative"}],attributes:{operation:e.operation,changeId:e.lease.changeId,goalId:e.lease.goalId,decisionState:e.record.transaction.state,assurancePassed:e.capsule.assurances.filter(r=>r.status==="passed").length,assuranceTotal:e.capsule.assurances.length}}),a}async function E(e,t){let a=await pt(e,t),r=await Ne(e,t);return {lease:a,record:r}}async function Yt(e){let t=C.resolve(e.workspacePath),a=await l({workspacePath:t,goalId:e.goalId,validateBindings:true}),r=a.goalPack;if(!r||!a.active)throw new Error("No active Goal Pack is available, or the named Goal is not active.");if(r.state!=="ready-to-plan")throw new Error(`Goal ${r.id} cannot begin a change while its state is ${r.state}.`);let i$1=await F(t),n=Y(i$1);if(n.modelHash!==r.sourceBinding.model.hash||(r.sourceBinding.graph.inputHash?n.inputHash!==r.sourceBinding.graph.inputHash:n.graphHash!==r.sourceBinding.graph.hash))throw new Error(`Goal ${r.id} is no longer bound to the current architecture generation.`);let s=`change-${r.intent.category}-${randomUUID().replace(/-/g,"").slice(0,16)}`,c$1=P(s),d=new Date().toISOString(),o=c(i$1.graph),l$1={schemaVersion:h,changeId:s,goalId:r.id,createdAt:d,workspace:r.workspace,scope:{kind:r.scope.kind,projects:[...r.scope.projects]},baseline:{model:$({role:"baseline-model",artifact:r.sourceBinding.model.artifact,schemaVersion:r.sourceBinding.model.schemaVersion,value:r.sourceBinding.model.hash,semantics:"workspace-model-structural-v1"}),graph:{...$({role:"baseline-graph",artifact:r.sourceBinding.graph.artifact,schemaVersion:r.sourceBinding.graph.schemaVersion,value:n.graphHash}),inputHash:n.inputHash}},generation:n.generation,semantics:"optimistic-generation-guard",privateMaterialization:{artifact:c$1.privateBaselineGraph,role:"hash-bound-baseline-cache",portable:false,authoritative:false,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:o}}};await i(t,c$1.lease,[{relativePath:c$1.privateBaselineGraph,payload:i$1.graph},{relativePath:c$1.lease,payload:l$1}]);let w=e.actorKind??"cli",y=e.actorId??"workspai-change",h$1=$({role:"intent",artifact:a.active.goalPack,schemaVersion:r.schemaVersion,value:c(r)}),g=r.successCriteria.map(_=>$({role:"success-criterion",artifact:_.id,schemaVersion:"workspai.goal-success-criterion.v1",value:c(_)})),m=await k(t,null,s,v("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[h$1,...g]},w,y,d));m=await k(t,m,s,v("scope-bound",{summary:"Bind immutable Goal scope.",scope:l$1.scope},w,y)),m=await k(t,m,s,v("evidence-attached",{summary:"Attach exact architecture generation and lease.",references:[l$1.baseline.model,{role:l$1.baseline.graph.role,artifact:l$1.baseline.graph.artifact,schemaVersion:l$1.baseline.graph.schemaVersion,digest:l$1.baseline.graph.digest},$({role:"architecture-lease",artifact:c$1.lease,schemaVersion:l$1.schemaVersion,value:c(l$1)})]},w,y)),await q({workspacePath:t,goalId:r.id,changeId:s});let p=await D(t,l$1,m);return b({operation:"begin",lease:l$1,record:m,capsule:p,nextActions:[`workspai change predict --change ${s} --file <prediction.json> --json`,`workspai change authorize --change ${s} --effects filesystem,command --json`]})}async function Xt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(await Ue(e.workspacePath,t),a.transaction.state!=="evidence-ready")throw new Error(`Prediction requires evidence-ready state, observed ${a.transaction.state}.`);let r={...e.prediction,schemaVersion:i$1,changeId:e.changeId,goalId:t.goalId,baselineGeneration:t.generation,nonCanonical:true,proofEligible:false,operations:[...e.prediction.operations].sort((c,d)=>S(c.operation,c.targetKind,c.targetId).localeCompare(S(d.operation,d.targetKind,d.targetId)))};await h$1(e.workspacePath,P(e.changeId).prediction,r);let i=$({role:"noncanonical-prediction",artifact:P(e.changeId).prediction,schemaVersion:r.schemaVersion,value:c(r)}),n=await k(e.workspacePath,a,e.changeId,v("plan-attached",{summary:"Attach an explicitly noncanonical architecture prediction.",references:[i]},e.actorKind??"agent",e.actorId??"workspai-agent")),s=await D(e.workspacePath,t,n);return b({operation:"predict",lease:t,record:n,capsule:s,nextActions:[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]})}async function Qt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(await Ue(e.workspacePath,t),e.effectClasses.length===0)throw new Error("Authorization requires at least one effect class.");let r=await k(e.workspacePath,a,e.changeId,v("authorized",{summary:`Authorize bounded effect classes: ${e.effectClasses.join(", ")}.`,authorization:{grantedBy:e.grantedBy,grant:"bounded-effects",effectClasses:[...new Set(e.effectClasses)].sort()}},e.actorKind??"human",e.grantedBy)),i=await D(e.workspacePath,t,r);return b({operation:"authorize",lease:t,record:r,capsule:i,nextActions:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`,`workspai change verify --change ${e.changeId} --json`]})}async function Zt(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId);if(a.transaction.state!=="blocked"&&a.transaction.state!=="awaiting-human")throw new Error(`Resume requires blocked or awaiting-human state, observed ${a.transaction.state}.`);let r=await k(e.workspacePath,a,e.changeId,v("resumed",{summary:e.reason,reason:e.reason,resumeTo:e.resumeTo},"human",e.actorId)),i=await D(e.workspacePath,t,r);return b({operation:"resume",lease:t,record:r,capsule:i,nextActions:e.resumeTo==="verifying"?[`workspai change verification record --change ${e.changeId} --file <verification-receipt.json> --json`]:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`]})}async function ea(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=new Set(e.receipt.artifacts.map(c=>H(c.artifact))),i=(e.receipt.deletedArtifacts??[]).map(c=>H(c.artifact));if(new Set(i).size!==i.length)throw new Error("Effect receipt contains duplicate deleted-artifact identities.");if(i.some(c=>r.has(c)))throw new Error("An effect artifact cannot be both present and deleted in one receipt.");if(i.length>0&&e.receipt.status!=="succeeded")throw new Error("Only a succeeded effect may carry deleted-artifact tombstones.");for(let c of e.receipt.artifacts)if(!await ce(e.workspacePath,c))throw new Error(`Effect artifact is missing or corrupt: ${c.artifact}`);for(let c of e.receipt.deletedArtifacts??[])if(!await Le(e.workspacePath,c))throw new Error(`Deleted effect artifact is present, outside the governed scope, or has an invalid tombstone: ${c.artifact}`);let n=await k(e.workspacePath,a,e.changeId,v("effect-recorded",{summary:e.receipt.summary,effect:e.receipt},e.actorKind??"agent",e.actorId??"workspai-agent")),s=await D(e.workspacePath,t,n);return b({operation:"effect-record",lease:t,record:n,capsule:s,nextActions:n.transaction.state==="blocked"?[`workspai change status --change ${e.changeId} --json`]:[`workspai change verify --change ${e.changeId} --json`]})}async function ta(e){let t=C.resolve(e.workspacePath),{lease:a,record:r}=await E(t,e.changeId);if(!r.transaction.requiredCriteria.includes(e.receipt.criterionId))throw new Error(`Verification criterion '${e.receipt.criterionId}' is outside the immutable Goal contract.`);let i=await F(t),n=P(e.changeId),[s,c]=await Promise.all([I(t,n.actualOverlay),I(t,n.surprises)]),d=r.transaction.verifications.some(m=>m.criterionId==="workspace-verify"&&m.status==="passed");if(!s||!c||!d)throw new Error("Domain verification can be admitted only after change verify re-observes the Graph and records a passing Workspace Verify receipt.");let o=Y(i),l=B(r.transaction,oe);if(e.receipt.target.modelHash!==o.modelHash||e.receipt.target.graphHash!==o.graphHash||e.receipt.target.effectHeadDigest!==l)throw new Error("Verification receipt does not target the current Model, Graph, and effect head.");for(let m of e.receipt.artifacts)if(!await ce(t,m))throw new Error(`Verification artifact is missing or corrupt: ${m.artifact}`);let w=e.actorKind??"ci",y=e.actorId??"workspai-verifier",h=r;if(h.transaction.state==="blocked"){if(!h.transaction.blockers.every(p=>p.code==="change.verification.criteria_missing"))throw new Error("The change is blocked by a condition that a verification receipt cannot resume.");h=await k(t,h,e.changeId,v("resumed",{summary:"Resume to admit a missing verification receipt.",resumeTo:"verifying"},w,y));}else if(h.transaction.state!=="verifying")throw new Error(`Verification receipt requires verifying or criteria-blocked state; observed ${h.transaction.state}.`);h=await k(t,h,e.changeId,v("verification-recorded",{summary:e.receipt.summary,verification:e.receipt},w,y)),h.transaction.state==="verifying"&&h.transaction.requiredCriteria.every(p=>h.transaction.verifications.filter(W=>W.criterionId===p).at(-1)?.status==="passed")&&(h=await k(t,h,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},w,y)));let g=await D(t,a,h);return b({operation:"verification-record",lease:a,record:h,capsule:g,nextActions:h.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}function J(e,t,a,r="verification"){return $({role:r,artifact:e,schemaVersion:t,value:c(a)})}function se(e){return e.summary.entityAdds+e.summary.entityRemovals+e.summary.entityChanges+e.summary.relationAdds+e.summary.relationRemovals+e.summary.relationChanges+e.summary.proofAdds+e.summary.proofRemovals+e.summary.proofChanges>0}function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function We(e){let t=C.normalize(C.resolve(e));return process.platform==="win32"?t.toLowerCase():t}async function vt(e){let t=new Set(e.receiptedArtifacts.map(H)),a=new Set;for(let i of t){let n=await d(e.workspacePath,i);n&&a.add(We(n));}let r=[];for(let i of e.changedArtifacts){let n=H(i);if(t.has(n))continue;let s=await d(e.workspacePath,n);s&&a.has(We(s))||r.push(i);}return r}async function aa(e){let t=C.resolve(e.workspacePath),{lease:a$1,record:r}=await E(t,e.changeId);if(r.transaction.state!=="authorized"&&r.transaction.state!=="executing")throw new Error(`Verification requires authorized or executing state, observed ${r.transaction.state}.`);e.refresh!==false&&await c$1({workspacePath:t,strict:false,agent:"generic"});let i=await F(t),n=await I(t,a$1.privateMaterialization.artifact);if(!n||c(n)!==a$1.privateMaterialization.digest.value)throw new Error(`The hash-bound baseline materialization is missing or corrupt for ${e.changeId}.`);let s=new Date().toISOString(),c$2=a(n,i.graph,new Date(s)),d=P(e.changeId);await h$1(t,d.actualOverlay,c$2);let o=J(d.actualOverlay,c$2.schemaVersion,c$2,"actual-architecture-overlay"),l=await I(t,d.prediction),w=l?J(d.prediction,l.schemaVersion,l,"noncanonical-prediction"):null,y=yt({changeId:e.changeId,generatedAt:s,prediction:l,predictionReference:w,actual:c$2,actualReference:o});await h$1(t,d.surprises,y);let h=J(d.surprises,y.schemaVersion,y,"architecture-surprises"),g$1=r,m=e.actorKind??"cli",p=e.actorId??"workspai-change-verify";if(se(c$2)&&g$1.transaction.effects.length===0){g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Observed architecture change has no typed effect receipt.",blocker:{code:"change.effect_receipt.missing",actionable:true,details:"Record the actual mutation effect before verification can claim causality."}},m,p));let A=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:A,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let _=g$1.transaction.effects.filter(A=>A.status==="succeeded").flatMap(A=>[...A.artifacts.map(K=>K.artifact),...(A.deletedArtifacts??[]).map(K=>K.artifact)]),W=await vt({workspacePath:t,changedArtifacts:c$2.changedArtifacts,receiptedArtifacts:_});if(W.length>0){g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Observed architecture artifacts are not covered by typed effect receipts.",blocker:{code:"change.effect_receipt.coverage_missing",actionable:true,details:`Uncovered artifacts: ${W.slice(0,20).join(", ")}`}},m,p));let A=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:A,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Cover observed artifacts" --json`]})}g$1=await k(t,g$1,e.changeId,v("verification-started",{summary:"Begin independent post-effect verification."},m,p));let Be=await f$1({workspacePath:t}),Je=await g(Be,t),X=C.relative(t,Je).split(C.sep).join("/"),j=await I(t,X);if(!j)throw new Error(`Workspace Verify evidence was not persisted at ${X}.`);let O=h$2(j,{strict:e.strict===true}),ge=Y(i),fe={id:`verify-workspace-${c({generatedAt:s,verify:j,gate:O}).slice(0,16)}`,criterionId:"workspace-verify",status:O.passed?"passed":"failed",summary:O.passed?`Workspace Verify passed in ${O.mode} mode.`:`Workspace Verify blocked in ${O.mode} mode: ${O.reasons.join("; ")}`,target:{modelHash:ge.modelHash,graphHash:ge.graphHash,effectHeadDigest:B(g$1.transaction,oe)},artifacts:[J(X,j.schemaVersion,j),o,h],observedAt:s};if(g$1=await k(t,g$1,e.changeId,v("verification-recorded",{summary:fe.summary,verification:fe},m,p)),g$1.transaction.state==="verifying"){let A=g$1.transaction.requiredCriteria.filter(K=>g$1.transaction.verifications.filter(Ye=>Ye.criterionId===K).at(-1)?.status!=="passed");A.length>0?g$1=await k(t,g$1,e.changeId,v("blocked",{summary:"Required outcome verification is incomplete.",blocker:{code:"change.verification.criteria_missing",actionable:true,details:`Missing passing receipts: ${A.join(", ")}`}},m,p)):g$1=await k(t,g$1,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},m,p));}let Fe=await D(t,a$1,g$1);return b({operation:"verify",lease:a$1,record:g$1,capsule:Fe,nextActions:g$1.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}async function ra(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=await de({workspacePath:e.workspacePath,lease:t,record:a});return b({operation:e.operation??"status",lease:t,record:a,capsule:r,nextActions:a.transaction.state==="evidence-ready"?[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]:a.transaction.state==="authorized"||a.transaction.state==="executing"?[`workspai change verify --change ${e.changeId} --json`]:[]})}async function ia(e){let t=C.resolve(e.workspacePath),a=await b$1(t,".workspai/changes","directory"),i=(a?await N.readdir(a,{withFileTypes:true}):[]).filter(d=>d.isDirectory()&&/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(d.name)).map(d=>d.name).sort(),n=[],s=null;for(let d of i)try{let{lease:o,record:l}=await E(t,d);s??=o.workspace.name;let w=await de({workspacePath:t,lease:o,record:l}),y=await le({workspacePath:t,changeId:d});n.push({changeId:d,goalId:o.goalId,state:l.transaction.state,status:w.status,createdAt:l.transaction.createdAt,updatedAt:l.transaction.updatedAt,scope:o.scope,assurance:{passed:w.assurances.filter(h=>h.status==="passed").length,total:w.assurances.length},blockers:l.transaction.blockers.map(h=>h.details??h.code),capsuleArtifact:P(d).capsule,valid:y.valid,errors:y.errors});}catch(o){n.push({changeId:d,goalId:null,state:null,status:"invalid",createdAt:null,updatedAt:null,scope:null,assurance:{passed:0,total:5},blockers:[],capsuleArtifact:P(d).capsule,valid:false,errors:[o instanceof Error?o.message:String(o)]});}n.sort((d,o)=>(o.updatedAt??"").localeCompare(d.updatedAt??"")||d.changeId.localeCompare(o.changeId));let c={schemaVersion:m,generatedAt:new Date().toISOString(),workspace:{name:s??await ft(t)},changes:n,summary:{total:n.length,open:n.filter(d=>d.status==="open"||d.status==="verified").length,blocked:n.filter(d=>d.status==="blocked").length,sealed:n.filter(d=>d.status==="sealed").length,aborted:n.filter(d=>d.status==="aborted").length,invalid:n.filter(d=>!d.valid).length}};return a$1(c,"contracts/workspace-intelligence/proof-carrying-change-list.v1.json","Proof-Carrying Change list"),c}async function na(e){let{lease:t,record:a}=await E(e.workspacePath,e.changeId),r=await k(e.workspacePath,a,e.changeId,v("aborted",{summary:e.reason,reason:e.reason},"human",e.actorId)),i=await D(e.workspacePath,t,r);return b({operation:"abort",lease:t,record:r,capsule:i,nextActions:[]})}async function le(e){let t=P(e.changeId),a=await I(e.workspacePath,t.capsule);if(!a)throw new Error(`Proof-carrying change capsule not found: ${e.changeId}`);let r=[];a.schemaVersion!==k$1&&r.push(`Unsupported capsule schema: ${a.schemaVersion}`),a.changeId!==e.changeId&&r.push("Capsule change binding does not match."),c(wt(a))!==a.integrity.capsuleDigest&&r.push("Capsule integrity digest does not match its canonical content.");let{lease:i,record:n$1}=await E(e.workspacePath,e.changeId),s=n$1.transaction.evidence.find(o=>o.role==="architecture-lease");(!s||s.digest.value!==c(i))&&r.push("Architecture lease does not match the decision-ledger evidence binding."),(i.goalId!==a.goalId||i.generation!==c({modelHash:i.baseline.model.digest.value,graphHash:i.baseline.graph.digest.value,inputHash:i.baseline.graph.inputHash}))&&r.push("Architecture lease identity or generation binding is invalid."),n$1.transaction.eventHeadDigest!==a.decision.eventHeadDigest&&r.push("Capsule does not bind the current decision event head."),c(n$1.transaction)!==a.decision.transaction.digest.value&&r.push("Decision transaction projection digest does not match the capsule.");let c$1=await I(e.workspacePath,i.privateMaterialization.artifact);(!c$1||c(c$1)!==i.privateMaterialization.digest.value)&&r.push("Hash-bound baseline materialization is missing or corrupt.");for(let o of [a.intent,a.decision.transaction,a.prediction,a.actualOverlay,a.surpriseReport,...a.effects,...a.verification].filter(l=>!!l))await ce(e.workspacePath,o)||r.push(`Referenced artifact is missing or corrupt: ${o.artifact}`);for(let o of a.deletedArtifacts??[])await Le(e.workspacePath,o)||r.push(`Deleted artifact tombstone is invalid or the artifact exists again: ${o.artifact}`);let d={schemaVersion:n,changeId:e.changeId,validatedAt:new Date().toISOString(),valid:r.length===0,errors:r,capsule:a};return a$1(d,"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json","Proof-Carrying Change capsule validation"),d}async function sa(e){let t=await le(e);if(!t.valid)throw new Error(`Cannot export an invalid capsule: ${t.errors.join("; ")}`);let a=C.resolve(e.workspacePath),r=C.resolve(a,e.outputPath),i=C.relative(a,r);if(i===".."||i.startsWith(`..${C.sep}`)||C.isAbsolute(i))throw new Error("Capsule export path must remain inside the workspace.");let n=i.split(C.sep).join("/"),s=await h$1(a,n,t.capsule),c={schemaVersion:o,changeId:e.changeId,outputPath:s,validation:t};return a$1(c,"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json","Proof-Carrying Change capsule export"),c}function oa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Prediction input must be a JSON object.");let t=e;if(!Array.isArray(t.operations)||!Array.isArray(t.assumptions))throw new Error("Prediction input requires operations[] and assumptions[].");let a=new Set(["add","remove","change"]),r=new Set(["entity","relation","proof","artifact"]),i=new Set(["high","medium","low"]);for(let s of t.operations)if(!s||!a.has(s.operation)||!r.has(s.targetKind)||typeof s.targetId!="string"||s.targetId.trim().length===0||typeof s.rationale!="string"||!i.has(s.confidence))throw new Error("Prediction contains an invalid operation.");let n=t.predictedRisk;if(!n||!["none","low","medium","high"].includes(n))throw new Error("Prediction requires predictedRisk: none, low, medium, or high.");return {schemaVersion:i$1,changeId:t.changeId??"change-placeholder",goalId:t.goalId??"goal-placeholder",generatedAt:t.generatedAt??new Date().toISOString(),baselineGeneration:t.baselineGeneration??"pending-binding",nonCanonical:true,proofEligible:false,operations:t.operations,assumptions:t.assumptions.filter(s=>typeof s=="string"),predictedRisk:n}}function ca(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Effect receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||!["filesystem","command","configuration","dependency","external"].includes(String(t.effectClass))||!["succeeded","failed","uncertain"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||typeof t.idempotencyKey!="string"||!Array.isArray(t.artifacts))throw new Error("Effect receipt is missing required typed fields.");if(t.deletedArtifacts!==void 0&&(!Array.isArray(t.deletedArtifacts)||t.deletedArtifacts.some(r=>!r||typeof r.artifact!="string"||r.observedAt!==void 0&&typeof r.observedAt!="string"||r.digest!==void 0&&(r.digest.algorithm!=="sha256"||r.digest.semantics!=="deletion-tombstone-v1"||typeof r.digest.value!="string"))))throw new Error("Effect receipt contains an invalid deleted-artifact tombstone.");let a=t;return {...a,...a.deletedArtifacts?{deletedArtifacts:a.deletedArtifacts.map(r=>r.digest?r:ht({artifact:r.artifact,observedAt:r.observedAt??a.observedAt}))}:{}}}function da(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Verification receipt input must be a JSON object.");let t=e;if(typeof t.id!="string"||typeof t.criterionId!="string"||!["passed","failed","inconclusive"].includes(String(t.status))||typeof t.summary!="string"||typeof t.observedAt!="string"||!t.target||typeof t.target.modelHash!="string"||typeof t.target.graphHash!="string"||typeof t.target.effectHeadDigest!="string"||!Array.isArray(t.artifacts))throw new Error("Verification receipt is missing required typed fields.");return t}function la(e,t){return e.decision.eventHeadDigest===t.eventHeadDigest&&e.decision.transaction.digest.value===c(t)}async function ga(e){let t=await le({workspacePath:e.workspacePath,changeId:e.changeId});if(!t.valid)throw new Error(`Proof-carrying change ${e.changeId} failed capsule validation.`);let{lease:a,record:r}=await E(e.workspacePath,e.changeId);if(a.goalId!==e.goalId||r.transaction.state!=="committed"||t.capsule.status!=="sealed")throw new Error(`Proof-carrying change ${e.changeId} is not a sealed change for ${e.goalId}.`);let i=[...r.transaction.verifications].reverse().find(n=>n.status==="passed");if(!i)throw new Error(`Proof-carrying change ${e.changeId} has no passing verification receipt.`);return {modelHash:i.target.modelHash,graphHash:i.target.graphHash}}
4
4
  export{ht as a,Yt as b,Xt as c,Qt as d,Zt as e,ea as f,ta as g,vt as h,aa as i,ra as j,ia as k,na as l,le as m,sa as n,oa as o,ca as p,da as q,la as r,ga as s};