workspai 0.72.1 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/contracts/runtime-command-surface.v1.json +7 -3
  2. package/dist/analyze-IA33T6MY.js +1 -0
  3. package/dist/{artifact-remediation-plan-WDK5ISRU.js → artifact-remediation-plan-OVTQM7HN.js} +1 -1
  4. package/dist/autopilot-release-T327V7QK.js +1 -0
  5. package/dist/chunk-252EKOR6.js +2 -0
  6. package/dist/{chunk-U3RX7KDY.js → chunk-4JJDDL3X.js} +1 -1
  7. package/dist/chunk-5EVBOUYW.js +3 -0
  8. package/dist/chunk-5Y4YRYZI.js +12 -0
  9. package/dist/{chunk-4PDEWMOG.js → chunk-773WUMFU.js} +15 -15
  10. package/dist/{chunk-JPPZDLY3.js → chunk-BTJPTJLT.js} +2 -2
  11. package/dist/{chunk-WMC2H7MJ.js → chunk-C43NXRRE.js} +1 -1
  12. package/dist/chunk-D6BL7ARI.js +2 -0
  13. package/dist/chunk-DLLHUG2Q.js +9 -0
  14. package/dist/chunk-DPC5DKH6.js +2 -0
  15. package/dist/{chunk-S66NO5BX.js → chunk-DTLLIA2C.js} +1 -1
  16. package/dist/{chunk-SS7X2YF5.js → chunk-FYR4FD7K.js} +1 -1
  17. package/dist/chunk-G6ADWA2B.js +2 -0
  18. package/dist/chunk-H333GKL4.js +3 -0
  19. package/dist/{chunk-T6LCDLJ7.js → chunk-H5DRKXXC.js} +1 -1
  20. package/dist/{chunk-KVPTZMEV.js → chunk-HAZGSAKP.js} +1 -1
  21. package/dist/{chunk-FYIPYGMW.js → chunk-IQFXLJIM.js} +1 -1
  22. package/dist/{chunk-JQINCVK5.js → chunk-IUOMBLRR.js} +1 -1
  23. package/dist/chunk-K3FXRBER.js +4 -0
  24. package/dist/{chunk-2RF75G5T.js → chunk-KCIET26G.js} +1 -1
  25. package/dist/chunk-LEEOZRWR.js +7 -0
  26. package/dist/{chunk-RQKDJVX3.js → chunk-NCZJUPG5.js} +49 -49
  27. package/dist/{chunk-IX5Z6EK6.js → chunk-ND5YAC4T.js} +1 -1
  28. package/dist/{chunk-62YBFWHY.js → chunk-RPM67N7A.js} +1 -1
  29. package/dist/chunk-SAZXL36B.js +157 -0
  30. package/dist/chunk-SVGUAVMG.js +1 -0
  31. package/dist/chunk-TBOIXIQA.js +1 -0
  32. package/dist/chunk-TGDXD4CD.js +1 -0
  33. package/dist/{chunk-ISGLADQI.js → chunk-TVSMNF5G.js} +1 -1
  34. package/dist/{chunk-TDQ2PRHV.js → chunk-UHT2SW7O.js} +1 -1
  35. package/dist/chunk-VLKX5U4H.js +13 -0
  36. package/dist/chunk-XF65LQ6M.js +1 -0
  37. package/dist/chunk-YYELANJO.js +7 -0
  38. package/dist/chunk-ZKYH44ER.js +1 -0
  39. package/dist/{chunk-N2PAAQKI.js → chunk-ZNKZ2KXR.js} +1 -1
  40. package/dist/chunk-ZS7JHATN.js +1 -0
  41. package/dist/{create-FOPYAWAR.js → create-EKA2QG5R.js} +1 -1
  42. package/dist/doctor-BXSNADVR.js +1 -0
  43. package/dist/{goal-lifecycle-ZH7AQIOX.js → goal-lifecycle-XXWNMIAD.js} +1 -1
  44. package/dist/{goal-pack-OP453Q6U.js → goal-pack-NTHYLISY.js} +1 -1
  45. package/dist/index.js +158 -158
  46. package/dist/pipeline-JLOC2SUT.js +5 -0
  47. package/dist/{project-agent-entry-QGPM7CU7.js → project-agent-entry-ZNUHGCVC.js} +1 -1
  48. package/dist/{project-intelligence-lens-U7PLWYXX.js → project-intelligence-lens-W72OUEDW.js} +1 -1
  49. package/dist/{project-test-coverage-4BGDDBBL.js → project-test-coverage-5PXAHBYQ.js} +1 -1
  50. package/dist/{proof-carrying-change-6LQ6JO5J.js → proof-carrying-change-WLUPMUO7.js} +1 -1
  51. package/dist/verified-goal-6O2JZOOR.js +1 -0
  52. package/dist/{workspace-3K2YGPU7.js → workspace-XTIGVLGH.js} +1 -1
  53. package/dist/{workspace-agent-sync-TFQNKRD3.js → workspace-agent-sync-TN6QDNBR.js} +1 -1
  54. package/dist/{workspace-context-ZDXF6S7S.js → workspace-context-Y3TNY2XZ.js} +1 -1
  55. package/dist/{workspace-contract-E7GVWM7W.js → workspace-contract-GRZY7WRD.js} +1 -1
  56. package/dist/{workspace-explain-YB66UFAS.js → workspace-explain-KUYHJFLY.js} +1 -1
  57. package/dist/{workspace-foundation-J62BMOQS.js → workspace-foundation-ZBUJTR56.js} +1 -1
  58. package/dist/{workspace-graph-stream-SJUCBPS4.js → workspace-graph-stream-KC2XUAE4.js} +1 -1
  59. package/dist/workspace-graph-token-efficiency-YHXFGH3Z.js +1 -0
  60. package/dist/{workspace-intelligence-3IAAM3H3.js → workspace-intelligence-26YT6KMN.js} +1 -1
  61. package/dist/{workspace-intelligence-benchmark-UCGDKMDF.js → workspace-intelligence-benchmark-QFVTUBDO.js} +1 -1
  62. package/dist/{workspace-intelligence-evaluation-QDSOOUHH.js → workspace-intelligence-evaluation-4AB4BBRP.js} +1 -1
  63. package/dist/{workspace-intelligence-runner-OELXKX3D.js → workspace-intelligence-runner-HVYKHCTX.js} +1 -1
  64. package/dist/{workspace-knowledge-graph-WNQMNAVL.js → workspace-knowledge-graph-RL3I2FHY.js} +1 -1
  65. package/dist/{workspace-knowledge-graph-query-3GPXGWYN.js → workspace-knowledge-graph-query-TT2KK3SF.js} +1 -1
  66. package/dist/workspace-knowledge-graph-snapshot-JEJMRQZL.js +1 -0
  67. package/dist/workspace-marker-7U3NYRPJ.js +1 -0
  68. package/dist/{workspace-mcp-serve-X7ZYJA3X.js → workspace-mcp-serve-2FGRXJG4.js} +1 -1
  69. package/dist/{workspace-model-5FA2636K.js → workspace-model-2ODVOWDQ.js} +1 -1
  70. package/dist/{workspace-onboarding-CZSQDNKO.js → workspace-onboarding-BY6RUBBH.js} +1 -1
  71. package/dist/{workspace-python-engine-state-BE4A3BL5.js → workspace-python-engine-state-VCOLSEWV.js} +2 -2
  72. package/dist/{workspace-registry-summary-WKENOFEA.js → workspace-registry-summary-VKTJ7PHV.js} +1 -1
  73. package/dist/workspace-repair-engine-RBM7NCGI.js +3 -0
  74. package/dist/workspace-run-JCA5WPCR.js +1 -0
  75. package/dist/{workspace-verify-37QL2JYE.js → workspace-verify-NFJ7RKKT.js} +1 -1
  76. package/dist/{workspace-watch-P5X6TAFK.js → workspace-watch-3DBBB6IP.js} +1 -1
  77. package/docs/SECURITY.md +16 -59
  78. package/docs/ci-workflows.md +43 -11
  79. package/package.json +2 -2
  80. package/dist/analyze-5ENZTHOT.js +0 -1
  81. package/dist/autopilot-release-QMZSHOLF.js +0 -1
  82. package/dist/chunk-2LIVMG5C.js +0 -2
  83. package/dist/chunk-4AW5QP5J.js +0 -5
  84. package/dist/chunk-5NL53T5C.js +0 -1
  85. package/dist/chunk-6WOFOOM7.js +0 -7
  86. package/dist/chunk-BVWDG66W.js +0 -1
  87. package/dist/chunk-CQBM6BBP.js +0 -2
  88. package/dist/chunk-CY4QZ3PE.js +0 -3
  89. package/dist/chunk-I7P6XQJI.js +0 -1
  90. package/dist/chunk-L4WG3NI7.js +0 -4
  91. package/dist/chunk-L5ZD2GD3.js +0 -2
  92. package/dist/chunk-LLEKVSMX.js +0 -9
  93. package/dist/chunk-LLSY6L7E.js +0 -157
  94. package/dist/chunk-NSH7TTSV.js +0 -1
  95. package/dist/chunk-QVUVJU56.js +0 -2
  96. package/dist/chunk-QYXX6G5O.js +0 -12
  97. package/dist/chunk-SATPH22S.js +0 -3
  98. package/dist/chunk-T6KHOIEY.js +0 -13
  99. package/dist/chunk-UNXG3ZFV.js +0 -1
  100. package/dist/chunk-WPZUKU2B.js +0 -2
  101. package/dist/chunk-X5ZNFXFI.js +0 -1
  102. package/dist/doctor-Z3Z5L67W.js +0 -1
  103. package/dist/pipeline-LPZHMO7S.js +0 -5
  104. package/dist/verified-goal-JIRVX7KO.js +0 -1
  105. package/dist/workspace-graph-token-efficiency-BTIS6JXL.js +0 -1
  106. package/dist/workspace-knowledge-graph-snapshot-MTFTCVFF.js +0 -1
  107. package/dist/workspace-marker-XGAWZZDX.js +0 -1
  108. package/dist/workspace-repair-engine-RXHJX4CQ.js +0 -3
  109. package/dist/workspace-run-IDRHBKEB.js +0 -1
@@ -0,0 +1,4 @@
1
+ import {a}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-SVGUAVMG.js';import {l,q}from'./chunk-TBOIXIQA.js';import {f as f$1,g,h as h$2}from'./chunk-DTLLIA2C.js';import {a as a$2}from'./chunk-UHT2SW7O.js';import {i,h as h$1,d,b,c as c$2,a as a$3,k as k$2}from'./chunk-FE5R6EUV.js';import {b as b$2}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$1}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 w=t.payload.references?.[0];f(w,"created must bind an intent artifact");let u=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:w,requiredCriteria:Qe(u),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,y=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(w=>w.status!=="succeeded"),"all effects must be certainly successful"),r="committed",y=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,y=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,...y?{terminalReason:y}:{}}}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(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$2(i.transaction,t),b$2(i.checkpoint,n),await k$2(e,i.events,`${a.map(s=>JSON.stringify(s)).join(`
2
+ `)}
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(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,y=[{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.`}],w=await I(e.workspacePath,t.surprises),u=[...e.record.transaction.effects.length===0&&o&&se(o)?["No typed effect receipt explains the observed architecture generation."]:[],...w?.summary.unpredicted?[`${w.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",h={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:y,remainingUncertainty:[...new Set(u)]};return {...h,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(h)}}}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 A(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$1({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 y=e.actorKind??"cli",w=e.actorId??"workspai-change",u=$({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(_)})),h$1=await k(t,null,s,v("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[u,...g]},y,w,d));h$1=await k(t,h$1,s,v("scope-bound",{summary:"Bind immutable Goal scope.",scope:l$1.scope},y,w)),h$1=await k(t,h$1,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)})]},y,w)),await q({workspacePath:t,goalId:r.id,changeId:s});let p=await D(t,l$1,h$1);return A({operation:"begin",lease:l$1,record:h$1,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 A({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 A({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 A({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 A({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(h=>h.criterionId==="workspace-verify"&&h.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 h of e.receipt.artifacts)if(!await ce(t,h))throw new Error(`Verification artifact is missing or corrupt: ${h.artifact}`);let y=e.actorKind??"ci",w=e.actorId??"workspai-verifier",u=r;if(u.transaction.state==="blocked"){if(!u.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.");u=await k(t,u,e.changeId,v("resumed",{summary:"Resume to admit a missing verification receipt.",resumeTo:"verifying"},y,w));}else if(u.transaction.state!=="verifying")throw new Error(`Verification receipt requires verifying or criteria-blocked state; observed ${u.transaction.state}.`);u=await k(t,u,e.changeId,v("verification-recorded",{summary:e.receipt.summary,verification:e.receipt},y,w)),u.transaction.state==="verifying"&&u.transaction.requiredCriteria.every(p=>u.transaction.verifications.filter(W=>W.criterionId===p).at(-1)?.status==="passed")&&(u=await k(t,u,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},y,w)));let g=await D(t,a,u);return A({operation:"verification-record",lease:a,record:u,capsule:g,nextActions:u.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),y=l?J(d.prediction,l.schemaVersion,l,"noncanonical-prediction"):null,w=yt({changeId:e.changeId,generatedAt:s,prediction:l,predictionReference:y,actual:c$2,actualReference:o});await h$1(t,d.surprises,w);let u=J(d.surprises,w.schemaVersion,w,"architecture-surprises"),g$1=r,h=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."}},h,p));let b=await D(t,a$1,g$1);return A({operation:"verify",lease:a$1,record:g$1,capsule:b,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let _=g$1.transaction.effects.filter(b=>b.status==="succeeded").flatMap(b=>[...b.artifacts.map(K=>K.artifact),...(b.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(", ")}`}},h,p));let b=await D(t,a$1,g$1);return A({operation:"verify",lease:a$1,record:g$1,capsule:b,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."},h,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,u],observedAt:s};if(g$1=await k(t,g$1,e.changeId,v("verification-recorded",{summary:fe.summary,verification:fe},h,p)),g$1.transaction.state==="verifying"){let b=g$1.transaction.requiredCriteria.filter(K=>g$1.transaction.verifications.filter(Ye=>Ye.criterionId===K).at(-1)?.status!=="passed");b.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: ${b.join(", ")}`}},h,p)):g$1=await k(t,g$1,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},h,p));}let Fe=await D(t,a$1,g$1);return A({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 A({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(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 y=await de({workspacePath:t,lease:o,record:l}),w=await le({workspacePath:t,changeId:d}),u=l.transaction.blockers.map(h=>h.details??h.code),g=y.status==="blocked"?y.assurances.filter(h=>h.status==="failed").map(h=>`${h.id}: ${h.summary}`):[];n.push({changeId:d,goalId:o.goalId,state:l.transaction.state,status:y.status,createdAt:l.transaction.createdAt,updatedAt:l.transaction.updatedAt,scope:o.scope,assurance:{passed:y.assurances.filter(h=>h.status==="passed").length,total:y.assurances.length},blockers:[...new Set([...u,...g])],capsuleArtifact:P(d).capsule,valid:w.valid,errors:w.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 A({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
+ 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};
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-A5FBGRJA.js';import {g as g$1,p}from'./chunk-WPZUKU2B.js';import {g,h}from'./chunk-FE5R6EUV.js';import {t,s}from'./chunk-ODK4LCEL.js';import {s as s$1,q}from'./chunk-RGNCL5OB.js';import {t as t$1}from'./chunk-VQZ5PI5J.js';import a from'path';import {existsSync}from'fs';import m from'fs-extra';var f=t.workspaceRegistry,w=s.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=t$1(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of s$1())if(await m.pathExists(t))try{let o=((await m.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(q(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await g(t,g$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await p({workspacePath:t});n=A.projects||[];}catch{n=[];}let d={contract:{exists:i,projectCount:n.length,path:g$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p$1="none",u=[],y=0;return i?(p$1="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p$1="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p$1="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p$1,contractPath:g$1,projects:u,sources:d}}}async function U(r){let e=await g(r,f);if(!e)return null;try{let t=await m.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e){let t=await M(r,e);return await h(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
1
+ import {a as a$1}from'./chunk-A5FBGRJA.js';import {g as g$1,p}from'./chunk-G6ADWA2B.js';import {g,h}from'./chunk-FE5R6EUV.js';import {t,s}from'./chunk-ODK4LCEL.js';import {s as s$1,q}from'./chunk-RGNCL5OB.js';import {t as t$1}from'./chunk-VQZ5PI5J.js';import a from'path';import {existsSync}from'fs';import m from'fs-extra';var f=t.workspaceRegistry,w=s.workspaceRegistry.schemaVersion;function E(r){return {slug:r.slug,relativePath:r.relativePath,framework:r.framework,kit:r.kit,source:r.source}}async function b(r){let e=t$1(r,"workspace.json").find(t=>existsSync(t));if(!e)return {exists:false,legacyProjectCount:0};try{let t=await m.readJson(e),c=Array.isArray(t.projects)?t.projects.length:0,o=typeof t.workspace_name=="string"&&t.workspace_name.trim()||typeof t.name=="string"&&t.name.trim()||a.basename(r);return {exists:true,manifestPath:e,workspaceName:o,profile:typeof t.profile=="string"?t.profile:void 0,legacyProjectCount:c}}catch{return {exists:true,manifestPath:e,legacyProjectCount:0,workspaceName:a.basename(r)}}}async function _(r){let e=a$1(r);for(let t of s$1())if(await m.pathExists(t))try{let o=((await m.readJson(t)).workspaces||[]).find(s=>a$1(s.path)===e);if(o)return {exists:true,projectCount:Array.isArray(o.projects)?o.projects.length:0,registryPath:t}}catch{continue}return {exists:false,projectCount:0,registryPath:a.join(q(),"workspaces.json")}}async function T(r,e){let t=a.resolve(r),c=await g(t,g$1),o=await b(t),s=await _(t),i=e?.contract!==void 0||!!c,n=[];if(e?.contract)n=e.contract.projects||[];else if(i)try{let{contract:A}=await p({workspacePath:t});n=A.projects||[];}catch{n=[];}let d={contract:{exists:i,projectCount:n.length,path:g$1},globalRegistry:{exists:s.exists,projectCount:s.projectCount,path:s.registryPath},legacyWorkspaceJson:{exists:o.exists,projectCount:o.legacyProjectCount,path:o.manifestPath?a.relative(t,o.manifestPath):void 0}},p$1="none",u=[],y=0;return i?(p$1="workspace.contract.json",u=n.map(E),y=u.length):s.projectCount>0?(p$1="global-registry",y=s.projectCount):o.legacyProjectCount>0&&(p$1="legacy-workspace.json",y=o.legacyProjectCount),{contractExists:i,summary:{schemaVersion:w,kind:"rapidkit.workspace.registry",workspacePath:t,workspaceName:o.workspaceName||a.basename(t),profile:o.profile,projectCount:y,authority:p$1,contractPath:g$1,projects:u,sources:d}}}async function U(r){let e=await g(r,f);if(!e)return null;try{let t=await m.readJson(e);return t?.schemaVersion!==w?null:t}catch{return null}}async function D(r,e){let t=await M(r,e);return await h(r,f,t),t}async function M(r,e){return {...(await T(r,{contract:e?.contract})).summary,generatedAt:(e?.now??new Date).toISOString(),registrySummaryPath:f}}function F(r,e=""){return r.projectCount>0?r.authority==="workspace.contract.json"?`${r.projectCount} project(s) registered in workspace contract${e}.`:r.authority==="global-registry"?`${r.projectCount} project(s) registered in global workspace registry${e}.`:`${r.projectCount} project(s) registered in legacy workspace manifest${e}.`:`Workspace state exists, but no projects are registered yet${e}.`}export{f as a,w as b,T as c,U as d,D as e,M as f,F as g};
@@ -0,0 +1,7 @@
1
+ import {d,b,e}from'./chunk-37SWTS2B.js';import {a}from'./chunk-NMXGSVMD.js';import {d as d$2}from'./chunk-S5KTATOU.js';import {B,q as q$1,A,u as u$1,z,D}from'./chunk-5EVBOUYW.js';import {k,m,g as g$1,f}from'./chunk-YYELANJO.js';import {g}from'./chunk-FE5R6EUV.js';import {p,t}from'./chunk-ODK4LCEL.js';import {a as a$1}from'./chunk-TQEMLBAG.js';import {c,d as d$1}from'./chunk-25AWHAB5.js';import {e as e$1,g as g$2}from'./chunk-RGNCL5OB.js';import {u,q,t as t$1}from'./chunk-VQZ5PI5J.js';import Q from'fs';import y from'path';import O from'chalk';import {execa}from'execa';var mt={"python-fastapi":{runtime:"python",framework:"FastAPI",markers:["pyproject.toml","fastapi"],commands:{init:"python -m pip install -e .",test:"pytest",build:"python -m build",start:"uvicorn main:app --reload"},errorPatterns:{setup:["ModuleNotFoundError","No module named","pip: command not found"],"test-failure":["FAILED","ERROR","test session started"],dependency:["ImportError","missing.*dependency"],runtime:["TypeError","AttributeError","ValueError"],timeout:["timeout","Timeout","timed out"],unknown:[]},healthCheck:{stage:"start",type:"http",value:"http://localhost:8000/docs"},validation:{command:"python -m pip list | grep fastapi",error:"FastAPI not installed"}},"python-django":{runtime:"python",framework:"Django",markers:["manage.py","django"],commands:{init:"python manage.py migrate",test:"python manage.py test",build:"python manage.py collectstatic --noinput",start:"python manage.py runserver 0.0.0.0:8000"},errorPatterns:{setup:["ModuleNotFoundError","ProgrammingError.*migrate"],"test-failure":["FAILED","ERROR","Ran.*test"],dependency:["ImportError","missing.*dependency"],runtime:["DatabaseError","ImproperlyConfigured"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"node-nestjs":{runtime:"node",framework:"NestJS",markers:["package.json","@nestjs/core"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm run start"},errorPatterns:{setup:["npm ERR!","ENOENT","not found"],"test-failure":["Tests.*failed","FAIL","fail.*test"],dependency:["Cannot find module","ERR_MODULE_NOT_FOUND"],runtime:["TypeError","Error: ","ReferenceError"],timeout:["timeout","TIMEOUT"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3}},"node-express":{runtime:"node",framework:"Express",markers:["package.json","express"],commands:{init:"npm install",test:"npm run test",build:"npm run build",start:"npm start"},errorPatterns:{setup:["npm ERR!","ENOENT"],"test-failure":["failed","FAIL"],dependency:["Cannot find module"],runtime:["Error","TypeError"],timeout:["timeout"],unknown:[]}},"go-fiber":{runtime:"go",framework:"Fiber",markers:["go.mod","fiber"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found","cannot find","go mod tidy"],"test-failure":["FAIL","--- FAIL"],dependency:["missing.*module"],runtime:["panic","fatal","Error"],timeout:["timeout","context deadline"],unknown:[]},dependencies:["init"]},"go-gin":{runtime:"go",framework:"Gin",markers:["go.mod","gin-gonic"],commands:{init:"go mod download && go mod tidy",test:"go test ./...",build:"go build -o app .",start:"./app"},errorPatterns:{setup:["go: .*not found"],"test-failure":["FAIL"],dependency:["missing.*module"],runtime:["panic"],timeout:["timeout"],unknown:[]}},"java-springboot":{runtime:"java",framework:"Spring Boot",markers:["pom.xml","build.gradle","spring-boot"],commands:{init:"mvn dependency:go-offline",test:"mvn test",build:"mvn package -DskipTests",start:"mvn spring-boot:run"},errorPatterns:{setup:["\\[ERROR\\]","BUILD FAILURE","missing dependencies"],"test-failure":["\\[ERROR\\] Tests run:","BUILD FAILURE"],dependency:["missing.*dependency"],runtime:["Exception","Error","NullPointerException"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8080}},"php-laravel":{runtime:"php",framework:"Laravel",markers:["composer.json","artisan","app/Models"],commands:{init:"composer install && php artisan migrate:fresh --seed",test:"php artisan test",build:"php artisan config:cache && php artisan route:cache && php artisan view:cache",start:"php artisan serve --host=0.0.0.0 --port=8000"},errorPatterns:{setup:["Composer.*lock","Fatal error","Class.*not found"],"test-failure":["FAILED","Tests.*failed"],dependency:["Class.*not found","require.*failed"],runtime:["Fatal error","Exception","Error"],timeout:["timeout","Timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:8e3},dependencies:["init"]},"php-symfony":{runtime:"php",framework:"Symfony",markers:["composer.json","symfony.lock","bin/console"],commands:{init:"composer install && php bin/console doctrine:database:create",test:"php bin/phpunit",build:"php bin/console cache:clear --env=prod",start:"symfony serve --no-tls"},errorPatterns:{setup:["Composer.*error","Fatal error"],"test-failure":["FAILED","failure"],dependency:["Class.*not found"],runtime:["Fatal error","Exception"],timeout:["timeout"],unknown:[]},dependencies:["init"]},"rust-actix":{runtime:"rust",framework:"Actix-web",markers:["Cargo.toml","actix"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find","failed.*download"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E","thread.*panicked"],timeout:["timeout"],unknown:[]},validation:{command:"cargo --version",error:"Rust/Cargo not installed"}},"rust-axum":{runtime:"rust",framework:"Axum",markers:["Cargo.toml","axum"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["test result:","FAILED"],dependency:["can.t find.*crate"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"rust-rocket":{runtime:"rust",framework:"Rocket",markers:["Cargo.toml","rocket"],commands:{init:"cargo fetch",test:"cargo test",build:"cargo build --release",start:"cargo run --release"},errorPatterns:{setup:["error: .*could not find"],"test-failure":["FAILED"],dependency:["can.t find"],runtime:["error\\[E"],timeout:["timeout"],unknown:[]}},"dotnet-aspnetcore":{runtime:"dotnet",framework:"ASP.NET Core",markers:[".csproj",".sln","Program.cs"],commands:{init:"dotnet restore",test:"dotnet test",build:"dotnet build -c Release",start:"dotnet run"},errorPatterns:{setup:["error CS","CSPROJ.*not found","NuGet.*restore"],"test-failure":["Failed:.*test","FAILED"],dependency:["error NU1101"],runtime:["error CS","Exception"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:5e3}},"elixir-phoenix":{runtime:"elixir",framework:"Phoenix",markers:["mix.exs","phoenix"],commands:{init:"mix setup",test:"mix test",build:"mix compile --all-warnings",start:"mix phx.server"},errorPatterns:{setup:["\\*\\* \\(.*Error\\)","Mix.InstallError"],"test-failure":["\\d+\\sfailed","FAILED"],dependency:["dependencies are not available"],runtime:["\\*\\* \\(","RuntimeError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:4e3},dependencies:["init"]},"ruby-rails":{runtime:"ruby",framework:"Rails",markers:["Gemfile","config/application.rb","bin/rails"],commands:{init:"bundle install && rails db:prepare",test:"rails test",build:"rails assets:precompile",start:"rails server --binding=0.0.0.0 --port=3000"},errorPatterns:{setup:["Bundler::.*Error","Gem::.*Error"],"test-failure":["failures,","error,","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","Exception","NoMethodError"],timeout:["timeout"],unknown:[]},healthCheck:{stage:"start",type:"port",value:3e3},dependencies:["init"]},"ruby-sinatra":{runtime:"ruby",framework:"Sinatra",markers:["Gemfile","app.rb","sinatra"],commands:{init:"bundle install",test:"rspec",build:`echo "Sinatra apps don't require build"`,start:"ruby app.rb"},errorPatterns:{setup:["Bundler.*Error","Gem.*Error"],"test-failure":["failure","FAILED"],dependency:["Could not find.*gem"],runtime:["Error","NoMethodError"],timeout:["timeout"],unknown:[]}}},ft={init:{python:["pip install -e .","poetry install","pip install -r requirements.txt"],node:["npm install","pnpm install","yarn install"],go:["go mod download && go mod tidy","go get ./..."],java:["mvn dependency:go-offline","gradle dependencies"],php:["composer install"],rust:["cargo fetch"],dotnet:["dotnet restore"],c:["cmake -S . -B build"],cpp:["cmake -S . -B build"],elixir:["mix deps.get"],ruby:["bundle install"],clojure:["clojure -P"],scala:["sbt update"],kotlin:["./gradlew dependencies","gradle dependencies"],deno:[],bun:["bun install"],"jvm-generic":["mvn dependency:go-offline","gradle dependencies"],unknown:[]},test:{python:["pytest","python -m unittest","python -m pytest"],node:["npm test","npm run test"],go:["go test ./...","make test"],java:["mvn test","gradle test"],php:["php artisan test","phpunit","pest"],rust:["cargo test"],dotnet:["dotnet test"],c:["ctest --test-dir build --output-on-failure"],cpp:["ctest --test-dir build --output-on-failure"],elixir:["mix test"],ruby:["rspec","ruby -m minitest"],clojure:["clojure -X:test"],scala:["sbt test"],kotlin:["./gradlew test","gradle test"],deno:["deno task test","deno test"],bun:["bun test","bun run test"],"jvm-generic":["mvn test","gradle test"],unknown:[]},build:{python:["python -m build","python setup.py build"],node:["npm run build"],go:["go build -o app .","go build ./..."],java:["mvn package -DskipTests","gradle build -x test"],php:['echo "PHP build: typically no build step"'],rust:["cargo build --release"],dotnet:["dotnet build -c Release"],c:["cmake --build build"],cpp:["cmake --build build"],elixir:["mix compile"],ruby:["gem build *.gemspec"],clojure:[],scala:["sbt compile"],kotlin:["./gradlew build","gradle build"],deno:["deno task build"],bun:["bun run build"],"jvm-generic":["mvn package -DskipTests","gradle build"],unknown:[]},start:{python:["python app.py","python main.py","uvicorn main:app --reload"],node:["npm start","node index.js","node src/index.js"],go:["./app","go run main.go","go run ./..."],java:["mvn spring-boot:run","gradle bootRun","java -jar target/*.jar"],php:["php -S 0.0.0.0:8000","php artisan serve"],rust:["cargo run --release","./target/release/app"],dotnet:["dotnet run"],c:[],cpp:[],elixir:["mix phx.server","iex -S mix"],ruby:["rails server","ruby app.rb","bundle exec puma"],clojure:["clojure -M:run"],scala:["sbt run"],kotlin:["./gradlew run","gradle run"],deno:["deno task start","deno task dev"],bun:["bun run start","bun run dev"],"jvm-generic":["java -jar *.jar","gradle run"],unknown:[]}};function de(e,r){if(r){let t=r.trim().toLowerCase().replace(/[_.\s]+/g,"-"),n=f(r),s=`${e}-${n==="gofiber"?"fiber":n==="gogin"?"gin":n==="dotnet"?"aspnetcore":n!=="unknown"?n:t==="fiber"?"fiber":t==="aspnetcore"||t==="asp-net-core"?"aspnetcore":t}`;return mt[s]}}function He(e,r,t){if(r){let n=de(e,r);if(n&&n.commands[t])return n.commands[t]}if(["init","test","build","start"].includes(t)){let n=ft[t]?.[e]??[];return n.length>0?n[0]:void 0}}var gt={test:"test",build:"build",start:"start"};function le(e){if(e.stage==="init")return e.runtime==="node"?A(e.projectPath):He(e.runtime,e.framework,e.stage);if(e.runtime==="node"){let r=gt[e.stage];if(r){let t=u$1(e.projectPath,r,{framework:e.framework});if(t)return z(e.projectPath,t.scriptName)}}return He(e.runtime,e.framework,e.stage)}function yt(e){let r=k(e).map(t=>t==="python"?"python":t==="node"||t==="bun"?"node":t==="go"?"go":t==="java"?"java":t==="php"?"php":t==="rust"?"rust":t==="dotnet"?"dotnet":t==="elixir"?"elixir":t==="ruby"?"ruby":t==="clojure"||t==="scala"||t==="kotlin"?"jvm-generic":null).filter(t=>t!==null).filter((t,n,o)=>o.indexOf(t)===n);return {primary:r.length>0?r[0]:"unknown",secondary:r.slice(1)}}function Xe(e){return yt(e).primary}function Ye(e,r){if(!e)return "unknown";r||(r={timeout:["timed out","timeout","deadline exceeded","SocketTimeoutException"],dependency:["cannot find module","import.*error","Could not find a package configuration file provided by","CMAKE_PREFIX_PATH"],setup:["ModuleNotFoundError","No module named","npm ERR!","error:","not found"],"test-failure":["FAILED","FAIL","failed"],runtime:["Exception","Error:","panic","TypeError"],unknown:[]});for(let[t,n]of Object.entries(r))for(let o of n)if(new RegExp(o,"i").test(e))return t;return "unknown"}async function re(e,r){let t=e.split(/[&|;]\s*/)[0].trim().split(/\s+/)[0];if(["echo","cd","pwd","test","true","false","exit"].includes(t))return {valid:true};if(t.includes("/")||t.includes("\\")){let o=y.isAbsolute(t)?t:y.resolve(r??process.cwd(),t);try{return await Q.promises.access(o,process.platform==="win32"?Q.constants.F_OK:Q.constants.X_OK),{valid:true}}catch{return {valid:false,reason:`Command '${t}' not found or not executable in '${r??process.cwd()}'`}}}try{let o=process.platform==="win32"?"where":"which";if((await execa(o,[t],{reject:false})).exitCode===0)return {valid:true}}catch{}return {valid:false,reason:`Command '${t}' not found or not executable`}}function Ze(e,r,t){if(!r)return e;let n=typeof r=="object"&&!Array.isArray(r)&&("dev"in r||"staging"in r||"prod"in r||"default"in r)&&!Object.keys(r).some(o=>["init","test","build","start"].includes(o))?r:{};return t&&typeof n[t]=="string"?n[t]:typeof n.default=="string"?n.default:e}async function Qe(e,r){if(!e)return {healthy:true};switch(e.type){case "port":{let t=e.value;try{let n=await import('net');return new Promise(o=>{let s=new n.Socket,i=5e3;s.setTimeout(i),s.on("connect",()=>{s.destroy(),o({healthy:true,reason:`Port ${t} is listening`});}),s.on("timeout",()=>{s.destroy(),o({healthy:false,reason:`Port ${t} timeout after ${i}ms`});}),s.on("error",p=>{s.destroy(),o({healthy:false,reason:`Port ${t} error: ${String(p)}`});}),s.connect(t,"localhost");})}catch(n){return {healthy:false,reason:`Port check error: ${n instanceof Error?n.message:String(n)}`}}}case "http":{let t=e.value,n;try{let o=new AbortController;n=setTimeout(()=>o.abort(),5e3);let s=await fetch(t,{method:"GET",signal:o.signal});return {healthy:s.status===200,reason:`HTTP ${s.status}`,metadata:{status:s.status}}}catch(o){return {healthy:false,reason:`HTTP check error: ${o instanceof Error?o.message:String(o)}`}}finally{n&&clearTimeout(n);}}case "log":{let t=e.value;if(!r)return {healthy:true};try{let n=[y.join(r,".workspai","last-run.log"),y.join(r,".rapidkit","last-run.log")].find(o=>Q.existsSync(o));if(n){let o=Q.readFileSync(n,"utf-8"),s=new RegExp(t,"i");return {healthy:s.test(o),reason:s.test(o)?"Log pattern found":"Log pattern not found"}}return {healthy:true,reason:"No log file to check"}}catch(n){return {healthy:false,reason:`Log check error: ${n instanceof Error?n.message:String(n)}`}}}case "command":{let t=e.value;try{let n=await execa(t,[],{cwd:r,reject:false,shell:true});return {healthy:n.exitCode===0,reason:n.exitCode===0?"Health check passed":"Health check failed",metadata:{exitCode:n.exitCode}}}catch(n){return {healthy:false,reason:`Command check error: ${n instanceof Error?n.message:String(n)}`}}}default:return {healthy:true}}}var et={init:"init",test:"test",build:"build",start:"start"};function ht(e){return e in et?et[e]:null}function kt(e,r){let n=q$1(e)?.contextJson?.commands;if(!n||typeof n!="object"||Array.isArray(n))return;let o=n[r];if(typeof o=="string"&&o.trim().length>0)return o.trim();if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o,i=s.default??s.dev;if(typeof i=="string"&&i.trim().length>0)return i.trim()}}function tt(e,r,t=D(e)){let n=ht(r);if(!n)return kt(e,r)?{supported:true}:{supported:false,reason:`Workspace stage "${r}" is not part of the Workspai fleet contract.`};if(!t.projectRoot)return {supported:false,reason:"No Workspai project metadata was detected for this target."};let o=t.commandMap[n];if(!o||o.status!=="supported"){let s=t.runtimeSupportTier==="observed"||t.frameworkSupportTier==="observed";return {supported:false,reason:o?.reason??`Command "${n}" is not supported for this project runtime/framework.`,shouldFail:!s}}return {supported:true}}var bt=new Set(["init","test","build","start"]),wt=new Set([".git","node_modules",".workspai",".rapidkit",".venv","dist","build","coverage","htmlcov"]);async function Y(e){try{return await Q.promises.access(e,Q.constants.F_OK),true}catch{return false}}function rt(e,r){let t=y.relative(y.resolve(e),y.resolve(r));return t===""||!t.startsWith(`..${y.sep}`)&&t!==".."&&!y.isAbsolute(t)}function vt(e){let r=y.resolve(e.projectPath,e.unit.root);return !e.selectedProjectPaths.some(t=>y.resolve(t)===y.resolve(e.projectPath)?false:rt(e.projectPath,t)&&rt(t,r))}async function xt(e){for(let r of e)if(await Y(r))return true;return false}async function Rt(e,r,t){if(r==="python"){let i=[y.join(e,".workspai","cli.py"),y.join(e,".rapidkit","cli.py")];for(let p of i)if(await Y(p))return {valid:true};return {valid:false,reason:"Project-local .workspai/cli.py is missing. Run `workspai init` in this project first."}}let o={go:"go",rust:"cargo",dotnet:"dotnet",php:"php"}[r];if(o)return re(o,e);let s=t.trim().split(/\s+/)[0];if(s&&["npm","npx","pnpm","yarn"].includes(s)){let i=e$1(s);if((await execa(i.command,[...i.prefixArgs,"--version"],{reject:false,env:g$2()})).exitCode===0)return {valid:true}}return re(t,e)}async function pe(e){let r=await Q.promises.readFile(e,"utf-8");return JSON.parse(r)}function W(e){return e.replace(/\\/g,"/")}function St(e){let r=e?.trim();return r?r.startsWith("project:")?r.slice(8).trim()||null:r:null}async function Ct(e){let r=y.join(e,p.model);if(await Y(r))try{let n=((await pe(r)).projects??[]).map(o=>typeof o.path=="string"?y.resolve(e,o.path):null).filter(o=>!!o).filter((o,s,i)=>i.indexOf(o)===s).filter(o=>Q.existsSync(o));if(n.length>0)return n.sort()}catch{}return a(e,{skipDirs:wt,includeHiddenDirs:false,descendIntoMatchedProjects:false,isProjectDir:async(t,n)=>await xt([...u(t,"context.json"),...u(t,"project.json")])?true:y.resolve(t)===y.resolve(n)?false:k(t).length>0})}async function it(e){for(let r of [y.join(".workspai","project.json"),y.join(".workspai","context.json"),y.join(".rapidkit","project.json"),y.join(".rapidkit","context.json")]){let t=y.join(e,r);if(await Y(t))try{let n=await pe(t),o=n.name??n.projectName??n.slug;if(typeof o=="string"&&o.trim())return o.trim()}catch{}}return null}async function Et(e,r,t){let n=St(t);if(!n)return {projects:r,normalizedScope:null};let o=W(n).toLowerCase(),s=[];for(let i of r){let p=W(y.relative(e,i)),c=y.basename(i),m=await it(i);[p,c,m].filter(d=>typeof d=="string"&&d.length>0).map(d=>W(d).toLowerCase()).includes(o)&&s.push(i);}if(s.length===0)throw new Error(`Workspace run scope did not match any project: ${t}`);return {projects:s,normalizedScope:n}}async function jt(e,r,t){let n=await execa("git",["diff","--name-only",`${t}...HEAD`],{cwd:e,reject:false,env:a$1()});if(n.exitCode!==0)return new Set(r);let o=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).map(i=>W(i));if(o.length===0)return new Set;let s=new Set;for(let i of r){let p=W(y.relative(e,i));if(!p||p===".")continue;let c=`${p}/`;o.some(m=>m===p||m.startsWith(c))&&s.add(i);}return s}async function Pt(e,r,t$1){let n=await g(e,t.workspaceContract)??q(e,"workspace.contract.json");if(await Y(n))try{let u=await At(e,r,t$1,n);if(u.graphStatus!=="missing")return u}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let o=await g(e,".workspai/workspace-dependency-graph.json")??q(e,"workspace-dependency-graph.json");if(!await Y(o))return {expanded:t$1,graphStatus:"missing",expansionDepth:0};let s;try{s=await pe(o);}catch{return {expanded:t$1,graphStatus:"invalid",expansionDepth:0}}let i=new Set(r.map(u=>y.resolve(u))),p=new Map;if(!s||typeof s!="object"||Array.isArray(s))return {expanded:t$1,graphStatus:"invalid",expansionDepth:0};let c=Array.isArray(s.projects)?s.projects:[];for(let u of c){if(!u||typeof u!="object"||Array.isArray(u))continue;let d=u,l=typeof d.path=="string"?d.path:"",w=y.resolve(e,l);if(!i.has(w))continue;let v=Array.isArray(d.dependsOn)?d.dependsOn.filter(C=>typeof C=="string"):[];for(let C of v){let x=y.resolve(e,C);i.has(x)&&(p.has(x)||p.set(x,new Set),p.get(x)?.add(w));}}let m=d$2(p,t$1);return {expanded:m.reached,graphStatus:"loaded",expansionDepth:m.added}}async function At(e,r,t,n){let o=await pe(n);if(!o||typeof o!="object"||Array.isArray(o))return {expanded:t,graphStatus:"invalid",expansionDepth:0};let s=o,i=Array.isArray(s.projects)?s.projects:null;if(!i)return {expanded:t,graphStatus:"invalid",expansionDepth:0};let p=new Map,c=new Map;for(let w of r){let v=W(y.relative(e,w));c.set(v,y.resolve(w));}let m=new Map,u=new Map,d=new Map;for(let w of i){if(!w||typeof w!="object"||Array.isArray(w))continue;let v=w,C=typeof v.slug=="string"?v.slug:"",x=typeof v.relativePath=="string"?W(v.relativePath):C,h=c.get(x);!C||!h||p.set(C,h);}for(let w of i){if(!w||typeof w!="object"||Array.isArray(w))continue;let v=w,C=typeof v.slug=="string"?v.slug:"",x=p.get(C);if(!x)continue;let h=v.contracts&&typeof v.contracts=="object"&&!Array.isArray(v.contracts)?v.contracts:{},R=Array.isArray(h.dependsOn)?h.dependsOn.filter(S=>typeof S=="string"):[],N=Array.isArray(h.publishes)?h.publishes.filter(S=>typeof S=="string"):[],_=Array.isArray(h.consumes)?h.consumes.filter(S=>typeof S=="string"):[];for(let S of R){let P=p.get(S);P&&(d.has(P)||d.set(P,new Set),d.get(P)?.add(x));}for(let S of N)m.has(S)||m.set(S,new Set),m.get(S)?.add(x);for(let S of _)u.has(S)||u.set(S,new Set),u.get(S)?.add(x);}for(let[w,v]of m.entries()){let C=u.get(w);if(C)for(let x of v){d.has(x)||d.set(x,new Set);for(let h of C)h!==x&&d.get(x)?.add(h);}}let l=d$2(d,t);return {expanded:l.reached,graphStatus:"loaded",expansionDepth:l.added}}async function Ft(e,r){if(typeof r=="boolean")return r;let t=t$1(e,"policies.yml").find(s=>Q.existsSync(s))??q(e,"policies.yml");if(!await Y(t))return true;let n="";try{n=await Q.promises.readFile(t,"utf-8");}catch{return true}let o=n.match(/^[\t ]*rules\.enforce_workspace_run_gates:\s*(true|false)\s*(?:#.*)?$/m);return o?o[1]==="true":true}function Tt(e,r){let t=process.env.RAPIDKIT_WORKSPACE_RUN_STAGE_TIMEOUT_MS;if(t){let n=Number.parseInt(t,10);if(Number.isFinite(n)&&n>0)return n}return e!=="init"?9e4:r==="python"||r==="java"||r==="jvm-generic"||r==="dotnet"||r==="rust"?6e5:3e5}function Ot(e){let r=e.trim();if(!r||/[&|;<>()$`"'\n\r]/.test(r))return null;let[t,...n]=r.split(/\s+/);return !t||/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)||![t,...n].every(o=>/^[A-Za-z0-9_./:@%+,=\\-]+$/.test(o))?null:{file:t,args:n}}function nt(e,r){let t=Number.parseInt(process.env[e]??"",10);return Number.isFinite(t)&&t>0?t:r}function ve(e){return new Promise(r=>setTimeout(r,e))}async function Dt(e){let r=process.argv[1];if(e.useRapidkitWrapper&&!r)return {exitCode:1,stdout:"",stderr:"Workspai entrypoint is unavailable for startup verification.",healthStatus:{healthy:false,reason:"Workspai entrypoint is unavailable."}};let t=e.useRapidkitWrapper&&r?execa(process.execPath,[r,"start"],{cwd:e.projectPath,reject:false,timeout:e.timeoutMs,env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}}):execa(e.finalCommand,[],{cwd:e.projectPath,reject:false,shell:true,timeout:e.timeoutMs}),n=Promise.resolve(t).then(u=>({kind:"exit",result:u}),u=>({kind:"error",error:u})),o=nt("WORKSPAI_WORKSPACE_RUN_STARTUP_GRACE_MS",2e3),s=await Promise.race([n,ve(o).then(()=>({kind:"alive"}))]);if(s.kind==="error"){let u=typeof s.error=="object"&&s.error!==null&&"timedOut"in s.error&&!!s.error.timedOut;return {exitCode:u?124:1,stdout:"",stderr:s.error instanceof Error?s.error.message:String(s.error),timedOut:u,healthStatus:{healthy:false,reason:"The start command failed before readiness."}}}if(s.kind==="exit"){let u=Number(s.result.exitCode??0);return {exitCode:u,stdout:String(s.result.stdout??""),stderr:String(s.result.stderr??""),healthStatus:{healthy:u===0,reason:u===0?"The start command completed successfully.":`The start command exited with code ${u} before readiness.`}}}let i=de(e.runtime,e.framework)?.healthCheck,p=i?{healthy:false,reason:"The configured health check has not passed yet."}:{healthy:true,reason:`The service remained alive for ${o}ms (bounded startup smoke).`};if(i){let u=nt("WORKSPAI_WORKSPACE_RUN_STARTUP_HEALTH_TIMEOUT_MS",15e3),d=Date.now()+u;for(;Date.now()<d;){let l=await Qe(i,e.projectPath);if(p={healthy:l.healthy,reason:l.reason},l.healthy)break;if((await Promise.race([n,ve(350).then(()=>({kind:"alive"}))])).kind!=="alive"){p={healthy:false,reason:"The service exited before its configured health check passed."};break}}}try{t.kill?.("SIGTERM",{forceKillAfterDelay:1e3});}catch{try{t.kill?.();}catch{}}let c=await Promise.race([n,ve(2e3).then(()=>({kind:"alive"}))]),m=c.kind==="exit"?c.result:void 0;return {exitCode:p.healthy?0:1,stdout:String(m?.stdout??""),stderr:String(m?.stderr??""),healthStatus:p}}async function Re(e,r,t,n=false){let o=process.argv[1];if(!o)return {exitCode:1,stdout:"",stderr:"RapidKit entrypoint is unavailable for nested workspace-run execution."};let s=false,i,p;try{let c=execa(process.execPath,[o,...e],{cwd:r,reject:false,detached:process.platform!=="win32",env:{...process.env,RAPIDKIT_WORKSPACE_RUN_CHILD:"1"}});t&&t>0&&(p=setTimeout(()=>{s=true;let u=c.pid;if(!u){c.kill("SIGTERM");return}if(process.platform==="win32"){execa("taskkill",["/pid",String(u),"/T","/F"],{reject:false});return}try{process.kill(-u,"SIGTERM");}catch{c.kill("SIGTERM");}i=setTimeout(()=>{try{process.kill(-u,"SIGKILL");}catch{}},1e3),i.unref();},t),p.unref()),n&&(c.stdout?.on("data",u=>process.stdout.write(u)),c.stderr?.on("data",u=>process.stderr.write(u)));let m=await c;return {exitCode:s?124:Number(m.exitCode??1),stdout:m.stdout,stderr:s?`${m.stderr??""}${m.stderr?`
2
+ `:""}Stage timed out after ${t}ms`:m.stderr}}catch(c){let m=s||typeof c=="object"&&c!==null&&"timedOut"in c&&!!c.timedOut;return {exitCode:m?124:1,stdout:typeof c=="object"&&c!==null&&"stdout"in c?String(c.stdout??""):"",stderr:m?`Stage timed out after ${t}ms`:typeof c=="object"&&c!==null&&"stderr"in c?String(c.stderr??""):c instanceof Error?c.message:String(c)}}finally{p&&clearTimeout(p),i&&clearTimeout(i);}}function ut(e){return e==="node"||e==="go"||e==="java"||e==="python"||e==="dotnet"||e==="rust"||e==="php"}function It(){return process.env.VITEST==="true"||process.env.VITEST==="1"||process.env.NODE_ENV==="test"}function $t(e,r=8){if(e.length<=r)return e.join(`
3
+ `);let t=3;return [...e.slice(0,t),...e.slice(-(r-t))].join(`
4
+ `)}function Mt(e){let r=/(?:\bnot found\b|\bno such\b|\bmissing\b|\bfailed\b|\berror\b|\bexception\b|\bcannot\b|\bdenied\b|\btimeout\b|\btimed out\b|\benoent\b|\beacces\b|\beperm\b)/i;return [...e].reverse().find(t=>r.test(t))??e.at(-1)}async function Wt(e){let r=process.cwd();try{process.chdir(e);let{handleInitCommand:t}=await import('./index.js');return {exitCode:await t(["init"]),stdout:"",stderr:""}}finally{process.chdir(r);}}async function xe(e){let r=d=>{let l=g$1(d);return l==="node"||l==="bun"?"node":l==="python"?"python":l==="go"?"go":l==="java"?"java":l==="php"?"php":l==="ruby"?"ruby":l==="rust"?"rust":l==="dotnet"?"dotnet":l==="elixir"?"elixir":l==="clojure"||l==="scala"||l==="kotlin"?"jvm-generic":Xe(e)},t=d=>{if(!d)return;let l=f(d);if(new Set(["fastapi","django","flask","nestjs","express","fastify","koa","gofiber","gogin","echo","springboot","laravel","symfony","rails","sinatra","dotnet","actix","axum","rocket","phoenix"]).has(l))return l},n=q$1(e),o=n?.detection??m(e,n?.projectJson??null),s=n?.contextJson,i=r(o.runtime),p=t(o.key),c={},m$1=new Set(["init","test","build","start"]);if(s?.commands&&typeof s.commands=="object")for(let[d,l]of Object.entries(s.commands))typeof l=="string"&&m$1.has(d)&&(c[d]=l);let u;if(s?.commandEnvironments&&typeof s.commandEnvironments=="object"){let d=s.commandEnvironments;u={dev:typeof d.dev=="string"?d.dev:void 0,staging:typeof d.staging=="string"?d.staging:void 0,prod:typeof d.prod=="string"?d.prod:void 0,default:typeof d.default=="string"?d.default:void 0};}return {runtime:i,framework:p,commandOverrides:Object.keys(c).length>0?c:void 0,environmentCommandVariants:u,environment:typeof s?.environment=="string"?s.environment:void 0}}async function ot(e,r,t,n,o,s,i,p=false){let c=!o?.[r]&&ut(t),m;if(o&&o[r]?m=o[r]:c?m=`rapidkit ${r}`:m=le({projectPath:e,runtime:t,framework:n,stage:r}),!m)return {exitCode:127,command:`<stage not supported for ${t}>`,message:`No stage command found for runtime '${t}' and framework '${n||"unknown"}'`,errorCategory:"runtime"};let u=Ze(m,s,i);if(!u)return {exitCode:127,command:m,message:"Failed to resolve stage command",errorCategory:"runtime"};let d=le({projectPath:e,runtime:t,framework:n,stage:r});if(c){if(d){let b=c?await Rt(e,t,d):await re(d,e);if(!b.valid)return {exitCode:127,command:u,message:b.reason||"Command not available",errorCategory:"setup"}}}else {let b=await re(u,e);if(!b.valid)return {exitCode:127,command:u,message:b.reason||"Command not available",errorCategory:"setup"}}let l=0,w="",v="",C,x=false,h,R=Tt(r,t),N=Date.now();try{let b=r==="start"?await Dt({projectPath:e,finalCommand:u,useRapidkitWrapper:c,runtime:t,framework:n,timeoutMs:R}):c?r==="init"&&It()?await Wt(e):await Re([r],e,R,p):await(async()=>{let I=Ot(u);return I?execa(I.file,I.args,{cwd:e,reject:false,timeout:R,forceKillAfterDelay:1e3}):execa(u,[],{cwd:e,reject:false,shell:true,timeout:R,forceKillAfterDelay:1e3})})();if(x=!!(typeof b=="object"&&b!==null&&"timedOut"in b&&b.timedOut),l=x?124:Number(b.exitCode??0),w=b.stdout,v=b.stderr,h=r==="start"?b.healthStatus:void 0,l!==0){let I=`${w}
5
+ ${v}`,me=Date.now()-N,ee=Ye(I);C=x||l===124||l===143&&me>=Math.floor(R*.8)||ee==="timeout"?"timeout":ee;}}catch(b){let I=typeof b=="object"&&b!==null&&"timedOut"in b&&!!b.timedOut;return {exitCode:I?124:1,command:u,message:I?`Stage timed out after ${R}ms`:b instanceof Error?b.message:"Command execution failed",errorCategory:I?"timeout":"runtime"}}let _=`${w}
6
+ ${v}`.split(/\r?\n/).map(b=>b.trim()).filter(Boolean),S=$t(_),P=Mt(_),D=Date.now()-N;if(r==="test"&&t==="go"&&l!==0&&/(?:matched no packages|no packages to test)/i.test(_.join(`
7
+ `)))return {exitCode:0,command:u,skipped:true,message:"No Go packages matched; test stage is not applicable to this runtime unit."};let U=x||l===124||l===143&&D>=Math.floor(R*.8),V=l===0?void 0:U?"timeout":C,J=l===0||!V?void 0:{category:V,exitCode:l,command:u,timedOut:U,timeoutMs:R,...S?{outputExcerpt:S}:{}};return {exitCode:l,command:u,errorCategory:V,healthStatus:h,failureDiagnostic:J,message:U?`Stage timed out after ${R}ms`:l!==0?P?`Stage failed with exit code ${l}: ${P}`:`Stage failed with exit code ${l}`:void 0}}function st(e){try{return JSON.parse(e)}catch{return null}}function Nt(e){switch(e){case "dotnet":return "Install .NET 8+ SDK, then rerun `npx workspai setup dotnet` or `npx workspai init`.";case "go":return "Install Go 1.21+, then rerun `npx workspai setup go` or `npx workspai init`.";case "java":case "jvm-generic":return "Install Java 21+ and Maven/Gradle, then rerun `npx workspai setup java` or `npx workspai init`.";case "node":return "Install Node.js LTS and npm/pnpm/yarn, then rerun `npx workspai setup node` or `npx workspai init`.";case "python":return "Install Python 3.10+ and pip/Poetry, then rerun `npx workspai setup python` or `npx workspai init`.";default:return null}}async function _t(e){let r=[],t=await Re(["doctor","workspace","--json"],e);if(t.exitCode!==0)r.push({gate:"doctor-workspace",status:"fail",summary:"doctor workspace command failed"});else {let s=st(t.stdout)?.healthScore,i=Number(s?.errors??0);Number.isFinite(i)&&i>0?r.push({gate:"doctor-workspace",status:"fail",summary:`doctor workspace reports ${i} error(s)`}):r.push({gate:"doctor-workspace",status:"pass",summary:"doctor workspace passed"});}let n=await Re(["readiness","--json"],e);if(n.exitCode!==0)r.push({gate:"readiness",status:"fail",summary:"readiness command failed"});else {let o=st(n.stdout),s=String(o?.overallStatus??"").toLowerCase();s==="fail"?r.push({gate:"readiness",status:"fail",summary:"readiness overall status is fail"}):s==="warn"?r.push({gate:"readiness",status:"warn",summary:"readiness overall status is warn"}):r.push({gate:"readiness",status:"pass",summary:"readiness overall status is pass"});}return r}var Lt=new Set(["dev","stop"]);function Gt(e){let r=e.trim();return !r||Lt.has(r.toLowerCase())?false:bt.has(r)?true:/^[a-z][a-z0-9_-]*$/i.test(r)}function at(e,r,t){let n=W(y.relative(t,r));return (Array.isArray(e.projects)?e.projects:[]).some(s=>{if(!s||typeof s!="object")return false;let i=s,p=[i.relativePath,i.path].filter(c=>typeof c=="string"&&c.length>0).map(c=>W(c));return i.status==="passed"&&(p.includes(n)||p.some(c=>c.endsWith(`/${n}`)))})}function Bt(e,r){return de(e,r)?.dependencies??[]}function Kt(e,r){let t=Math.max(1,Math.min(4,r)),n=Number(e??t);return Number.isFinite(n)?Math.max(1,Math.min(16,Math.trunc(n))):t}async function Rr(e$1){if(!Gt(e$1.stage))throw new Error(`Unsupported workspace run stage: ${e$1.stage}`);let r=Date.now(),t=y.resolve(e$1.workspacePath);c({blockId:"workspace.run.resolve",status:"running",message:"Resolving workspace project fleet",component:"workspace-run"});let n=await d(t),o=await Ct(t),{projects:s,normalizedScope:i}=await Et(t,o,e$1.scope),p=e$1.affected===true,c$1=e$1.blastRadius===true,m=e$1.since?.trim()||"HEAD~1",u=p?await jt(t,s,m):new Set(s),d$2,l="not-applicable",w=0,v="all";if(p&&c$1){let g=await Pt(t,o,u);d$2=g.expanded,l=g.graphStatus,w=g.expansionDepth,v="affected+blast-radius";}else p?(d$2=u,v="affected"):(d$2=u,v="all");c({blockId:"workspace.run.resolve",status:"succeeded",message:`Resolved ${s.length} project(s)`,component:"workspace-run",attributes:{projects:s.length,selectionMode:v}}),c({blockId:"workspace.run.gates",status:"running",message:"Evaluating workspace run gates",component:"workspace-run"});let C=e$1.stage==="init"||e$1.planOnly===true?false:await Ft(t,e$1.enforceGates),x=C?await _t(t):[{gate:"doctor-workspace",status:"skipped",summary:"workspace run gates disabled"},{gate:"readiness",status:"skipped",summary:"workspace run gates disabled"}],h=x.find(g=>g.status==="fail");c({blockId:"workspace.run.gates",status:h?"blocked":"succeeded",message:h?`Blocked by ${h.gate}`:"Workspace run gates passed",component:"workspace-run",attributes:{gates:x}});let R=s.filter(g=>d$2.has(g)),N=e$1.continueOnError===true||e$1.stage==="init",_=e$1.parallel===true,S=Kt(e$1.maxWorkers,R.length),P=R.length,D=0;c({blockId:"workspace.run.execute",status:h?"blocked":"running",message:h?`Execution blocked by ${h.gate}`:`Executing ${e$1.stage} across ${P} project(s)`,component:"workspace-run",progress:{completed:0,total:P},attributes:{stage:e$1.stage,parallel:_,maxWorkers:S}}),e$1.json||console.log(O.gray(`Workspace run (${e$1.stage}) started: ${P} target(s), ${_?`parallel x${S}`:"sequential"}`));let K=new Map;for(let g of o){let k=W(y.relative(t,g)),a=await it(g),L=s.includes(g),E=L&&d$2.has(g);K.set(g,{path:g,relativePath:k,projectName:a??(y.basename(k)||y.basename(g)),selected:E,affected:E,status:"skipped",exitCode:null,durationMs:0,reason:E?void 0:L?"not affected":"outside scope",framework:void 0,runtimeDetected:void 0,executionCommand:void 0});}if(h)for(let g of R){let k=K.get(g);k&&(k.status="skipped",k.reason=`blocked by ${h.gate}`);}else {let g=async k=>{let a=K.get(k);if(!a)return;let L=W(y.relative(t,k));e$1.json||console.log(O.gray(`\u23F3 [${D}/${P}] ${e$1.stage} ${L}`)),a.selected=true,a.affected=true;let E=Date.now(),$=B(k),T=e$1.runtime?.trim().toLowerCase(),z=$.units.filter(f=>vt({projectPath:k,unit:f,selectedProjectPaths:R})).filter(f=>!T||f.runtime===T).map(f=>({unit:f,stage:f.stages.find(j=>j.stage===e$1.stage)})).filter(f=>!!f.stage),G=z.map(({unit:f,stage:j})=>({unitId:f.id,runtime:f.runtime,role:f.role,root:f.root,manifest:f.manifest,stage:j.stage,command:j.command,status:"planned",exitCode:null,durationMs:0}));if(a.runtimeExecutions=G,!$.polyglot&&!T&&G.length>0){let f=await xe(k);a.framework=f.framework,a.runtimeDetected=f.runtime;let j=f.commandOverrides?.[e$1.stage],M=j||(ut(f.runtime)?`rapidkit ${e$1.stage}`:le({projectPath:k,runtime:f.runtime,framework:f.framework,stage:e$1.stage}));if(M){let F=G[0];G.splice(0,G.length,{...F,unitId:`project:${f.runtime}`,root:".",manifest:z.map(({unit:ne})=>ne.manifest).join(", "),command:M});}}if(e$1.planOnly){a.runtimeDetected||(a.runtimeDetected=z[0]?.unit.runtime),a.status="skipped",a.reason=z.length>0?`plan only: ${z.length} runtime unit(s)`:T?`no ${T} runtime unit supports stage "${e$1.stage}"`:`no runtime unit supports stage "${e$1.stage}"`,a.durationMs=Date.now()-E,D+=1;return}if($.polyglot||T){if(z.length===0){a.status="failed",a.reason=T?`No ${T} runtime unit supports stage "${e$1.stage}"`:`No runtime unit supports stage "${e$1.stage}"`,a.errorCategory="setup",a.errorMessage=a.reason,a.exitCode=127,a.durationMs=Date.now()-E,D+=1;return}let f;for(let F=0;F<z.length;F+=1){let{unit:ne,stage:Ee}=z[F],Z=G[F],je=y.resolve(k,ne.root),pt=Date.now(),he=await xe(je),H=await ot(je,e$1.stage,ne.runtime,he.framework,{[e$1.stage]:Ee.command},he.environmentCommandVariants,he.environment,!e$1.json);if(Z.durationMs=Date.now()-pt,Z.exitCode=H.exitCode,Z.status=H.skipped?"skipped":H.exitCode===0?"passed":"failed",Z.reason=H.message,Z.errorCategory=H.errorCategory,Z.failureDiagnostic=H.failureDiagnostic,H.exitCode!==0&&!f&&(f=H.message??Ee.command),H.exitCode!==0&&!N){for(let Pe of G.slice(F+1))Pe.status="skipped",Pe.reason="stopped after runtime-unit failure";break}}let j=G.find(F=>F.status==="failed");a.runtimeDetected=z[0]?.unit.runtime,a.executionCommand=G.filter(F=>F.status!=="skipped").map(F=>`[${F.runtime}:${F.root}] ${F.command}`).join(" && "),a.durationMs=Date.now()-E;let M=G.find(F=>F.status==="passed");a.exitCode=j?.exitCode??0,a.status=j?"failed":M?"passed":"skipped",a.reason=j?f??"runtime-unit stage failed":M?void 0:"No applicable runtime unit executed the requested stage",a.errorCategory=j?j.errorCategory??"runtime":void 0,a.errorMessage=a.reason,a.failureDiagnostic=j?.failureDiagnostic,D+=1;return}let{runtime:fe,framework:ge,commandOverrides:ct,environmentCommandVariants:dt,environment:lt}=await xe(k);a.runtimeDetected=fe,a.framework=ge;let ye=tt(k,e$1.stage);if(!ye.supported){a.status=ye.shouldFail===false?"skipped":"failed",a.reason=ye.reason??`stage "${e$1.stage}" unsupported for project`,a.durationMs=Date.now()-E,a.exitCode=a.status==="failed"?127:null,a.status==="failed"&&(a.errorCategory="setup",a.errorMessage=a.reason),D+=1;return}if(e$1.reusePassed&&n){let f=n.stages[e$1.stage]??n.stages[e$1.stage];if(f&&at(f,k,t)){a.status="passed",a.reason="reused passed result from workspace-run-last.json",a.durationMs=Date.now()-E,a.exitCode=0,D+=1,e$1.json||console.log(O.gray(`\u21BA reused passed cache for ${L}`));return}}let Ce=Bt(fe,ge).filter(f=>f!==e$1.stage);if(Ce.length>0&&n){let f=Ce.find(j=>{let M=n.stages[j];return !M||!at(M,k,t)});if(f){a.status="skipped",a.reason=`dependency stage "${f}" not satisfied in workspace-run-last.json`,a.durationMs=Date.now()-E,a.exitCode=null,D+=1;return}}let A=await ot(k,e$1.stage,fe,ge,ct,dt,lt,!e$1.json);a.executionCommand=A.command,a.errorCategory=A.errorCategory,a.healthStatus=A.healthStatus,a.failureDiagnostic=A.failureDiagnostic,a.durationMs=Date.now()-E,a.exitCode=A.exitCode;let q=a.runtimeExecutions?.[0];if(q&&(q.command=A.command,q.status=A.skipped?"skipped":A.exitCode===0?"passed":"failed",q.exitCode=A.exitCode,q.durationMs=a.durationMs,q.reason=A.message,q.errorCategory=A.errorCategory,q.failureDiagnostic=A.failureDiagnostic),A.skipped?(a.status="skipped",a.reason=A.message):A.exitCode===0?(a.status="passed",a.reason=void 0):(a.status="failed",a.reason=A.message||"stage command failed",a.errorMessage=A.message),D+=1,!e$1.json){let f=P>0?Math.round(D/P*100):100,j=a.status==="passed"?O.green("\u2705"):O.red("\u274C");if(console.log(O.gray(`${j} [${D}/${P}] (${f}%) ${L} ${a.durationMs}ms`)),a.status==="failed"){a.reason&&console.log(O.red(` Reason: ${a.reason}`)),a.executionCommand&&console.log(O.gray(` Command: ${a.executionCommand}`));let M=Nt(a.runtimeDetected);M&&a.errorCategory==="setup"&&console.log(O.gray(` Hint: ${M}`));}}};if(_&&R.length>1){let k=0,a=false,L=new Array(S).fill(null).map(async()=>{for(;k<R.length;){if(a&&!N)return;let E=k;k+=1;let $=R[E];await g($),K.get($)?.status==="failed"&&(a=true);}});if(await Promise.all(L),!N&&a){let E=false;for(let $ of R){let T=K.get($);if(T){if(T.status==="failed"){E=true;continue}E&&T.status==="skipped"&&(T.reason=T.reason||"stopped after failure");}}}}else for(let k of R){await g(k);let a=K.get(k);if(!N&&a?.status==="failed"){let L=R.slice(R.indexOf(k)+1);for(let E of L){let $=K.get(E);$&&($.status="skipped",$.reason="stopped after failure");}break}}}let U=[];for(let g of o){let k=K.get(g);k&&U.push(k);}let V=U.filter(g=>g.status==="passed").length,J=U.filter(g=>g.status==="failed").length,b$1=U.filter(g=>g.status==="skipped").length;c({blockId:"workspace.run.execute",status:J>0?"failed":h?"blocked":"succeeded",message:`Workspace run finished: ${V} passed, ${J} failed, ${b$1} skipped`,component:"workspace-run",progress:{completed:P,total:P,percent:100},attributes:{passed:V,failed:J,skipped:b$1,stage:e$1.stage}});let I=e$1.strict===true,me=J>0||I&&x.some(g=>g.status==="fail"||g.status==="warn")?1:0,ee={schemaVersion:"1.0",workspacePath:t,stage:e$1.stage,generatedAt:new Date().toISOString(),durationMs:Date.now()-r,options:{affected:p,blastRadius:c$1,since:p?m:null,parallel:_,maxWorkers:S,continueOnError:N,strict:I,enforceGates:C,scope:i,reusePassed:e$1.reusePassed===true,planOnly:e$1.planOnly===true,runtime:e$1.runtime?.trim()||null},selection:{mode:v,since:p?m:null,scope:i,graphStatus:l,expansionDepth:w},gates:{enforced:C,results:x,blocked:!!h,blockingGate:h?.gate},summary:{projectCount:o.length,selectedCount:R.length,passed:V,failed:J,skipped:b$1,exitCode:me},projects:U,enterpriseControls:{jsonReady:true,evidencePath:b}},Se=y.join(t,b);c({blockId:"workspace.run.publish",status:"running",message:"Publishing workspace run evidence",component:"workspace.run"});try{await e(t,ee),c({blockId:"workspace.run.publish",status:"succeeded",message:"Workspace run evidence published",component:"workspace.run"}),d$1({workspacePath:t,relativePath:b,blockId:"workspace.run.publish"});}catch(g){throw c({blockId:"workspace.run.publish",status:"failed",message:g instanceof Error?g.message:"Workspace run evidence publish failed",component:"workspace.run"}),g}return e$1.json||(h&&(console.log(O.red(`\u274C Workspace run blocked by ${h.gate}`)),console.log(O.gray(` ${h.summary}`))),console.log(O.cyan(`Workspace run (${e$1.stage}) => passed: ${V}, failed: ${J}, skipped: ${b$1}`)),console.log(O.gray(`Report: ${Se}`))),ee}export{Tt as a,Rr as b};