workspai 0.75.0 → 0.75.1

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 (65) hide show
  1. package/dist/analyze-Z3EZNJRI.js +1 -0
  2. package/dist/autopilot-release-T6XFRWZT.js +1 -0
  3. package/dist/{chunk-FS3WLRQ4.js → chunk-25V5XMWB.js} +1 -1
  4. package/dist/{chunk-WOPZX56J.js → chunk-2CT5SN2L.js} +1 -1
  5. package/dist/{chunk-V5WVGPOP.js → chunk-2GWQ6NZV.js} +1 -1
  6. package/dist/{chunk-GE46XKD2.js → chunk-2OCJKLTW.js} +1 -1
  7. package/dist/{chunk-ZW4QV6SB.js → chunk-3WQ5TYCO.js} +1 -1
  8. package/dist/{chunk-NGU7RYXA.js → chunk-4VSQNSGH.js} +1 -1
  9. package/dist/{chunk-CGNMS32W.js → chunk-566NQQTJ.js} +1 -1
  10. package/dist/{chunk-G3ZC5W4U.js → chunk-5EEXLM45.js} +1 -1
  11. package/dist/{chunk-YP436V7Q.js → chunk-65AE7EC5.js} +1 -1
  12. package/dist/{chunk-HLSOZOL3.js → chunk-6KMR5PKQ.js} +2 -2
  13. package/dist/{chunk-J4J3RYCL.js → chunk-6NSJBKKK.js} +1 -1
  14. package/dist/{chunk-TXVMHEJS.js → chunk-ABUSBLBH.js} +1 -1
  15. package/dist/{chunk-RX3U7JKF.js → chunk-AICCXYY5.js} +1 -1
  16. package/dist/{chunk-O2CFT2A3.js → chunk-FU6SQ2ND.js} +1 -1
  17. package/dist/{chunk-MXI2DWLL.js → chunk-HDISUL3F.js} +1 -1
  18. package/dist/{chunk-LMOTDLJF.js → chunk-M6DVNC6X.js} +1 -1
  19. package/dist/{chunk-4KEZQLBU.js → chunk-NGZF4YJS.js} +1 -1
  20. package/dist/{chunk-CK73SQFF.js → chunk-NI5QWBZK.js} +1 -1
  21. package/dist/{chunk-NFWUAEVQ.js → chunk-NRIMJMTF.js} +8 -8
  22. package/dist/{chunk-36VNERGC.js → chunk-QBKOPXKC.js} +1 -1
  23. package/dist/{chunk-SRCZX2KC.js → chunk-RTD5D35M.js} +1 -1
  24. package/dist/{chunk-GIFAGOMK.js → chunk-SCKEFXF5.js} +1 -1
  25. package/dist/{chunk-DT3LRKZQ.js → chunk-UE7ART6X.js} +1 -1
  26. package/dist/{chunk-P5RZO5BY.js → chunk-VJQPIH2S.js} +35 -35
  27. package/dist/{chunk-4DX4HBG3.js → chunk-WPPRUFJW.js} +1 -1
  28. package/dist/{create-7UENFCJK.js → create-P4XJVZCL.js} +1 -1
  29. package/dist/{doctor-KGADT4PI.js → doctor-PFN6KB6P.js} +1 -1
  30. package/dist/{goal-lifecycle-HIQGDEEP.js → goal-lifecycle-BDWTWS55.js} +1 -1
  31. package/dist/{goal-pack-63PEP2ND.js → goal-pack-5JDNZFKV.js} +1 -1
  32. package/dist/index.js +179 -172
  33. package/dist/{pipeline-VFI35PR4.js → pipeline-OUYS4ZYV.js} +1 -1
  34. package/dist/{project-agent-entry-Z3OY3S7T.js → project-agent-entry-75WO3QWP.js} +1 -1
  35. package/dist/{project-intelligence-lens-YWICXW6P.js → project-intelligence-lens-JCHFOIA7.js} +1 -1
  36. package/dist/{proof-carrying-change-BAP2C3KV.js → proof-carrying-change-LAYV4LTI.js} +1 -1
  37. package/dist/{verified-goal-A6WOMNTU.js → verified-goal-75KGBWTE.js} +1 -1
  38. package/dist/{workspace-PAXTJCMH.js → workspace-CBQDOUSH.js} +1 -1
  39. package/dist/{workspace-agent-sync-MGCEF4ON.js → workspace-agent-sync-RTOTO3DY.js} +1 -1
  40. package/dist/{workspace-context-2G6QZ6D3.js → workspace-context-STRZO2N3.js} +1 -1
  41. package/dist/{workspace-contract-VWPOIYHJ.js → workspace-contract-PMHUUKFM.js} +1 -1
  42. package/dist/{workspace-explain-HLEBUK4K.js → workspace-explain-CATMJUMN.js} +1 -1
  43. package/dist/{workspace-foundation-X7LOGTS3.js → workspace-foundation-OULCDCXG.js} +1 -1
  44. package/dist/{workspace-graph-stream-XGSRDRLI.js → workspace-graph-stream-Q55CI4K4.js} +1 -1
  45. package/dist/{workspace-intelligence-GFJKIWBX.js → workspace-intelligence-3RPZRWSF.js} +1 -1
  46. package/dist/{workspace-intelligence-runner-BU6JKNUD.js → workspace-intelligence-runner-BNZUYUUN.js} +1 -1
  47. package/dist/{workspace-knowledge-graph-OUTCLYS2.js → workspace-knowledge-graph-VJLD35ES.js} +1 -1
  48. package/dist/workspace-knowledge-graph-snapshot-TQAKDDUA.js +1 -0
  49. package/dist/{workspace-mcp-serve-JYUKX3YS.js → workspace-mcp-serve-67NTYD67.js} +1 -1
  50. package/dist/{workspace-model-DUGPW5IB.js → workspace-model-6TKZMNEF.js} +1 -1
  51. package/dist/{workspace-onboarding-C4CKWTJ3.js → workspace-onboarding-7V7EH3RH.js} +1 -1
  52. package/dist/{workspace-registry-summary-4KX4QD55.js → workspace-registry-summary-ILVO7DEU.js} +1 -1
  53. package/dist/{workspace-repair-engine-OVW4J3DI.js → workspace-repair-engine-2VGFB3DJ.js} +1 -1
  54. package/dist/workspace-run-X7KV6MIT.js +1 -0
  55. package/dist/{workspace-verify-B7HEFYO6.js → workspace-verify-VQWYDAF2.js} +1 -1
  56. package/dist/{workspace-watch-TQYAMLIV.js → workspace-watch-2Z636HWS.js} +1 -1
  57. package/docs/ci-workflows.md +15 -8
  58. package/docs/commands-reference.md +6 -0
  59. package/docs/workspace-operations.md +12 -2
  60. package/package.json +1 -1
  61. package/dist/analyze-FRQVJ3VJ.js +0 -1
  62. package/dist/autopilot-release-D3UES53H.js +0 -1
  63. package/dist/workspace-knowledge-graph-snapshot-XWJRUMAC.js +0 -1
  64. package/dist/workspace-run-NVQGRZYO.js +0 -1
  65. /package/dist/{chunk-D4AMCZJU.js → chunk-PTI743SC.js} +0 -0
@@ -1,4 +1,4 @@
1
- import {a as a$1}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-DT3LRKZQ.js';import {l,q}from'./chunk-36VNERGC.js';import {f,g,h as h$2}from'./chunk-G3ZC5W4U.js';import {a as a$3}from'./chunk-FS3WLRQ4.js';import {i,h as h$1,d,b as b$1,a as a$2,c as c$2,k as k$2}from'./chunk-BLEIUQL6.js';import {b as b$3}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {h,i as i$1,m,k as k$1,n,o,g as g$1,l as l$1,j,s,e,f as f$1}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {randomUUID,createHash}from'crypto';import P from'path';import T from'fs-extra';var rt=new Set(["committed","rejected","aborted","superseded"]);function p(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function nt(e){return [...new Set(e)].sort()}function Ge(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function ze(e,t,a){p(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function it(e,t){ze(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return p(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function st(e,t,a){return ze(e.verifications,t.id,"verification"),p(t.target.effectHeadDigest===Ge(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function ot(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 ct(e$1,t,a){if(t.kind==="created"){p(e$1===null,"created must be the first event");let w=t.payload.references?.[0];p(w,"created must bind an intent artifact");let u=t.payload.references?.filter(I=>I.role==="success-criterion").map(I=>I.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:nt(u),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}p(e$1,`${t.kind} cannot occur before created`),p(!rt.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,n=e$1.scope,i=e$1.evidence,d=e$1.plans,f=e$1.authorization,l=e$1.effects,s=e$1.verifications,o=e$1.blockers,h=e$1.terminalReason;switch(t.kind){case "scope-bound":p(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),p(t.payload.scope,"scope-bound requires scope"),n=t.payload.scope,r="scoped";break;case "evidence-attached":p(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),p((t.payload.references?.length??0)>0,"evidence-attached requires references"),i=[...i,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":p(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),p((t.payload.references?.length??0)>0,"plan-attached requires references"),d=[...d,...t.payload.references??[]];break;case "authorized":p(e$1.state==="evidence-ready","authorization requires evidence-ready state"),p(t.payload.authorization,"authorized requires a bounded authorization grant"),f=t.payload.authorization,r="authorized";break;case "effect-requested":p(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":p(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),p(t.payload.effect,"effect-recorded requires a receipt"),p(f?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),l=it(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(o=[...o,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":p(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",o=[...o,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":p(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{p(e$1.state==="verifying","verification-recorded requires verifying state"),p(t.payload.verification,"verification-recorded requires a receipt"),s=st(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":p(t.payload.blocker,"blocked requires a structured blocker"),o=[...o,t.payload.blocker],r="blocked";break;case "resumed":p(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),p(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,o=[];break;case "committed":p(e$1.state==="verifying","commit requires verifying state"),p(ot(e$1),"every required criterion needs a latest passing receipt"),p(!e$1.effects.some(w=>w.status!=="succeeded"),"all effects must be certainly successful"),r="committed",h=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,h=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:n,evidence:i,plans:d,authorization:f,effects:l,verifications:s,blockers:o,...h?{terminalReason:h}:{}}}function qe(e,t,a,r){let n=(t?.sequence??0)+1,i={schemaVersion:f$1,transactionId:e,sequence:n,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...i,digest:r.digestCanonical(i)}}function L(e,t){p(e.length>0,"at least one event is required");let a=null,r=null;for(let n of e){p(n.schemaVersion===f$1,`unsupported event schema ${n.schemaVersion}`),p(n.sequence===(r?.sequence??0)+1,`event sequence ${n.sequence} is not contiguous`),p(n.previousEventDigest===(r?.digest??null),`event ${n.sequence} has an invalid previous digest`);let{digest:i,...d}=n;p(n.digest===t.digestCanonical(d),`event ${n.sequence} digest is invalid`),p(!r||n.transactionId===r.transactionId,"events cross transaction boundaries"),a=ct(a,n,t),r=n;}return a}function ne(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 U(e,t){return Ge(e,t)}var G={digestCanonical:c};function lt(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 N(e){let a=`.workspai/decisions/${lt(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function ft(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,n)=>{try{return JSON.parse(r)}catch(i){throw new Error(`Decision event log is corrupt at ${t}:${n+1}: ${i.message}`)}})}async function Ne(e,t){let a=N(t),r=await b$1(e,a.events);return r?ft(await T.readFile(r,"utf8"),r):[]}function We(e,t){let a=N(t);return {directory:a$2(e,a.directory),transaction:a$2(e,a.transaction),checkpoint:a$2(e,a.checkpoint),events:a$2(e,a.events)}}async function gt(e,t,a$1,r){let n=N(t.id),i=ne(t,r,G);for(let[d,f]of a$1.entries())a(f,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${d+1}`);return b$3(n.transaction,t),b$3(n.checkpoint,i),await k$2(e,n.events,`${a$1.map(d=>JSON.stringify(d)).join(`
1
+ import {a as a$1}from'./chunk-FIK343LI.js';import {c as c$1}from'./chunk-UE7ART6X.js';import {l,q}from'./chunk-QBKOPXKC.js';import {f,g,h as h$2}from'./chunk-5EEXLM45.js';import {a as a$3}from'./chunk-25V5XMWB.js';import {i,h as h$1,d,b as b$1,a as a$2,c as c$2,k as k$2}from'./chunk-BLEIUQL6.js';import {b as b$3}from'./chunk-VN2MKTQO.js';import {a}from'./chunk-AFIFZTOY.js';import {a as a$4}from'./chunk-XWKGZRHN.js';import {c,d as d$1}from'./chunk-EWZZUQBR.js';import {b as b$2}from'./chunk-25AWHAB5.js';import {h,i as i$1,m,k as k$1,n,o,g as g$1,l as l$1,j,s,e,f as f$1}from'./chunk-ODK4LCEL.js';import {a as a$5}from'./chunk-FB7SCXAZ.js';import {randomUUID,createHash}from'crypto';import P from'path';import T from'fs-extra';var rt=new Set(["committed","rejected","aborted","superseded"]);function p(e,t){if(!e)throw new Error(`Decision protocol violation: ${t}`)}function nt(e){return [...new Set(e)].sort()}function Ge(e,t){return t.digestCanonical(e.effects.map(a=>({id:a.id,status:a.status,key:a.idempotencyKey})))}function ze(e,t,a){p(!e.some(r=>r.id===t),`${a} receipt '${t}' already exists`);}function it(e,t){ze(e.effects,t.id,"effect");let a=e.effects.find(r=>r.idempotencyKey===t.idempotencyKey);return p(!a,`effect idempotency key '${t.idempotencyKey}' was already recorded by '${a?.id}'`),[...e.effects,t]}function st(e,t,a){return ze(e.verifications,t.id,"verification"),p(t.target.effectHeadDigest===Ge(e,a),`verification '${t.id}' does not bind the current effect head`),[...e.verifications,t]}function ot(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 ct(e$1,t,a){if(t.kind==="created"){p(e$1===null,"created must be the first event");let w=t.payload.references?.[0];p(w,"created must bind an intent artifact");let u=t.payload.references?.filter(I=>I.role==="success-criterion").map(I=>I.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:nt(u),scope:null,evidence:[],plans:[],authorization:null,effects:[],verifications:[],blockers:[]}}p(e$1,`${t.kind} cannot occur before created`),p(!rt.has(e$1.state),`${t.kind} cannot follow terminal state ${e$1.state}`);let r=e$1.state,n=e$1.scope,i=e$1.evidence,d=e$1.plans,f=e$1.authorization,l=e$1.effects,s=e$1.verifications,o=e$1.blockers,h=e$1.terminalReason;switch(t.kind){case "scope-bound":p(e$1.state==="draft"||e$1.state==="scoped","scope-bound requires draft or scoped state"),p(t.payload.scope,"scope-bound requires scope"),n=t.payload.scope,r="scoped";break;case "evidence-attached":p(e$1.state==="scoped"||e$1.state==="evidence-ready","evidence-attached requires scoped state"),p((t.payload.references?.length??0)>0,"evidence-attached requires references"),i=[...i,...t.payload.references??[]],r="evidence-ready";break;case "plan-attached":p(e$1.state==="evidence-ready","plan-attached requires evidence-ready state"),p((t.payload.references?.length??0)>0,"plan-attached requires references"),d=[...d,...t.payload.references??[]];break;case "authorized":p(e$1.state==="evidence-ready","authorization requires evidence-ready state"),p(t.payload.authorization,"authorized requires a bounded authorization grant"),f=t.payload.authorization,r="authorized";break;case "effect-requested":p(e$1.state==="authorized"||e$1.state==="executing","effect-requested requires authorization"),r="executing";break;case "effect-recorded":p(e$1.state==="authorized"||e$1.state==="executing","effect-recorded requires authorization"),p(t.payload.effect,"effect-recorded requires a receipt"),p(f?.effectClasses.includes(t.payload.effect.effectClass),`effect class '${t.payload.effect.effectClass}' is outside the authorization grant`),l=it(e$1,t.payload.effect),r=t.payload.effect.status==="succeeded"?"executing":"blocked",t.payload.effect.status!=="succeeded"&&(o=[...o,{code:t.payload.effect.status==="uncertain"?"decision.effect.uncertain":"decision.effect.failed",actionable:true,details:t.payload.effect.summary}]);break;case "effect-uncertain":p(e$1.state==="authorized"||e$1.state==="executing","effect-uncertain requires an active execution"),r="blocked",o=[...o,t.payload.blocker??{code:"decision.effect.uncertain",actionable:true}];break;case "verification-started":p(e$1.state==="authorized"||e$1.state==="executing","verification-started requires authorized or executing state"),r="verifying";break;case "verification-recorded":{p(e$1.state==="verifying","verification-recorded requires verifying state"),p(t.payload.verification,"verification-recorded requires a receipt"),s=st(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":p(t.payload.blocker,"blocked requires a structured blocker"),o=[...o,t.payload.blocker],r="blocked";break;case "resumed":p(e$1.state==="blocked"||e$1.state==="awaiting-human","resumed requires a paused state"),p(t.payload.resumeTo,"resumed requires an explicit target state"),r=t.payload.resumeTo,o=[];break;case "committed":p(e$1.state==="verifying","commit requires verifying state"),p(ot(e$1),"every required criterion needs a latest passing receipt"),p(!e$1.effects.some(w=>w.status!=="succeeded"),"all effects must be certainly successful"),r="committed",h=t.payload.reason??t.payload.summary;break;case "rejected":case "aborted":case "superseded":r=t.kind,h=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:n,evidence:i,plans:d,authorization:f,effects:l,verifications:s,blockers:o,...h?{terminalReason:h}:{}}}function qe(e,t,a,r){let n=(t?.sequence??0)+1,i={schemaVersion:f$1,transactionId:e,sequence:n,kind:a.kind,occurredAt:a.occurredAt,actor:a.actor,previousEventDigest:t?.digest??null,payload:a.payload};return {...i,digest:r.digestCanonical(i)}}function L(e,t){p(e.length>0,"at least one event is required");let a=null,r=null;for(let n of e){p(n.schemaVersion===f$1,`unsupported event schema ${n.schemaVersion}`),p(n.sequence===(r?.sequence??0)+1,`event sequence ${n.sequence} is not contiguous`),p(n.previousEventDigest===(r?.digest??null),`event ${n.sequence} has an invalid previous digest`);let{digest:i,...d}=n;p(n.digest===t.digestCanonical(d),`event ${n.sequence} digest is invalid`),p(!r||n.transactionId===r.transactionId,"events cross transaction boundaries"),a=ct(a,n,t),r=n;}return a}function ne(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 U(e,t){return Ge(e,t)}var G={digestCanonical:c};function lt(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 N(e){let a=`.workspai/decisions/${lt(e)}`;return {directory:a,transaction:`${a}/transaction.json`,checkpoint:`${a}/checkpoint.json`,events:`${a}/events.jsonl`,lock:`${a}.lock`}}function ft(e,t){return e.split(/\r?\n/).filter(r=>r.trim().length>0).map((r,n)=>{try{return JSON.parse(r)}catch(i){throw new Error(`Decision event log is corrupt at ${t}:${n+1}: ${i.message}`)}})}async function Ne(e,t){let a=N(t),r=await b$1(e,a.events);return r?ft(await T.readFile(r,"utf8"),r):[]}function We(e,t){let a=N(t);return {directory:a$2(e,a.directory),transaction:a$2(e,a.transaction),checkpoint:a$2(e,a.checkpoint),events:a$2(e,a.events)}}async function gt(e,t,a$1,r){let n=N(t.id),i=ne(t,r,G);for(let[d,f]of a$1.entries())a(f,"contracts/workspace-intelligence/decision-event.v1.json",`Decision event ${d+1}`);return b$3(n.transaction,t),b$3(n.checkpoint,i),await k$2(e,n.events,`${a$1.map(d=>JSON.stringify(d)).join(`
2
2
  `)}
3
3
  `),await h$1(e,n.transaction,t),await h$1(e,n.checkpoint,i),{transaction:t,checkpoint:i,events:a$1,paths:We(e,t.id)}}async function Me(e){let t=N(e.transactionId),a=a$2(e.workspacePath,t.lock);return a$4(a,async()=>{let r=await Ne(e.workspacePath,e.transactionId),n=r.at(-1)??null;if((n?.digest??null)!==e.expectedHeadDigest)throw new Error(`Decision transaction head changed: expected ${e.expectedHeadDigest??"<empty>"}, observed ${n?.digest??"<empty>"}`);r.length>0&&L(r,G);let i=qe(e.transactionId,n,e.event,G),d=[...r,i],f=L(d,G);return gt(e.workspacePath,f,d,e.event.occurredAt)},{purpose:`decision:${e.transactionId}`,timeoutMs:3e4,staleMs:6e4})}async function Be(e,t){let a=await Ne(e,t);if(a.length===0)throw new Error(`Decision transaction not found: ${t}`);let r=L(a,G),n=ne(r,r.updatedAt,G);return {transaction:r,checkpoint:n,events:a,paths:We(e,t)}}function W(e){return N(e).directory}var oe={digestCanonical:c},pt="workspai.deleted-artifact-tombstone.v1";function ut(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 E(e){let a=`.workspai/changes/${ut(e)}`;return {directory:a,lease:`${a}/lease.json`,prediction:`${a}/predicted-overlay.json`,actualOverlay:`${a}/actual-overlay.json`,surprises:`${a}/architecture-surprises.json`,workspaceVerification:`${a}/verification/workspace-verify.json`,capsule:`${a}/capsule.json`,privateBaselineGraph:`${a}/private/baseline-graph.json`}}function mt(e,t){return {kind:e,id:t}}function x(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 A(e,t){let a=await b$1(e,t);return a?await T.readJson(a):null}async function Fe(e,t){let a=await d(e,C(t));return !a||!(await T.stat(a).catch(()=>null))?.isFile()?null:createHash("sha256").update(await T.readFile(a)).digest("hex")}async function yt(e,t){let a=new Map;await Promise.all(t.proofs.map(async n=>{let i=C(n.artifact),d=a.get(i);d||(d=Fe(e,i),a.set(i,d)),await d;}));let r=Object.fromEntries((await Promise.all([...a.entries()].map(async([n,i])=>[n,await i]))).filter(n=>typeof n[1]=="string"));return {...t,pccArtifactContentHashes:r}}async function wt(e){let a=(await A(e,s.workspaceContract.artifactPath))?.workspace?.name;if(typeof a=="string"&&a.trim())return a.trim();let r=await A(e,".workspai/workspace.json"),n=r?.workspace_name??r?.name;return typeof n=="string"&&n.trim()?n.trim():P.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 i=await T.readFile(a);return createHash("sha256").update(i).digest("hex")===t.digest.value}let r=await T.readJson(a).catch(()=>null);return r?(t.digest.semantics==="workspace-model-structural-v1"?d$1(r):c(r))===t.digest.value:false}function Je(e){return c({schemaVersion:pt,artifact:C(e),deleted:true})}function vt(e){let t=C(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:Je(t)}}}async function Ye(e,t){if(t.digest.algorithm!=="sha256"||t.digest.semantics!=="deletion-tombstone-v1"||t.digest.value!==Je(t.artifact))return false;let a=await d(e,t.artifact);return a!==null&&!await T.pathExists(a)}async function kt(e,t){let a=await A(e,E(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 J(e){let t=await a$3(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 Ct(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:Ct(t,a,r)}}async function de(e,t){let a=await J(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,n=new Date().toISOString()){return {kind:e,payload:t,occurredAt:n,actor:mt(a,r)}}async function k(e,t,a,r){return Me({workspacePath:e,transactionId:a,expectedHeadDigest:t?.transaction.eventHeadDigest??null,event:r})}function b(e,t,a){return `${e}\0${t}\0${a}`}function It(e){let t=[];for(let[a,r]of [["entity",e.entities],["relation",e.relations],["proof",e.proofs]])t.push(...r.added.map(n=>({operation:"add",targetKind:a,targetId:n.id}))),t.push(...r.removed.map(n=>({operation:"remove",targetKind:a,targetId:n.id}))),t.push(...r.changed.map(n=>({operation:"change",targetKind:a,targetId:n.id})));return t.push(...e.changedArtifacts.map(a=>({operation:"change",targetKind:"artifact",targetId:a}))),t.sort((a,r)=>b(a.operation,a.targetKind,a.targetId).localeCompare(b(r.operation,r.targetKind,r.targetId)))}function Pt(e,t){let a=new Set(t.filter(s=>s.targetKind==="artifact").map(s=>C(s.targetId)));if(a.size===0)return new Set;let r=new Set,n=new Set,i=(s,o)=>{a.has(C(o.artifact))&&(n.add(o.id),r.add(b(s,"proof",o.id)));};e.proofs.added.forEach(s=>i("add",s)),e.proofs.removed.forEach(s=>i("remove",s)),e.proofs.changed.forEach(s=>{let o=s.after??s.before;o&&i("change",o);});let d=new Set,f=(s,o)=>{o.proofIds.some(h=>n.has(h))&&(d.add(o.id),r.add(b(s,"entity",o.id)));};e.entities.added.forEach(s=>f("add",s)),e.entities.removed.forEach(s=>f("remove",s)),e.entities.changed.forEach(s=>{let o=s.after??s.before;o&&f("change",o);});let l=(s,o)=>{!o.proofIds.some(h=>n.has(h))&&!d.has(o.from)&&!d.has(o.to)||r.add(b(s,"relation",o.id));};return e.relations.added.forEach(s=>l("add",s)),e.relations.removed.forEach(s=>l("remove",s)),e.relations.changed.forEach(s=>{let o=s.after??s.before;o&&l("change",o);}),r}function bt(e){let t=e.prediction?.operations.map(o=>({operation:o.operation,targetKind:o.targetKind,targetId:o.targetId}))??[],a=It(e.actual),r=new Set(t.map(o=>b(o.operation,o.targetKind,o.targetId))),n=new Set(a.map(o=>b(o.operation,o.targetKind,o.targetId))),i=Pt(e.actual,t),d=a.filter(o=>r.has(b(o.operation,o.targetKind,o.targetId))||i.has(b(o.operation,o.targetKind,o.targetId))),f=a.filter(o=>!r.has(b(o.operation,o.targetKind,o.targetId))&&!i.has(b(o.operation,o.targetKind,o.targetId))),l=t.filter(o=>!n.has(b(o.operation,o.targetKind,o.targetId))),s=e.prediction?f.length===0&&l.length===0&&i.size===0?"exact":f.length===0?"within-expectation":"surprising":"no-prediction";return {schemaVersion:j,changeId:e.changeId,generatedAt:e.generatedAt,prediction:e.predictionReference,actual:e.actualReference,matched:d,unpredicted:f,missing:l,summary:{predicted:t.length,actual:a.length,matched:d.length,unpredicted:f.length,missing:l.length,verdict:s}}}async function ie(e){let t=await A(e.workspacePath,e.relativePath);return t?x({role:e.role,artifact:e.relativePath,schemaVersion:e.schemaVersion,value:c(t)}):null}function At(e){let{integrity:t,...a}=e;return a}async function le(e){let t=E(e.lease.changeId),[a,r,n]=await Promise.all([ie({workspacePath:e.workspacePath,relativePath:t.prediction,role:"prediction",schemaVersion:i$1}),ie({workspacePath:e.workspacePath,relativePath:t.actualOverlay,role:"actual-architecture-overlay",schemaVersion:a$5}),ie({workspacePath:e.workspacePath,relativePath:t.surprises,role:"architecture-surprises",schemaVersion:j})]),i=x({role:"decision-transaction",artifact:`${W(e.lease.changeId)}/transaction.json`,schemaVersion:e.record.transaction.schemaVersion,value:c(e.record.transaction)}),d=e.record.transaction.effects.flatMap(g=>g.artifacts),f=e.record.transaction.effects.flatMap(g=>g.deletedArtifacts??[]),l=e.record.transaction.verifications.flatMap(g=>g.artifacts),s=await A(e.workspacePath,t.actualOverlay),o=s?!se(s):false,h=[{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(g=>g.status==="succeeded")||e.record.transaction.effects.length===0&&o?"passed":e.record.transaction.effects.length===0?"pending":"failed",summary:e.record.transaction.effects.length===0&&o?"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(g=>g.status==="failed")?"failed":"pending",summary:`${e.record.transaction.verifications.length} independent verification receipt(s) are recorded.`}],w=await A(e.workspacePath,t.surprises),u=[...e.record.transaction.effects.length===0&&s&&se(s)?["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(g=>g.details??g.code)],I=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(g=>g.status==="passed")?"verified":"open",c$1={schemaVersion:k$1,changeId:e.lease.changeId,goalId:e.lease.goalId,generatedAt:e.record.transaction.updatedAt,status:I,workspace:e.lease.workspace,scope:e.lease.scope,decision:{transaction:i,eventHeadDigest:e.record.transaction.eventHeadDigest,effectHeadDigest:U(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:n,effects:d,deletedArtifacts:f,verification:l,assurances:h,remainingUncertainty:[...new Set(u)]};return {...c$1,integrity:{algorithm:"sha256",semantics:"canonical-json-v1",capsuleDigest:c(c$1)}}}async function S(e,t,a){let r=await le({workspacePath:e,lease:t,record:a});return await h$1(e,E(t.changeId).capsule,r),r}function V(e){let t=E(e.lease.changeId),a$1={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:`${W(e.lease.changeId)}/transaction.json`,events:`${W(e.lease.changeId)}/events.jsonl`,capsule:t.capsule},nextActions:e.nextActions};return a(a$1,"contracts/workspace-intelligence/change-operation-result.v1.json","Proof-Carrying Change operation result"),b$2({kind:"operation.completed",status:e.record.transaction.state==="blocked"||e.record.transaction.state==="awaiting-human"?"blocked":e.record.transaction.state==="aborted"?"cancelled":"succeeded",component:"proof-carrying-change",correlationId:e.lease.changeId,message:`${e.operation}: ${e.record.transaction.state}`,evidenceBindings:[{kind:"artifact",ref:t.capsule,role:"output",provenance:"authoritative"},{kind:"artifact",ref:`${W(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$1}async function R(e,t){let a=await kt(e,t),r=await Be(e,t);return {lease:a,record:r}}async function sa(e){let t=P.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 n=await J(t),i$1=Y(n);if(i$1.modelHash!==r.sourceBinding.model.hash||(r.sourceBinding.graph.inputHash?i$1.inputHash!==r.sourceBinding.graph.inputHash:i$1.graphHash!==r.sourceBinding.graph.hash))throw new Error(`Goal ${r.id} is no longer bound to the current architecture generation.`);let d=`change-${r.intent.category}-${randomUUID().replace(/-/g,"").slice(0,16)}`,f=E(d),l$1=new Date().toISOString(),s=await yt(t,n.graph),o=c(s),h$1={schemaVersion:h,changeId:d,goalId:r.id,createdAt:l$1,workspace:r.workspace,scope:{kind:r.scope.kind,projects:[...r.scope.projects]},baseline:{model:x({role:"baseline-model",artifact:r.sourceBinding.model.artifact,schemaVersion:r.sourceBinding.model.schemaVersion,value:r.sourceBinding.model.hash,semantics:"workspace-model-structural-v1"}),graph:{...x({role:"baseline-graph",artifact:r.sourceBinding.graph.artifact,schemaVersion:r.sourceBinding.graph.schemaVersion,value:i$1.graphHash}),inputHash:i$1.inputHash}},generation:i$1.generation,semantics:"optimistic-generation-guard",privateMaterialization:{artifact:f.privateBaselineGraph,role:"hash-bound-baseline-cache",portable:false,authoritative:false,digest:{algorithm:"sha256",semantics:"canonical-json-v1",value:o}}};await i(t,f.lease,[{relativePath:f.privateBaselineGraph,payload:s},{relativePath:f.lease,payload:h$1}]);let w=e.actorKind??"cli",u=e.actorId??"workspai-change",I=x({role:"intent",artifact:a.active.goalPack,schemaVersion:r.schemaVersion,value:c(r)}),c$1=r.successCriteria.map(j=>x({role:"success-criterion",artifact:j.id,schemaVersion:"workspai.goal-success-criterion.v1",value:c(j)})),g=await k(t,null,d,v("created",{summary:`Begin proof-carrying change for ${r.id}.`,references:[I,...c$1]},w,u,l$1));g=await k(t,g,d,v("scope-bound",{summary:"Bind immutable Goal scope.",scope:h$1.scope},w,u)),g=await k(t,g,d,v("evidence-attached",{summary:"Attach exact architecture generation and lease.",references:[h$1.baseline.model,{role:h$1.baseline.graph.role,artifact:h$1.baseline.graph.artifact,schemaVersion:h$1.baseline.graph.schemaVersion,digest:h$1.baseline.graph.digest},x({role:"architecture-lease",artifact:f.lease,schemaVersion:h$1.schemaVersion,value:c(h$1)})]},w,u)),await q({workspacePath:t,goalId:r.id,changeId:d});let D=await S(t,h$1,g);return V({operation:"begin",lease:h$1,record:g,capsule:D,nextActions:[`workspai change predict --change ${d} --file <prediction.json> --json`,`workspai change authorize --change ${d} --effects filesystem,command --json`]})}async function oa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await de(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((f,l)=>b(f.operation,f.targetKind,f.targetId).localeCompare(b(l.operation,l.targetKind,l.targetId)))};await h$1(e.workspacePath,E(e.changeId).prediction,r);let n=x({role:"noncanonical-prediction",artifact:E(e.changeId).prediction,schemaVersion:r.schemaVersion,value:c(r)}),i=await k(e.workspacePath,a,e.changeId,v("plan-attached",{summary:"Attach an explicitly noncanonical architecture prediction.",references:[n]},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await S(e.workspacePath,t,i);return V({operation:"predict",lease:t,record:i,capsule:d,nextActions:[`workspai change authorize --change ${e.changeId} --effects filesystem,command --json`]})}async function ca(e){let{lease:t,record:a$1}=await R(e.workspacePath,e.changeId);if(await de(e.workspacePath,t),a$1.transaction.state!=="evidence-ready")throw new Error(`Plan attachment requires evidence-ready state, observed ${a$1.transaction.state}.`);let r=e.role.trim().toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/.test(r))throw new Error(`Invalid proof-carrying plan role: ${e.role}`);if(!e.schemaVersion.trim())throw new Error("Plan schema version is required.");let n=e.contractPath.replace(/\\/g,"/");if(!n.startsWith("contracts/")||n.split("/").some(l=>l===".."||l==="."))throw new Error(`Plan contract path must resolve inside the published contract root: ${e.contractPath}`);if(!e.payload||typeof e.payload!="object"||e.payload.schemaVersion!==e.schemaVersion)throw new Error("Plan payload schema version does not match its PCC reference.");a(e.payload,n,`${r} plan`);let i=c(e.payload),d=`${E(e.changeId).directory}/plans/${r}-${i}.json`;await h$1(e.workspacePath,d,e.payload);let f=await k(e.workspacePath,a$1,e.changeId,v("plan-attached",{summary:`Attach ${r} execution plan.`,references:[x({role:r,artifact:d,schemaVersion:e.schemaVersion,value:i})]},e.actorKind??"cli",e.actorId??"workspai-plan"));return await S(e.workspacePath,t,f),{changeId:e.changeId,state:f.transaction.state,artifact:d,digest:i}}async function da(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId);if(await de(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)),n=await S(e.workspacePath,t,r);return V({operation:"authorize",lease:t,record:r,capsule:n,nextActions:[`workspai change effect record --change ${e.changeId} --file <effect-receipt.json> --json`,`workspai change verify --change ${e.changeId} --json`]})}async function la(e){let{lease:t,record:a}=await R(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)),n=await S(e.workspacePath,t,r);return V({operation:"resume",lease:t,record:r,capsule:n,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 fa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=new Set(e.receipt.artifacts.map(f=>C(f.artifact))),n=(e.receipt.deletedArtifacts??[]).map(f=>C(f.artifact));if(new Set(n).size!==n.length)throw new Error("Effect receipt contains duplicate deleted-artifact identities.");if(n.some(f=>r.has(f)))throw new Error("An effect artifact cannot be both present and deleted in one receipt.");if(n.length>0&&e.receipt.status!=="succeeded")throw new Error("Only a succeeded effect may carry deleted-artifact tombstones.");for(let f of e.receipt.artifacts)if(!await ce(e.workspacePath,f))throw new Error(`Effect artifact is missing or corrupt: ${f.artifact}`);for(let f of e.receipt.deletedArtifacts??[])if(!await Ye(e.workspacePath,f))throw new Error(`Deleted effect artifact is present, outside the governed scope, or has an invalid tombstone: ${f.artifact}`);let i=await k(e.workspacePath,a,e.changeId,v("effect-recorded",{summary:e.receipt.summary,effect:e.receipt},e.actorKind??"agent",e.actorId??"workspai-agent")),d=await S(e.workspacePath,t,i);return V({operation:"effect-record",lease:t,record:i,capsule:d,nextActions:i.transaction.state==="blocked"?[`workspai change status --change ${e.changeId} --json`]:[`workspai change verify --change ${e.changeId} --json`]})}async function ga(e){let t=P.resolve(e.workspacePath),{lease:a,record:r}=await R(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 n=await J(t),i=E(e.changeId),[d,f]=await Promise.all([A(t,i.actualOverlay),A(t,i.surprises)]),l=r.transaction.verifications.some(c=>c.criterionId==="workspace-verify"&&c.status==="passed");if(!d||!f||!l)throw new Error("Domain verification can be admitted only after change verify re-observes the Graph and records a passing Workspace Verify receipt.");let s=Y(n),o=U(r.transaction,oe);if(e.receipt.target.modelHash!==s.modelHash||e.receipt.target.graphHash!==s.graphHash||e.receipt.target.effectHeadDigest!==o)throw new Error("Verification receipt does not target the current Model, Graph, and effect head.");for(let c of e.receipt.artifacts)if(!await ce(t,c))throw new Error(`Verification artifact is missing or corrupt: ${c.artifact}`);let h=e.actorKind??"ci",w=e.actorId??"workspai-verifier",u=r;if(u.transaction.state==="blocked"){if(!u.transaction.blockers.every(g=>g.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"},h,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},h,w)),u.transaction.state==="verifying"&&u.transaction.requiredCriteria.every(g=>u.transaction.verifications.filter(j=>j.criterionId===g).at(-1)?.status==="passed")&&(u=await k(t,u,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},h,w)));let I=await S(t,a,u);return V({operation:"verification-record",lease:a,record:u,capsule:I,nextActions:u.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}function F(e,t,a,r="verification"){return x({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 C(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Et(e){if(e.scope.kind==="workspace")return e.overlay;let t=new Set(e.scope.projects),a=c=>!!(c.projectId&&t.has(c.projectId)),r={added:e.overlay.entities.added.filter(a),removed:e.overlay.entities.removed.filter(a),changed:e.overlay.entities.changed.filter(c=>a(c.after??c.before??{}))},n=c=>e.scopedEntityIds.has(c.from)||e.scopedEntityIds.has(c.to),i={added:e.overlay.relations.added.filter(n),removed:e.overlay.relations.removed.filter(n),changed:e.overlay.relations.changed.filter(c=>{let g=c.after??c.before;return !!(g&&n(g))})},d=new Set([...r.added.flatMap(c=>c.proofIds),...r.removed.flatMap(c=>c.proofIds),...r.changed.flatMap(c=>[...c.before?.proofIds??[],...c.after?.proofIds??[]]),...i.added.flatMap(c=>c.proofIds),...i.removed.flatMap(c=>c.proofIds),...i.changed.flatMap(c=>[...c.before?.proofIds??[],...c.after?.proofIds??[]])]),f=c=>{let g=C(c);return e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(D=>g===D||g.startsWith(`${D}/`))},l=c=>d.has(c.id)||f(c.artifact),s={added:e.overlay.proofs.added.filter(l),removed:e.overlay.proofs.removed.filter(l),changed:e.overlay.proofs.changed.filter(c=>{let g=c.after??c.before;return !!(g&&l(g))})},o=e.overlay.impactedEntityIds.filter(c=>e.scopedEntityIds.has(c)),h=e.overlay.changedArtifacts.filter(f),w=r.removed.length+i.removed.length+s.removed.length,u=w+r.added.length+r.changed.length+i.added.length+i.changed.length+s.added.length+s.changed.length,I=u===0?"none":w>0||o.length>=10?"high":o.length>=5||u>=5?"medium":"low";return {...e.overlay,entities:r,relations:i,proofs:s,impactedEntityIds:o,changedArtifacts:h,summary:{entityAdds:r.added.length,entityRemovals:r.removed.length,entityChanges:r.changed.length,relationAdds:i.added.length,relationRemovals:i.removed.length,relationChanges:i.changed.length,proofAdds:s.added.length,proofRemovals:s.removed.length,proofChanges:s.changed.length,impactedEntities:o.length,changedArtifacts:h.length,risk:I}}}function Le(e){let t=P.normalize(P.resolve(e));return process.platform==="win32"?t.toLowerCase():t}async function Dt(e){let t=new Set(e.receiptedArtifacts.map(C)),a=new Set;for(let n of t){let i=await d(e.workspacePath,n);i&&a.add(Le(i));}let r=[];for(let n of e.changedArtifacts){let i=C(n);if(t.has(i))continue;let d$1=await d(e.workspacePath,i);d$1&&a.has(Le(d$1))||r.push(n);}return r}function Rt(e){let t=C(e.artifact);return e.receiptedArtifacts.has(t)||e.scope.kind==="workspace"||e.projectPrefixes.includes(".")?true:e.projectPrefixes.some(a=>t===a||t.startsWith(`${a}/`))}async function $t(e){let t=C(e.artifact),a=f=>{let l=f.proofs.filter(s=>C(s.artifact)===t);return l.length===0?[]:l.some(s=>!s.contentHash)?null:[...new Set(l.map(s=>s.contentHash))].sort()},r=a(e.baseline),n=a(e.head),i=await Fe(e.workspacePath,t),d=e.baseline.pccArtifactContentHashes?.[t];return d?i===null||i!==d:r&&r.length>0?i===null||!r.includes(i):r&&r.length===0?i!==null||!!n?.length:r===null||n===null?true:c(r)!==c(n)}async function ha(e){let t=P.resolve(e.workspacePath),{lease:a,record:r}=await R(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 n=await J(t),i=await A(t,a.privateMaterialization.artifact);if(!i||c(i)!==a.privateMaterialization.digest.value)throw new Error(`The hash-bound baseline materialization is missing or corrupt for ${e.changeId}.`);let d=new Date().toISOString(),f$1=n.model.projects.filter(y=>a.scope.projects.includes(y.name)).map(y=>C(y.path).replace(/\/$/u,"")).filter(Boolean),l=Et({overlay:a$1(i,n.graph,new Date(d)),scope:a.scope,projectPrefixes:f$1,scopedEntityIds:new Set([...i.entities,...n.graph.entities].filter(y=>y.projectId&&a.scope.projects.includes(y.projectId)).map(y=>y.id))}),s=E(e.changeId);await h$1(t,s.actualOverlay,l);let o=F(s.actualOverlay,l.schemaVersion,l,"actual-architecture-overlay"),h=await A(t,s.prediction),w=h?F(s.prediction,h.schemaVersion,h,"noncanonical-prediction"):null,u=bt({changeId:e.changeId,generatedAt:d,prediction:h,predictionReference:w,actual:l,actualReference:o});await h$1(t,s.surprises,u);let I=F(s.surprises,u.schemaVersion,u,"architecture-surprises"),c$2=r,g$1=e.actorKind??"cli",D=e.actorId??"workspai-change-verify";if(se(l)&&c$2.transaction.effects.length===0){c$2=await k(t,c$2,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."}},g$1,D));let y=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:y,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Record missing effect receipt" --json`]})}let j=c$2.transaction.effects.filter(y=>y.status==="succeeded").flatMap(y=>[...y.artifacts.map(H=>H.artifact),...(y.deletedArtifacts??[]).map(H=>H.artifact)]),Xe=new Set(j.map(C)),Qe=(await Promise.all(l.changedArtifacts.map(async y=>({artifact:y,contentChanged:await $t({workspacePath:t,artifact:y,baseline:i,head:n.graph})})))).filter(({artifact:y,contentChanged:H})=>H&&Rt({artifact:y,scope:a.scope,projectPrefixes:f$1,receiptedArtifacts:Xe})).map(({artifact:y})=>y),ge=await Dt({workspacePath:t,changedArtifacts:Qe,receiptedArtifacts:j});if(ge.length>0){c$2=await k(t,c$2,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: ${ge.slice(0,20).join(", ")}`}},g$1,D));let y=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:y,nextActions:[`workspai change resume --change ${e.changeId} --to authorized --reason "Cover observed artifacts" --json`]})}c$2=await k(t,c$2,e.changeId,v("verification-started",{summary:"Begin independent post-effect verification."},g$1,D));let Ze=await f({workspacePath:t}),et=await g(Ze,t),he=P.relative(t,et).split(P.sep).join("/"),X=await A(t,he);if(!X)throw new Error(`Workspace Verify evidence was not persisted at ${he}.`);await h$1(t,s.workspaceVerification,X);let M=await A(t,s.workspaceVerification);if(!M)throw new Error(`Change-scoped Workspace Verify evidence was not persisted at ${s.workspaceVerification}.`);let K=h$2(X,{strict:e.strict===true}),pe=Y(n),ue={id:`verify-workspace-${c({generatedAt:d,verify:M,gate:K}).slice(0,16)}`,criterionId:"workspace-verify",status:K.passed?"passed":"failed",summary:K.passed?`Workspace Verify passed in ${K.mode} mode.`:`Workspace Verify blocked in ${K.mode} mode: ${K.reasons.join("; ")}`,target:{modelHash:pe.modelHash,graphHash:pe.graphHash,effectHeadDigest:U(c$2.transaction,oe)},artifacts:[F(s.workspaceVerification,M.schemaVersion,M),o,I],observedAt:d};if(c$2=await k(t,c$2,e.changeId,v("verification-recorded",{summary:ue.summary,verification:ue},g$1,D)),c$2.transaction.state==="verifying"){let y=c$2.transaction.requiredCriteria.filter(H=>c$2.transaction.verifications.filter(at=>at.criterionId===H).at(-1)?.status!=="passed");y.length>0?c$2=await k(t,c$2,e.changeId,v("blocked",{summary:"Required outcome verification is incomplete.",blocker:{code:"change.verification.criteria_missing",actionable:true,details:`Missing passing receipts: ${y.join(", ")}`}},g$1,D)):c$2=await k(t,c$2,e.changeId,v("committed",{summary:"Seal the independently verified proof-carrying change."},g$1,D));}let tt=await S(t,a,c$2);return V({operation:"verify",lease:a,record:c$2,capsule:tt,nextActions:c$2.transaction.state==="committed"?[`workspai change capsule validate --change ${e.changeId} --json`]:[`workspai change status --change ${e.changeId} --json`]})}async function pa(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await le({workspacePath:e.workspacePath,lease:t,record:a});return V({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 ua(e){let t=P.resolve(e.workspacePath),a$1=await b$1(t,".workspai/changes","directory"),n=(a$1?await T.readdir(a$1,{withFileTypes:true}):[]).filter(l=>l.isDirectory()&&/^change-[a-z0-9][a-z0-9-]{7,95}$/.test(l.name)).map(l=>l.name).sort(),i=[],d=null;for(let l of n)try{let{lease:s,record:o}=await R(t,l);d??=s.workspace.name;let h=await le({workspacePath:t,lease:s,record:o}),w=await fe({workspacePath:t,changeId:l}),u=o.transaction.blockers.map(c=>c.details??c.code),I=h.status==="blocked"?h.assurances.filter(c=>c.status==="failed").map(c=>`${c.id}: ${c.summary}`):[];i.push({changeId:l,goalId:s.goalId,state:o.transaction.state,status:h.status,createdAt:o.transaction.createdAt,updatedAt:o.transaction.updatedAt,scope:s.scope,assurance:{passed:h.assurances.filter(c=>c.status==="passed").length,total:h.assurances.length},blockers:[...new Set([...u,...I])],capsuleArtifact:E(l).capsule,valid:w.valid,errors:w.errors});}catch(s){i.push({changeId:l,goalId:null,state:null,status:"invalid",createdAt:null,updatedAt:null,scope:null,assurance:{passed:0,total:5},blockers:[],capsuleArtifact:E(l).capsule,valid:false,errors:[s instanceof Error?s.message:String(s)]});}i.sort((l,s)=>(s.updatedAt??"").localeCompare(l.updatedAt??"")||l.changeId.localeCompare(s.changeId));let f={schemaVersion:m,generatedAt:new Date().toISOString(),workspace:{name:d??await wt(t)},changes:i,summary:{total:i.length,open:i.filter(l=>l.status==="open"||l.status==="verified").length,blocked:i.filter(l=>l.status==="blocked").length,sealed:i.filter(l=>l.status==="sealed").length,aborted:i.filter(l=>l.status==="aborted").length,invalid:i.filter(l=>!l.valid).length}};return a(f,"contracts/workspace-intelligence/proof-carrying-change-list.v1.json","Proof-Carrying Change list"),f}async function ma(e){let{lease:t,record:a}=await R(e.workspacePath,e.changeId),r=await k(e.workspacePath,a,e.changeId,v("aborted",{summary:e.reason,reason:e.reason},"human",e.actorId)),n=await S(e.workspacePath,t,r);return V({operation:"abort",lease:t,record:r,capsule:n,nextActions:[]})}async function fe(e){let t=E(e.changeId),a$1=await A(e.workspacePath,t.capsule);if(!a$1)throw new Error(`Proof-carrying change capsule not found: ${e.changeId}`);let r=[];a$1.schemaVersion!==k$1&&r.push(`Unsupported capsule schema: ${a$1.schemaVersion}`),a$1.changeId!==e.changeId&&r.push("Capsule change binding does not match."),c(At(a$1))!==a$1.integrity.capsuleDigest&&r.push("Capsule integrity digest does not match its canonical content.");let{lease:n$1,record:i}=await R(e.workspacePath,e.changeId),d=i.transaction.evidence.find(s=>s.role==="architecture-lease");(!d||d.digest.value!==c(n$1))&&r.push("Architecture lease does not match the decision-ledger evidence binding."),(n$1.goalId!==a$1.goalId||n$1.generation!==c({modelHash:n$1.baseline.model.digest.value,graphHash:n$1.baseline.graph.digest.value,inputHash:n$1.baseline.graph.inputHash}))&&r.push("Architecture lease identity or generation binding is invalid."),i.transaction.eventHeadDigest!==a$1.decision.eventHeadDigest&&r.push("Capsule does not bind the current decision event head."),c(i.transaction)!==a$1.decision.transaction.digest.value&&r.push("Decision transaction projection digest does not match the capsule.");let f=await A(e.workspacePath,n$1.privateMaterialization.artifact);(!f||c(f)!==n$1.privateMaterialization.digest.value)&&r.push("Hash-bound baseline materialization is missing or corrupt.");for(let s of [a$1.intent,a$1.decision.transaction,a$1.prediction,a$1.actualOverlay,a$1.surpriseReport,...a$1.effects,...a$1.verification].filter(o=>!!o))await ce(e.workspacePath,s)||r.push(`Referenced artifact is missing or corrupt: ${s.artifact}`);for(let s of a$1.deletedArtifacts??[])await Ye(e.workspacePath,s)||r.push(`Deleted artifact tombstone is invalid or the artifact exists again: ${s.artifact}`);let l={schemaVersion:n,changeId:e.changeId,validatedAt:new Date().toISOString(),valid:r.length===0,errors:r,capsule:a$1};return a(l,"contracts/workspace-intelligence/proof-carrying-change-capsule-validation.v1.json","Proof-Carrying Change capsule validation"),l}async function ya(e){let t=await fe(e);if(!t.valid)throw new Error(`Cannot export an invalid capsule: ${t.errors.join("; ")}`);let a$1=P.resolve(e.workspacePath),r=P.resolve(a$1,e.outputPath),n=P.relative(a$1,r);if(n===".."||n.startsWith(`..${P.sep}`)||P.isAbsolute(n))throw new Error("Capsule export path must remain inside the workspace.");let i=n.split(P.sep).join("/"),d=await h$1(a$1,i,t.capsule),f={schemaVersion:o,changeId:e.changeId,outputPath:d,validation:t};return a(f,"contracts/workspace-intelligence/proof-carrying-change-capsule-export.v1.json","Proof-Carrying Change capsule export"),f}function wa(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"]),n=new Set(["high","medium","low"]);for(let d of t.operations)if(!d||!a.has(d.operation)||!r.has(d.targetKind)||typeof d.targetId!="string"||d.targetId.trim().length===0||typeof d.rationale!="string"||!n.has(d.confidence))throw new Error("Prediction contains an invalid operation.");let i=t.predictedRisk;if(!i||!["none","low","medium","high"].includes(i))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(d=>typeof d=="string"),predictedRisk:i}}function va(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:vt({artifact:r.artifact,observedAt:r.observedAt??a.observedAt}))}:{}}}function ka(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 Ca(e,t){return e.decision.eventHeadDigest===t.eventHeadDigest&&e.decision.transaction.digest.value===c(t)}async function Ia(e){let t=await fe({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 R(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 n=[...r.transaction.verifications].reverse().find(i=>i.status==="passed");if(!n)throw new Error(`Proof-carrying change ${e.changeId} has no passing verification receipt.`);return {modelHash:n.target.modelHash,graphHash:n.target.graphHash}}
4
4
  export{Be as a,vt as b,sa as c,oa as d,ca as e,da as f,la as g,fa as h,ga as i,Dt as j,ha as k,pa as l,ua as m,ma as n,fe as o,ya as p,wa as q,va as r,ka as s,Ca as t,Ia as u};
@@ -1 +1 @@
1
- import {c}from'./chunk-DT3LRKZQ.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-36VNERGC.js';import {f as f$2}from'./chunk-ZKYH44ER.js';import {a as a$1}from'./chunk-FS3WLRQ4.js';import {c as c$3}from'./chunk-ZI54C2AO.js';import {b}from'./chunk-OA2YJN22.js';import {b as b$1}from'./chunk-NFWUAEVQ.js';import {f,i as i$1}from'./chunk-BLEIUQL6.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var be=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,we=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,ke=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,ve=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function ye(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(be.test(t))throw new Error("Goal intent contains unsupported control characters.");if(we.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(ke.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Pe(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function je(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=ye(e),n=ve.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Pe(r),d=je(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Ge="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Ce(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ae(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Re(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Se(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function Ee(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function Ie(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Ce(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return Ee(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Te(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function xe(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:!e.scope?.trim()});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ae(r),s=await Re({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await Ie({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Se(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=xe(await Te(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Ge,"Goal plan result"),P}export{et as a};
1
+ import {c}from'./chunk-UE7ART6X.js';import {j,i,d as d$1,f as f$1,c as c$2,e,h}from'./chunk-QBKOPXKC.js';import {f as f$2}from'./chunk-ZKYH44ER.js';import {a as a$1}from'./chunk-25V5XMWB.js';import {c as c$3}from'./chunk-ZI54C2AO.js';import {b}from'./chunk-OA2YJN22.js';import {b as b$1}from'./chunk-NRIMJMTF.js';import {f,i as i$1}from'./chunk-BLEIUQL6.js';import {a}from'./chunk-AFIFZTOY.js';import {d,c as c$1}from'./chunk-EWZZUQBR.js';import {q,p}from'./chunk-ODK4LCEL.js';import C from'path';import _ from'fs-extra';var be=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/,we=/(?:^|\s)(?:\/(?:home|Users|private|var|tmp|mnt|opt|srv|root|workspace|workspaces|data|Volumes|etc|usr|run|dev|proc|sys)\/[^\s]+|[A-Za-z]:[\\/][^\s]+|\\\\[^\\\s]+\\[^\s]+)/,ke=/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:github_pat_|gh[pousr]_|glpat-|npm_|xox[baprs]-|sk-(?:proj-)?)[A-Za-z0-9_-]{12,}|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[A-Za-z0-9_-]{20,}|\bBearer\s+[A-Za-z0-9._~+/-]{16,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/]+:[^\s@/]+@|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^\s]{6,})/i,ve=[{category:"test-coverage",patterns:[/\b(?:test\s+)?coverage\b/i,/\bcoverage\s+(?:to|above|at least)\b/i]},{category:"dependency-security",patterns:[/\b(?:dependency|dependencies|package|packages)\b.*\b(?:security|vulnerab|audit)\b/i,/\b(?:security|vulnerab|audit)\b.*\b(?:dependency|dependencies|package|packages)\b/i]},{category:"release-readiness",patterns:[/\brelease[ -]readiness\b/i,/\bready (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare (?:this |the )?(?:workspace|project) for release\b/i,/\bprepare\b[^\n]{0,80}\bfor release\b/i]},{category:"defect-repair",patterns:[/\b(?:fix|repair|resolve|debug)\b.*\b(?:bug|error|failure|issue|regression)\b/i]},{category:"performance",patterns:[/\b(?:performance|latency|throughput|cpu|optimi[sz]e|faster|slower)\b/i,/\b(?:memory\s+(?:allocation|consumption|footprint|leak|pressure|usage)|out[ -]of[ -]memory|heap|ram)\b/i]},{category:"refactor",patterns:[/\b(?:refactor|restructure|decouple|extract|simplify|cleanup|clean up)\b/i]},{category:"documentation",patterns:[/\b(?:document|documentation|readme|guide|tutorial|docs)\b/i]},{category:"feature-change",patterns:[/\b(?:add|build|create|enforce|enhance|harden|implement|improve|introduce|support)\b/i]},{category:"system-understanding",patterns:[/\b(?:understand|explain|map|find|where|how|architecture|analy[sz]e|search)\b/i]}];function ye(e){if(typeof e!="string")throw new Error("Goal intent must be text.");let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Goal intent cannot be empty.");if(t.length>2e3)throw new Error("Goal intent exceeds the 2000 character safety limit.");if(be.test(t))throw new Error("Goal intent contains unsupported control characters.");if(we.test(t))throw new Error("Goal intent contains a machine-local absolute path. Use a workspace-relative path or project scope.");if(ke.test(t))throw new Error("Goal intent appears to contain secret material and was not persisted.");return t}function Pe(e){let t=e.match(/\b(?:coverage\D{0,24})?((?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?))\s*(?:%|percent(?:age)?(?:\s+points?)?)/i);if(!t||!/coverage/i.test(e))return null;let r=Number(t[1]);return Number.isFinite(r)&&r>=0&&r<=100?r:null}var re=[{runtime:"cpp",patterns:[/\bc\+\+/i,/\bcpp\b/i]},{runtime:"dotnet",patterns:[/\.net\b/i,/\bdotnet\b/i,/\bc#/i,/\bcsharp\b/i]},{runtime:"node",patterns:[/\bnode(?:\.js)?\b/i,/\btypescript\b/i,/\bjavascript\b/i,/\b(?:js|ts)\b/i]},{runtime:"python",patterns:[/\bpython\b/i,/\bpytest\b/i]},{runtime:"go",patterns:[/\bgolang\b/i,/\bgo(?:\s+(?:test|coverage|tests))\b/i]},{runtime:"java",patterns:[/\bjava\b/i,/\bjunit\b/i,/\bjacoco\b/i]},{runtime:"rust",patterns:[/\brust\b/i,/\bcargo\b/i]},{runtime:"php",patterns:[/\bphp\b/i,/\bphpunit\b/i]},{runtime:"ruby",patterns:[/\bruby\b/i,/\brspec\b/i]},{runtime:"kotlin",patterns:[/\bkotlin\b/i]},{runtime:"scala",patterns:[/\bscala\b/i]},{runtime:"clojure",patterns:[/\bclojure\b/i]},{runtime:"elixir",patterns:[/\belixir\b/i]},{runtime:"deno",patterns:[/\bdeno\b/i]},{runtime:"bun",patterns:[/\bbun\b/i]},{runtime:"c",patterns:[/\bc(?:\s+(?:test|coverage|tests|code))\b/i]}];function je(e){return re.filter(t=>t.patterns.some(r=>r.test(e))).map(t=>t.runtime)}function K(e,t={}){let r=ye(e),n=ve.filter(u=>u.patterns.some(j=>j.test(r))).map(u=>u.category),a=n.some(u=>u!=="feature-change")?n.filter(u=>u!=="feature-change"):n,s=a[0]??"feature-change",l=Pe(r),d=je(r),p=d.length===0&&t.selectedCoverageRuntime?[t.selectedCoverageRuntime]:d,m=[...new Set((t.availableCoverageRuntimes??[]).filter(u=>re.some(j=>j.runtime===u)))].sort(),b=[];return a.length>1&&a[0]!=="test-coverage"&&b.push(`The intent also contains signals for: ${a.slice(1).join(", ")}.`),s==="test-coverage"&&l===null&&b.push("A numeric test coverage target is required for machine verification."),s==="test-coverage"&&p.length>1&&b.push(`The Goal names multiple coverage runtimes: ${p.join(", ")}. Select one runtime per Goal.`),s==="test-coverage"&&p.length===0&&m.length>1&&b.push(`Coverage scope is ambiguous across detected runtimes: ${m.join(", ")}. Name one runtime or language in the Goal.`),s==="test-coverage"&&p.length===1&&m.length>0&&!m.includes(p[0])&&b.push(`The requested ${p[0]} coverage runtime is not present in the selected scope. Detected runtimes: ${m.join(", ")}.`),{original:r,normalized:r.toLocaleLowerCase("en-US"),statement:r.replace(/[.!?]+$/,""),category:s,confidence:a.length===1?"high":a.length>1?"medium":"low",ambiguities:b,...l===null?{}:{requestedTarget:{metric:"test-coverage-percent",operator:"at-least",value:l,...p.length===1?{runtime:p[0]}:{}}}}}function oe(e){let t={"test-coverage":["test suite coverage configuration instrumentation","CI tests LCOV Cobertura JaCoCo LLVM coverage"],"dependency-security":["dependency manifest lockfile security audit vulnerability"],"release-readiness":["release pipeline readiness gates build test deploy"],"defect-repair":["failure error test implementation call path"],"feature-change":["API implementation module dependency tests"],refactor:["module dependency ownership implementation tests"],performance:["performance benchmark latency throughput runtime"],documentation:["documentation README guide architecture decision"],"system-understanding":["architecture service API dependency ownership"]};return [...new Set([e.statement,...t[e.category]])].slice(0,3)}var ae="contracts/workspace-intelligence/goal-pack.v1.json",se="contracts/workspace-intelligence/goal-agent-handoff.v1.json",Ge="contracts/workspace-intelligence/goal-plan-result.v1.json",pe="contracts/workspace-intelligence/goal-index.v1.json",ue=new Set(["node","bun","deno","python","go","java","dotnet","rust","php","ruby","elixir","clojure","scala","kotlin","c","cpp"]);function Ce(e,t){let r=e.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)??[],n=new Set(t.map(m=>m.toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"")).filter(Boolean)),a=[];for(let m=0;m<r.length;){let b=0;for(let u=Math.min(4,r.length-m);u>=1;u-=1){let j=r.slice(m,m+u).join("").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/g,"");if(n.has(j)){b=u;break}}if(b>0){m+=b;continue}a.push(r[m]),m+=1;}let s=a.findIndex((m,b)=>{let u=m.toLocaleLowerCase("en-US"),j=a[b+1]?.toLocaleLowerCase("en-US");return u==="without"&&["breaking","changing","modifying","removing"].includes(j??"")||u==="while"&&["keeping","maintaining","preserving"].includes(j??"")}),l=s>=2?a.slice(0,s):a,d=l.length>=2?l.join(" "):e;if(s<2)return [d];let p=a.slice(s).filter(m=>!["without","while","breaking","changing","modifying","removing","keeping","maintaining","preserving"].includes(m.toLocaleLowerCase("en-US")));return p.length>0?[d,p.join(" ")]:[d]}function ie(e){return e.split(C.sep).join("/")}function V(e,t){return C.resolve(t.absolutePath??C.join(e,t.path))}function ce(e){let t=e.requested.trim().replace(/^project:/,"");if(!t)throw new Error("Project goal scope must name a project.");let r=C.isAbsolute(t)?C.resolve(t):null,n=e.model.projects.filter(a=>a.name===t||ie(a.path)===ie(t)||r!==null&&V(e.workspacePath,a)===r);if(n.length!==1)throw new Error(n.length===0?`Project goal scope was not found in the canonical model: ${t}`:`Project goal scope is ambiguous in the canonical model: ${t}`);return n[0]}async function Ae(e){let t=await a$1(e);if(t.status==="miss")throw new Error(`Canonical model and live graph evidence are required (${t.reason}). Run \`workspai workspace intelligence run --for-agent generic --strict --json\` or retry with --refresh.`);let{model:r,graph:n}=t;return a(r,"contracts/workspace-intelligence/workspace-model.v1.json","Goal source model"),a(n,"contracts/workspace-intelligence/workspace-knowledge-graph.v1.json","Goal source graph"),b$1(n,r),{model:r,graph:n}}function le(e){let t=e.scope.trim();if(t==="workspace")return {kind:"workspace",projects:e.model.projects.map(n=>n.name).sort(),selectionSource:e.selectionSource,resolution:"selected"};let r=t.startsWith("projects:")?"projects:":t.startsWith("project:")&&t.slice(8).includes(",")?"project:":null;if(r){let n=t.slice(r.length).split(",").map(l=>l.trim()).filter(Boolean);if(n.length<2)throw new Error("A project-set Goal scope must name at least two projects.");let a=n.map(l=>ce({workspacePath:e.workspacePath,model:e.model,requested:l})),s=[...new Set(a.map(l=>l.name))].sort();if(s.length!==n.length)throw new Error("A project-set Goal scope must not contain duplicate projects.");return {kind:"project-set",projects:s,selectionSource:e.selectionSource,resolution:"selected"}}if(t)return {kind:"project",projects:[ce({workspacePath:e.workspacePath,model:e.model,requested:t}).name],selectionSource:e.selectionSource,resolution:"selected"};throw new Error("Goal scope cannot be empty.")}async function Re(e){if(e.explicitScope?.trim())return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:e.explicitScope,selectionSource:"explicit"}),selectionRequired:false};if(e.invocationProjectPath){let t=C.resolve(e.invocationProjectPath),r=e.model.projects.filter(n=>V(e.workspacePath,n)===t);if(r.length!==1)throw new Error("The invocation project is not represented uniquely in the canonical workspace model. Refresh intelligence or pass --scope explicitly.");return {scope:{kind:"project",projects:[r[0].name],selectionSource:"invocation-project",resolution:"selected"},selectionRequired:false}}if(e.model.projects.length===1)return {scope:{kind:"project",projects:[e.model.projects[0].name],selectionSource:"single-project-workspace",resolution:"selected"},selectionRequired:false};if(e.selectScope){let t=await e.selectScope({workspaceName:e.model.workspace.name,projects:e.model.projects.map(n=>({name:n.name,runtime:n.runtime,runtimeCandidates:[...n.runtimeCandidates].sort(),framework:n.framework})).sort((n,a)=>n.name.localeCompare(a.name))}),r=t.kind==="workspace"?"workspace":t.projects.length===1?`project:${t.projects[0]}`:`projects:${t.projects.join(",")}`;return {scope:le({workspacePath:e.workspacePath,model:e.model,scope:r,selectionSource:"interactive"}),selectionRequired:false}}return {scope:{kind:"workspace",projects:e.model.projects.map(t=>t.name).sort(),selectionSource:"workspace",resolution:"selection-required"},selectionRequired:true}}function Se(e,t){if(t.kind==="workspace")return {entities:e.quality.entityCount,relationships:e.quality.relationCount,proofs:e.quality.proofCount,unresolved:e.quality.unknownCount,proofCoveragePercent:Number((e.quality.relationProofCoverageRatio*100).toFixed(2))};let r=new Set(t.projects),n=e.entities.filter(p=>p.projectId!==void 0&&r.has(p.projectId)),a=new Set(n.map(p=>p.id)),s=e.relations.filter(p=>a.has(p.from)||a.has(p.to)),l=new Set([...n.flatMap(p=>p.proofIds),...s.flatMap(p=>p.proofIds)]),d=s.filter(p=>p.proofIds.length>0).length;return {entities:n.length,relationships:s.length,proofs:l.size,unresolved:s.length-d,proofCoveragePercent:s.length===0?100:Number((d/s.length*100).toFixed(2))}}function Ee(e){let t=new Map;for(let n of e){let a=t.get(n.kind)??[];a.push(n),t.set(n.kind,a);}let r=[];for(let n=0;[...t.values()].some(a=>n<a.length);n+=1)for(let a of t.values()){let s=a[n];s&&r.push(s);}return r}async function Ie(e){let t=C.join(e.workspacePath,p.intelligenceRun),r=await _.readJson(t).catch(()=>null),a=(Array.isArray(r?.stages)?r.stages:[]).filter(o=>o.status==="blocked"||o.status==="failed").map(o=>String(o.id??"unknown")).sort(),s=r?.status,l={status:s==="passed"?"passed":s==="blocked"||s==="failed"?"blocked":"unknown",artifact:p.intelligenceRun,blockedStages:a},d={status:"not-applicable",runtime:null,runtimeChoices:[],runner:null,existingEvidence:[],prerequisites:[]};if(e.intent.category==="test-coverage"){let o=e.intent.requestedTarget?.runtime;if(e.intent.ambiguities.some(P=>P.startsWith("Coverage scope is ambiguous")||P.startsWith("The Goal names multiple coverage runtimes")||P.startsWith("The selected projects do not share a common canonical coverage runtime")||P.startsWith("The requested ")))d={status:"requires-setup",runtime:o??null,runtimeChoices:e.coverageRuntimeChoices,runner:null,existingEvidence:[],prerequisites:["Select exactly one detected runtime or language for this coverage Goal."]};else {let P=o?e.projects.filter(c=>c.runtimeCandidates.includes(o)):e.projects,i=await Promise.all(P.map(async c=>({project:c,capability:await c$3(V(e.workspacePath,c),o??(ue.has(c.runtime)?c.runtime:"unknown"))}))),h=i.map(c=>c.capability.status);d={status:h.includes("unsupported")?"unsupported":h.includes("requires-setup")?"requires-setup":"available",runtime:i.length===1?i[0].capability.runtime:[...new Set(i.map(c=>c.capability.runtime))].join(","),runtimeChoices:e.coverageRuntimeChoices,runner:i.length===1?i[0].capability.runner:[...new Set(i.flatMap(c=>c.capability.runner?[c.capability.runner]:[]))].join(",")||null,existingEvidence:i.flatMap(c=>c.capability.existingEvidence.map(A=>({project:c.project.name,...A}))).filter((c,A,w)=>w.findIndex(k=>k.project===c.project&&k.path===c.path&&k.sha256===c.sha256)===A).sort((c,A)=>c.project.localeCompare(A.project)||c.path.localeCompare(A.path)),prerequisites:[...new Set(i.flatMap(c=>c.capability.prerequisites))].sort()};}}let p$1=oe(e.intent),m=[...Ce(p$1[0],e.projects.map(o=>o.name)),...p$1.slice(1)].filter((o,y,P)=>P.indexOf(o)===y).slice(0,3),b=m.map((o,y)=>{let P=o.match(/[A-Za-z0-9][A-Za-z0-9+#.%_-]*/g)?.length??0,i=y===0&&P>=4?2:1,h=e.projects.map(w=>{let k=G=>f$2(e.graph,{query:o,projectId:w.name,...G?{kind:G}:{},limit:60,relationsPerEntity:0,minimumTermMatches:i}).entities,S=k(),de=[...new Set(e.graph.entities.filter(G=>G.projectId===w.name||G.projectId===void 0&&G.identity.scope==="workspace").map(G=>G.kind))].flatMap(G=>k(G).slice(0,8)),U=[...S,...de];return U.filter((G,me)=>U.findIndex(ge=>ge.id===G.id)===me)}),c=[],A=new Set;for(let w=0;h.some(k=>w<k.length);w+=1)for(let k of h){let S=k[w];!S||A.has(S.id)||(A.add(S.id),c.push(S));}return Ee(c)}),u={"test-coverage":["test-suite"],"dependency-security":["package","module"],"release-readiness":["pipeline","deployment","lifecycle-stage"],"defect-repair":["test-suite","lifecycle-stage"],"feature-change":["project","runtime-unit","api","package","module","test-suite"],refactor:["package","module","api","test-suite"],performance:["lifecycle-stage","test-suite","pipeline"],documentation:["document","decision"],"system-understanding":["project","service","api","package","protocol"]},j=new Set(e.projects.map(o=>o.name)),v=e.graph.entities.filter(o=>o.proofIds.length>0&&(!o.projectId||j.has(o.projectId))&&u[e.intent.category].includes(o.kind)).sort((o,y)=>u[e.intent.category].indexOf(o.kind)-u[e.intent.category].indexOf(y.kind)||o.label.localeCompare(y.label)),f=[],M=new Set,E=o=>{!o||f.length>=20||M.has(o.id)||(M.add(o.id),f.push(o));},I=(e.intent.statement.match(/[A-Za-z][A-Za-z0-9+#.-]{1,}/g)??[]).length>=2,g=I?b[0]??[]:[];for(let o of g.slice(0,12))E(o);if(!I)for(let o of v)E(o);for(let o=0;f.length<20&&b.slice(1).some(y=>o<y.length);o+=1)for(let y of b.slice(1))E(y[o]);if(I)for(let o of v)E(o);for(let o of g.slice(12))E(o);let T=f.map(o=>({entityId:o.id,kind:o.kind,label:o.label,proofIds:o.proofIds.slice(0,12)})),L=b[0]?.length??0;return {workspaceIntelligence:l,measurement:d,retrieval:{status:I&&L>=3?"grounded":T.length>0?"partial":"empty",strategy:"deterministic-category-v1",queries:m,anchors:T}}}async function Te(e$1){let t=C.join(e$1,f$1);if(!await _.pathExists(t))return {schemaVersion:e,generatedAt:new Date(0).toISOString(),activeGoalId:null,goals:[]};let r=await _.readJson(t);a(r,pe,"Goal index");try{i(r);}catch(n){let a=h(r);if(!(a!==null&&n instanceof Error&&n.message==="Goal index is inconsistent: activeGoalId must identify the only selected actionable lifecycle entry.")||!a)throw n;return a}return r}function xe(e$1,t,r){let n=e$1.goals.find(l=>l.id===t.id),a=t.state==="ready-to-plan",s={id:t.id,fingerprint:t.fingerprint,objective:t.intent.statement,category:t.intent.category,state:t.state,lifecycle:n?.lifecycle==="cancelled"?"cancelled":a?"active":"planned",scope:t.scope,createdAt:n?.createdAt??t.generatedAt,updatedAt:r,goalPack:t.artifacts.goalPack,agentHandoff:t.artifacts.agentHandoff,...n?.verifiedGoalId?{verifiedGoalId:n.verifiedGoalId}:{},...n?.repairTransactionId?{repairTransactionId:n.repairTransactionId}:{},...n?.repairTransactionIds?{repairTransactionIds:n.repairTransactionIds}:{},...n?.changeTransactionId?{changeTransactionId:n.changeTransactionId}:{},...n?.changeTransactionIds?{changeTransactionIds:n.changeTransactionIds}:{},...n?.verificationReceipt?{verificationReceipt:n.verificationReceipt}:{}};return {schemaVersion:e,generatedAt:r,activeGoalId:s.lifecycle==="active"?t.id:e$1.activeGoalId===t.id?null:e$1.activeGoalId,goals:[...e$1.goals.filter(l=>l.id!==t.id).map(l=>s.lifecycle==="active"&&l.lifecycle==="active"?{...l,lifecycle:"planned",updatedAt:r}:l),s].sort((l,d)=>l.id.localeCompare(d.id))}}async function et(e){let t=b({startPath:C.resolve(e.startPath),explicitWorkspacePath:e.workspacePath,strict:true,requireProjectMembership:!e.scope?.trim()});if(!t)throw new Error("No canonical Workspai workspace could be resolved.");let r=C.resolve(t.workspacePath);e.refresh&&await c({workspacePath:r,strict:false,agent:"generic"});let{model:n,graph:a$1}=await Ae(r),s=await Re({workspacePath:r,invocationProjectPath:t.projectPath,model:n,explicitScope:e.scope,selectScope:e.selectScope}),l=s.scope,d$2=n.projects.filter(i=>l.projects.includes(i.name));if(d$2.length===0)throw new Error("A Goal Pack requires at least one registered project in its selected scope.");let p$1=e.maxAttempts??5;if(!Number.isInteger(p$1)||p$1<1||p$1>25)throw new Error("--max-attempts must be an integer from 1 to 25.");let m=new Date().toISOString(),b$1=d(n),u=d$2.map(i=>({name:i.name,runtimes:[...new Set(i.runtimeCandidates.filter(h=>ue.has(h)))].sort()})),j$1=[...new Set(u.flatMap(i=>i.runtimes))].sort(),v=u.length<=1?j$1:u[0].runtimes.filter(i=>u.every(h=>h.runtimes.includes(i))),f$2=K(e.intent,{availableCoverageRuntimes:v,...e.runtime?{selectedCoverageRuntime:e.runtime}:v.length===1?{selectedCoverageRuntime:v[0]}:{}});if(e.runtime&&!v.includes(e.runtime)){let i=e.runtime,h=u.filter(c=>!c.runtimes.includes(i)).map(c=>c.name);throw new Error(d$2.length>1&&h.length>0?`--runtime ${e.runtime} is not canonical for every project in the selected Goal scope. Missing from: ${h.join(", ")}. Split the projects into runtime-compatible Goal scopes.`:`--runtime ${e.runtime} is not present in the canonical Workspace Model for the selected Goal scope. Available runtimes: ${v.join(", ")||"none"}.`)}if(e.runtime&&f$2.category!=="test-coverage")throw new Error("--runtime is valid only for a test-coverage Goal.");if(e.runtime&&f$2.requestedTarget?.runtime&&f$2.requestedTarget.runtime!==e.runtime)throw new Error(`--runtime ${e.runtime} conflicts with the ${f$2.requestedTarget.runtime} runtime named in the Goal intent.`);if(!s.selectionRequired&&f$2.category==="test-coverage"&&f$2.requestedTarget&&!f$2.requestedTarget.runtime&&v.length>1&&!e.runtime&&e.selectCoverageRuntime){let i=await e.selectCoverageRuntime({workspaceName:n.workspace.name,scope:l,projects:d$2.map(h=>({name:h.name,runtime:h.runtime,runtimeCandidates:[...h.runtimeCandidates].sort()})),runtimes:v});if(!v.includes(i))throw new Error("The selected coverage runtime is outside the canonical Goal scope.");f$2=K(e.intent,{availableCoverageRuntimes:v,selectedCoverageRuntime:i});}!s.selectionRequired&&f$2.category==="test-coverage"&&d$2.length>1&&v.length===0&&(f$2={...f$2,ambiguities:[`The selected projects do not share a common canonical coverage runtime: ${u.map(i=>`${i.name} (${i.runtimes.join(", ")||"none"})`).join("; ")}. Split them into runtime-compatible Goal scopes so every selected project is verified.`,...f$2.ambiguities]}),s.selectionRequired&&(f$2={...f$2,ambiguities:[`Goal scope is unresolved across ${l.projects.length} registered projects: ${l.projects.join(", ")}. Select one project, multiple projects, or the entire workspace.`,...f$2.ambiguities]});let M=await Ie({workspacePath:r,projects:d$2,graph:a$1,intent:f$2,coverageRuntimeChoices:v}),E={generatedAt:m,intent:f$2,workspaceName:n.workspace.name,scope:l,sourceBinding:{model:{artifact:p.model,schemaVersion:q.model,hashAlgorithm:"sha256",hashSemantics:"workspace-model-structural-v1",hash:b$1,generatedAt:n.generatedAt},graph:{artifact:p.knowledgeGraph,schemaVersion:q.knowledgeGraph,hashAlgorithm:"sha256",hashSemantics:"canonical-json-v1",hash:c$1(a$1),generatedAt:a$1.generatedAt,modelHash:a$1.source.hash,...a$1.source.inputs?.hash?{inputHash:a$1.source.inputs.hash}:{}}},preflight:M,baseline:{projectCount:d$2.length,runtimes:[...new Set(d$2.flatMap(i=>i.runtimeCandidates))].sort(),frameworks:[...new Set(d$2.map(i=>i.framework))].sort(),graph:Se(a$1,l)},maxAttempts:p$1,consumer:e.consumer??"generic"},I={digestCanonical:c$1},{goalPack:g,handoff:T}=j(E,I);a(g,ae,"Goal Pack"),a(T,se,"Goal agent handoff");let L=false,o=async()=>{let i=C.join(r,g.artifacts.goalPack),h=C.join(r,g.artifacts.agentHandoff),[c,A]=await Promise.all([_.pathExists(i),_.pathExists(h)]);if(c!==A)throw new Error(`Goal Pack instance is incomplete and cannot be resumed: ${g.id}`);if(!c)return;let[w,k]=await Promise.all([_.readJson(i),_.readJson(h)]);a(w,ae,"Persisted Goal Pack"),a(k,se,"Persisted goal agent handoff");let S=j({...E,generatedAt:w.generatedAt,sourceBinding:w.sourceBinding},I);if(w.id!==g.id||k.goalId!==g.id||c$1(w)!==c$1(S.goalPack)||c$1(k)!==c$1(S.handoff))throw new Error(`Goal Pack instance failed immutable integrity validation: ${g.id}`);g=w,T=k,L=true;};if(e.dryRun)await o();else {let i$2=`.workspai/goals/${g.id}/publication`;await f(r,i$2,async()=>{await o();let h=xe(await Te(r),g,new Date().toISOString());a(h,pe,"Goal index"),i(h),await i$1(r,d$1,L?[{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]:[{relativePath:g.artifacts.goalPack,payload:g},{relativePath:g.artifacts.agentHandoff,payload:T},{relativePath:d$1,payload:g},{relativePath:f$1,payload:h}]);});}let y=[g.artifacts.goalPack,g.artifacts.agentHandoff,d$1,f$1],P={schemaVersion:c$2,result:g.state==="needs-confirmation"?"needs-confirmation":g.state==="blocked"?"blocked":g.state==="needs-evidence"?"needs-evidence":"planned",resolution:{source:t.source,invocationScope:t.projectPath?"project":"workspace"},goalPack:g,agentHandoff:T,writtenArtifacts:e.dryRun?[]:L?[d$1,f$1]:y,dryRun:e.dryRun===true,resumed:L};return a(P,Ge,"Goal plan result"),P}export{et as a};
@@ -1,4 +1,4 @@
1
- import {m,a as a$1,l as l$1}from'./chunk-ZW4QV6SB.js';import {b as b$5,g as g$2}from'./chunk-GIFAGOMK.js';import {b as b$4,a}from'./chunk-D5LLTUTY.js';import {b as b$2,f as f$2,s as s$1,t as t$1,u,P as P$1,v,q as q$1,r as r$1,R,n,o,p as p$2,h as h$2,i,m as m$1,j,k,l,O,w,x,y,z as z$1,A,B as B$1,C,E,G,I,D as D$1,F,H,J as J$1,K,L,M,N,S,T,U,V,Y as Y$1,X as X$1,W,a as a$3,Q}from'./chunk-QYEQVNBF.js';import {b as b$1,c,d}from'./chunk-4KEZQLBU.js';import {b as b$3}from'./chunk-COICGD62.js';import {d as d$2}from'./chunk-G3ZC5W4U.js';import {b as b$7}from'./chunk-NFWUAEVQ.js';import {r,m as m$2,d as d$1}from'./chunk-O2CFT2A3.js';import {p as p$1}from'./chunk-LMOTDLJF.js';import {g}from'./chunk-BLEIUQL6.js';import {a as a$2,b as b$6}from'./chunk-VN2MKTQO.js';import {f as f$1,g as g$1,h}from'./chunk-VQZ5PI5J.js';import {q,p,t,s as s$2}from'./chunk-ODK4LCEL.js';import s from'path';import h$1 from'fs-extra';var pe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Jt="workspace-operational-skill.v1";function Yt(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ot(e){let t=Yt(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Jt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...pe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Xt=q.skillsIndex;function Tt(e){let t=[...e.skills].sort((i,c)=>i.skillId.localeCompare(c.skillId)),r=e.inputsHash??d$1({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath),decisions:e.decisions??[]}),n=e.decisions?[...e.decisions].sort((i,c)=>i.skillId.localeCompare(c.skillId)):void 0;return {schemaVersion:Xt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title})),...n?{selection:{generatedCount:n.filter(i=>i.status==="generated").length,suppressedCount:n.filter(i=>i.status==="suppressed").length,decisions:n}}:{}}}var _t=[p.agentIndex,b$1,d$2],B="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Qt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${p.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${p.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."],applicability:"api"},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${p.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${p.verify}\` for verdict and blocking reasons.`,`Read \`${t.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."],applicability:"workspace"},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Run a registered project-scoped test/build command when available; otherwise resolve the repository-authored validation command from cited manifests before promoting the migration.","Document rollback and verification signals."],applicability:"schema"},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Use registered test/build commands for affected projects; when none are registered, resolve repository-authored commands from cited manifests instead of inventing one.","Re-run `workspace verify` after evidence refresh."],applicability:"dependency"},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${t.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."],applicability:"contract"}];function z(e){return `npx workspai ${e}`.trim()}function Zt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",B,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",..._t.map(r=>`- \`${r}\``),"","## Why this skill exists here","",`Applicability: **${e.decision.confidence} confidence**.`,"",...e.decision.reasons.map(r=>`- ${r}`),...e.decision.signals.length>0?["","Evidence signals:","",...e.decision.signals.map(r=>`- \`${r}\``)]:[],"","## Project-aware execution boundary","",...e.projectEvidence,"",...e.retrievalCommands.length>0?["## Scoped retrieval commands","",...e.retrievalCommands.map(r=>`- \`${r}\``),""]:[],"## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
1
+ import {m,a as a$1,l as l$1}from'./chunk-3WQ5TYCO.js';import {b as b$5,g as g$2}from'./chunk-SCKEFXF5.js';import {b as b$4,a}from'./chunk-D5LLTUTY.js';import {b as b$2,f as f$2,s as s$1,t as t$1,u,P as P$1,v,q as q$1,r as r$1,R,n,o,p as p$2,h as h$2,i,m as m$1,j,k,l,O,w,x,y,z as z$1,A,B as B$1,C,E,G,I,D as D$1,F,H,J as J$1,K,L,M,N,S,T,U,V,Y as Y$1,X as X$1,W,a as a$3,Q}from'./chunk-QYEQVNBF.js';import {b as b$1,c,d}from'./chunk-NGZF4YJS.js';import {b as b$3}from'./chunk-COICGD62.js';import {d as d$2}from'./chunk-5EEXLM45.js';import {b as b$7}from'./chunk-NRIMJMTF.js';import {r,m as m$2,d as d$1}from'./chunk-FU6SQ2ND.js';import {p as p$1}from'./chunk-M6DVNC6X.js';import {g}from'./chunk-BLEIUQL6.js';import {a as a$2,b as b$6}from'./chunk-VN2MKTQO.js';import {f as f$1,g as g$1,h}from'./chunk-VQZ5PI5J.js';import {q,p,t,s as s$2}from'./chunk-ODK4LCEL.js';import s from'path';import h$1 from'fs-extra';var pe=["Scope","Evidence","Diagnosis","Fix Plan","Run","Verify","Assumptions"];var Jt="workspace-operational-skill.v1";function Yt(e){if(typeof e!="string")return null;let t=e.trim();return !t||t.includes("/")||t.includes("..")?null:t}function Ot(e){let t=Yt(e.skillId);if(!t)throw new Error(`Invalid skill id: ${e.skillId}`);return {schemaVersion:Jt,skillId:t,canonicalPath:W(t),title:e.title,triggers:[...e.triggers].sort((r,n)=>r.localeCompare(n)),requiredReports:[...e.requiredReports].sort((r,n)=>r.localeCompare(n)),scopedProjects:[...e.scopedProjects??[]].sort((r,n)=>r.localeCompare(n)),verificationCommands:[...e.verificationCommands],answerContractSections:[...pe],...e.promptStem?{promptStem:e.promptStem}:{},markdown:e.markdown}}var Xt=q.skillsIndex;function Tt(e){let t=[...e.skills].sort((i,c)=>i.skillId.localeCompare(c.skillId)),r=e.inputsHash??d$1({skillIds:t.map(i=>i.skillId),paths:t.map(i=>i.canonicalPath),decisions:e.decisions??[]}),n=e.decisions?[...e.decisions].sort((i,c)=>i.skillId.localeCompare(c.skillId)):void 0;return {schemaVersion:Xt,generatedAt:e.generatedAt,inputsHash:r,skills:t.map(i=>({skillId:i.skillId,path:i.canonicalPath,schemaVersion:i.schemaVersion,title:i.title})),...n?{selection:{generatedCount:n.filter(i=>i.status==="generated").length,suppressedCount:n.filter(i=>i.status==="suppressed").length,decisions:n}}:{}}}var _t=[p.agentIndex,b$1,d$2],B="<!-- WORKSPAI:GENERATED-OPERATIONAL-SKILL -->",Qt=[{skillId:"workspai-diagnose-api-failure",title:"Diagnose API failure",triggers:["api failure","500 error","integration test failed","service unreachable"],objective:"Investigate a failing API or service using Workspai evidence before editing application code.",steps:[`Read \`${p.agentIndex}\` and identify fail/warn reports for the scoped project.`,`Read \`${p.doctor}\`, \`doctor-project-last-run.json\`, and project-scoped run evidence if present.`,"If a fix was requested, read `artifact-remediation-plan-last-run.json` for cross-artifact next steps, then `doctor-remediation-plan-last-run.json` for Doctor-specific file edits.","Map the failure to workspace vs project scope; cite exit codes and blocker messages.","Propose the smallest safe fix (config, env, dependency) with explicit verification commands."],applicability:"api"},{skillId:"workspai-release-readiness",title:"Release readiness",triggers:["release","ship","production","readiness gate"],objective:"Assess whether this workspace is release-ready using governed Workspai gates.",steps:[`Read \`${p.readiness}\` and \`pipeline-last-run.json\`.`,`Read \`${p.verify}\` for verdict and blocking reasons.`,`Read \`${t.artifactRemediationPlan}\` when a Studio or agent repair path is needed.`,"List blocking gates first; never claim ready without cited report fields.","Provide one safe next command and a verification checklist."],applicability:"workspace"},{skillId:"workspai-safe-schema-migration",title:"Safe schema migration",triggers:["migration","schema change","database migration","db migrate"],objective:"Plan and verify a schema migration with blast-radius awareness.",steps:["Identify affected projects from workspace model and dependency graph.","Run or review impact/verify evidence for transitive dependents.","Run a registered project-scoped test/build command when available; otherwise resolve the repository-authored validation command from cited manifests before promoting the migration.","Document rollback and verification signals."],applicability:"schema"},{skillId:"workspai-dependency-upgrade",title:"Dependency upgrade",triggers:["upgrade dependency","bump package","security advisory","outdated deps"],objective:"Upgrade dependencies with graph-aware verification.",steps:["Scope the upgrade to the owning project from workspace model.","Check transitive dependents via workspace graph / impact reports.","Use registered test/build commands for affected projects; when none are registered, resolve repository-authored commands from cited manifests instead of inventing one.","Re-run `workspace verify` after evidence refresh."],applicability:"dependency"},{skillId:"workspai-rename-contract",title:"Rename contract safely",triggers:["rename contract","rename event","breaking api","contract change"],objective:"Rename or change a shared contract with consumer awareness.",steps:[`Read \`${t.workspaceContract}\` for publishes/consumes/owns edges.`,"List all consumer projects before proposing renames.","Update contract file and regenerate workspace model.","Verify contract gate and integration tests for consumers."],applicability:"contract"}];function z(e){return `npx workspai ${e}`.trim()}function Zt(e){let t=["---",`name: ${e.template.skillId}`,`description: ${e.template.objective}`,"---","",B,"",`# ${e.template.title}`,"",`> Workspace: **${e.workspaceName}** \xB7 Skill: \`${e.template.skillId}\``,"","## Objective","",e.template.objective,"","## Triggers","",...e.template.triggers.map(r=>`- ${r}`),"","## Required evidence (read first)","",..._t.map(r=>`- \`${r}\``),"","## Why this skill exists here","",`Applicability: **${e.decision.confidence} confidence**.`,"",...e.decision.reasons.map(r=>`- ${r}`),...e.decision.signals.length>0?["","Evidence signals:","",...e.decision.signals.map(r=>`- \`${r}\``)]:[],"","## Project-aware execution boundary","",...e.projectEvidence,"",...e.retrievalCommands.length>0?["## Scoped retrieval commands","",...e.retrievalCommands.map(r=>`- \`${r}\``),""]:[],"## Procedure","",...e.template.steps.map((r,n)=>`${n+1}. ${r}`),""];if(e.scopedProjects.length>0&&t.push("## Scoped projects","",...e.scopedProjects.map(r=>`- ${r}`),""),e.contractSummary&&t.push("## Contract context","",e.contractSummary,""),e.verificationCommands.length>0){t.push("## Verification commands (this workspace)","");for(let r of e.verificationCommands)t.push(`- \`${r}\``);t.push("");}return t.push("## Answer contract","","Return: Scope, Evidence, Diagnosis, Fix Plan, Run, Verify, Assumptions.","","## Refresh stale evidence","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""),t.join(`
2
2
  `)}function er(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tr(e){let t=new Map;for(let c of e.projects){let m=new Set([c.runtime,...c.runtimeCandidates??[]].map(er).filter(a=>a&&a!=="unknown"));for(let a of m){let k=t.get(a)??[];k.includes(c.name)||k.push(c.name),t.set(a,k);}}let r=[];for(let[c,m]of [...t.entries()].sort(([a],[k])=>a.localeCompare(k)))r.push({skillId:`workspai-${c}-runtime-validation`,title:`${c.toUpperCase()} runtime validation`,triggers:[`${c} build`,`${c} test`,`${c} runtime failure`],objective:`Validate ${c} changes against the detected runtime boundary, registered project commands, and canonical Workspai evidence.`,steps:["Read the scoped project lens and current fail/warn evidence before changing source.",`Use a registered ${c} command only when the project model identifies ${c} as the primary runtime; for a composite secondary boundary, inspect its manifest and Graph proofs instead of assuming the primary adapter covers it.`,"Run only the affected project validation first, then verify the workspace when the change crosses a contract boundary."],scopedProjects:[...m].sort(),applicability:"derived"});t.size>1&&r.push({skillId:"workspai-polyglot-change-validation",title:"Polyglot change validation",triggers:["cross-language change","polyglot change","binding change","multi-runtime validation"],objective:"Plan and verify a cross-runtime change without assuming that one runtime command proves the whole system.",steps:["Use the project topology and bounded Graph query to identify runtime and contract boundaries.","Validate each affected runtime with its registered project command.","Run workspace impact and canonical verification before declaring the change complete."],scopedProjects:Wt([...t.values()].flat()),applicability:"derived"});let n=e.projects.filter(c=>c.commands.supported.includes("test")).map(c=>c.name).sort();n.length>0&&r.push({skillId:"workspai-test-evidence-recovery",title:"Test evidence recovery",triggers:["test failure","coverage","regression","test evidence"],objective:"Repair a test or coverage blocker by proving changed behavior, not merely improving a metric.",steps:["Read the exact Analyze, Doctor, or Goal evidence that owns the test finding.","Inspect the behavior and relevant test boundary before proposing a source change.","Run the scoped test command, then the exact producer and canonical verification."],scopedProjects:n,applicability:"derived"});let i=e.projects.filter(c=>c.importantFiles.some(m=>/(?:^|\/)(?:Dockerfile|docker-compose|compose\.|Chart\.yaml|\.github\/workflows)/i.test(m))).map(c=>c.name).sort();return i.length>0&&r.push({skillId:"workspai-delivery-evidence",title:"Delivery evidence and CI recovery",triggers:["ci failure","workflow failure","container build","deployment evidence"],objective:"Diagnose delivery evidence with the owning project and CI/container artifacts before changing application source.",steps:["Identify whether the failing evidence is project-owned or workspace-owned.","Inspect the referenced workflow or delivery artifact and its bounded proof paths.","Validate the affected project first, then refresh the exact evidence producer and verify the workspace."],scopedProjects:i,applicability:"derived"}),r}function rr(e,t){if(!e?.safeCommands?.length)return [z("workspace verify --json"),z("doctor workspace --json")];let r=new Set(t);return e.safeCommands.filter(n=>n.scope==="workspace"||n.project&&r.has(n.project)).slice(0,8).map(n=>n.display)}function nr(e,t){if(!e?.projects?.length)return;let r=new Set(t),n=e.projects.filter(i=>r.has(i.slug)).filter(i=>(i.contracts?.owns?.length??0)>0||(i.contracts?.publishes?.length??0)>0||(i.contracts?.consumes?.length??0)>0||(i.contracts?.apis?.length??0)>0).slice(0,12).map(i=>{let c=i.contracts?.owns?.join(", ")||"none",m=i.contracts?.publishes?.join(", ")||"none",a=i.contracts?.consumes?.join(", ")||"none";return `- **${i.slug}**: owns \`${c}\`; publishes \`${m}\`; consumes \`${a}\``});return n.length>0?n.join(`
3
3
  `):void 0}var ar=/(?:^|\/)(?:package(?:-lock)?\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|pyproject\.toml|poetry\.lock|requirements[^/]*\.txt|Pipfile(?:\.lock)?|uv\.lock|Cargo\.toml|Cargo\.lock|go\.mod|go\.sum|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|Gemfile(?:\.lock)?|composer\.(?:json|lock)|mix\.exs|deps\.edn|project\.clj|[^/]+\.(?:csproj|fsproj|vbproj)|Directory\.Packages\.props)$/i,or=/(?:^|\/)(?:openapi|swagger|asyncapi)\.(?:json|ya?ml)$|(?:^|\/)(?:routes?|controllers?|endpoints?|proto)(?:\/|\.)/i,ir=/(?:^|\/)(?:migrations?|database|db|prisma)(?:\/|\.)|(?:^|\/)schema\.(?:sql|prisma)$/i;function sr(e){let t=e.attributes.artifact;return typeof t=="string"&&t.trim()?t.trim():null}function cr(e){let t=e.attributes.ports;return Array.isArray(t)&&t.length>0}function lr(e,t){return e?.entities.filter(r=>r.projectId===t)??[]}function ue(e,t=12){return [...new Set([...e].map(r=>r.trim()).filter(Boolean))].sort((r,n)=>r.localeCompare(n)).slice(0,t)}function Wt(e){return [...new Set([...e].map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function dr(e){if(e.template.scopedProjects)return {projects:[...e.template.scopedProjects].sort(),reasons:["The canonical workspace model directly derived this capability."],signals:ue(e.template.scopedProjects.map(i=>`model:project:${i}:${e.template.skillId}`)),confidence:"high",applicable:true};if(e.template.applicability==="workspace")return {projects:e.model.projects.map(i=>i.name).sort(),reasons:["Workspace-level release and verification gates are always available."],signals:["model:workspace",`model:project-count:${e.model.projects.length}`],confidence:"high",applicable:true};let t=[],r=[],n=new Set;for(let i of e.model.projects){let c=lr(e.graph,i.name),m=Wt([...i.importantFiles,...c.map(sr).filter(l=>!!l)]),a=e.contract?.projects.find(l=>l.slug===i.name),k=false;switch(e.template.applicability){case "dependency":{let l=m.filter(d=>ar.test(d)),p=c.filter(d=>d.kind==="package");k=l.length>0||p.length>0,r.push(...l.map(d=>`artifact:${d}`),...p.slice(0,4).map(d=>`graph:package:${d.label}`)),k&&n.add("Dependency manifests or package entities were observed.");break}case "api":{let l=c.filter(w=>w.kind==="api"||w.kind==="endpoint"||w.kind==="service"&&cr(w)),p=m.filter(w=>or.test(w)),d=a?.contracts?.apis??[],R=(a?.ports??[]).filter(w=>["http","https","grpc"].includes(w.protocol));k=l.length>0||p.length>0||d.length>0||R.length>0,r.push(...l.slice(0,4).map(w=>`graph:${w.kind}:${w.label}`),...p.map(w=>`artifact:${w}`),...d.map(w=>`contract:api:${w.name}:${w.basePath}`),...R.map(w=>`contract:port:${w.name}:${w.protocol}:${w.port}`)),k&&n.add("An API, endpoint, routed artifact, or network contract was observed.");break}case "schema":{let l=c.filter(d=>{if(d.kind==="database")return true;if(d.kind!=="schema")return false;let R=`${d.label} ${JSON.stringify(d.attributes)}`;return /database|migration|sql|prisma|orm/i.test(R)}),p=m.filter(d=>ir.test(d));k=l.length>0||p.length>0,r.push(...l.slice(0,4).map(d=>`graph:${d.kind}:${d.label}`),...p.map(d=>`artifact:${d}`)),k&&n.add("A database, schema, or migration artifact was observed.");break}case "contract":{let l=a?[...a.contracts?.owns??[],...a.contracts?.publishes??[],...a.contracts?.consumes??[],...(a.contracts?.apis??[]).map(d=>d.name)]:[],p=c.filter(d=>["api","protocol"].includes(d.kind));k=l.length>0||p.length>0,r.push(...l.map(d=>`contract:${i.name}:${d}`),...p.slice(0,6).map(d=>`graph:${d.kind}:${d.label}`)),k&&n.add("A shared API, protocol, schema, or authored contract edge was observed.");break}case "derived":k=true;break}k&&t.push(i.name);}return {projects:ue(t,e.model.projects.length),reasons:[...n],signals:ue(r),confidence:e.graph||e.contract?"high":"medium",applicable:t.length>0}}function pr(e,t,r){let n=[];for(let i of t){let c=e.projects.find(l=>l.name===i);if(!c)continue;let m=c.commands.supported.filter(l=>["build","test","lint","format"].includes(l)),a=c.commands.supported.filter(l=>["docs","doctor"].includes(l)),k=r.filter(l=>l.startsWith("artifact:")).map(l=>l.slice(9)).filter(l=>c.importantFiles.includes(l)||l.includes(c.name));n.push(`- **${c.name}** \u2014 runtime \`${c.runtime}\`, framework \`${c.framework}\`, confidence \`${c.confidence}\`.`),n.push(m.length>0?` Registered lifecycle commands: ${m.map(l=>`\`${l}\``).join(", ")}.`:" No project-native build/test command is registered; inspect repository-authored manifests and Graph proofs before running a command."),a.length>0&&n.push(` Registered evidence commands: ${a.map(l=>`\`${l}\``).join(", ")}.`),k.length>0&&n.push(` Relevant artifacts: ${ue(k,6).map(l=>`\`${l}\``).join(", ")}.`);}return n.length>0?n:["- No project boundary was proven; do not infer repository-specific commands or files."]}function ur(e,t){let r=e.applicability==="api"?"api endpoint route service failure":e.applicability==="schema"?"database schema migration persistence":e.applicability==="dependency"?"package dependency manifest lockfile":e.applicability==="contract"?"api protocol published consumed contract":e.applicability==="workspace"?"release pipeline deployment verification":`${e.title.toLowerCase()} manifest command test`;return t.slice(0,8).map(n=>z(`workspace graph search "${r}" --scope project:${n} --limit 12 --json`))}function jt(e){let t=e.model.workspace.name,r=[],n=[];for(let i of [...Qt,...tr(e.model)]){let c=dr({template:i,model:e.model,contract:e.contract??null,graph:e.graph??null}),m={skillId:i.skillId,title:i.title,status:c.applicable?"generated":"suppressed",confidence:c.confidence,reasons:c.reasons.length>0?c.reasons:["No authoritative workspace signal proves this capability is present."],signals:c.signals,scopedProjects:c.projects};if(n.push(m),m.status==="suppressed")continue;let a=m.scopedProjects,k=rr(e.context??null,a),l=nr(e.contract??null,a),p=Zt({template:i,workspaceName:t,scopedProjects:a,verificationCommands:k,contractSummary:l,decision:m,projectEvidence:pr(e.model,a,m.signals),retrievalCommands:ur(i,a)});r.push(Ot({skillId:i.skillId,title:i.title,triggers:i.triggers,requiredReports:[..._t],scopedProjects:a,verificationCommands:k,...X$1(i.skillId)?{promptStem:Y$1[i.skillId]}:{},markdown:p}));}return {skills:r,decisions:n}}async function Nt(e){let t=s.resolve(e.workspacePath),r=[],n=d$1({skills:e.skills.map(a=>({id:a.skillId,path:a.canonicalPath,hash:d$1({markdown:a.markdown})})),decisions:e.decisions??[]}),i=Tt({generatedAt:e.generatedAt,skills:e.skills,inputsHash:n,decisions:e.decisions}),c=new Set(e.skills.map(a=>a.skillId)),m=[];if(e.write){let a=s.join(t,".workspai","skills");if(await h$1.pathExists(a))for(let l of await h$1.readdir(a,{withFileTypes:true})){if(!l.isFile()||!l.name.endsWith(".md"))continue;let p=l.name.slice(0,-3);if(c.has(p))continue;let d=s.join(a,l.name);(await h$1.readFile(d,"utf8")).includes(B)&&(await h$1.remove(d),m.push(p));}for(let l of e.skills){let p=s.join(t,l.canonicalPath);await h$1.ensureDir(s.dirname(p)),await h$1.writeFile(p,l.markdown,"utf8"),r.push(l.canonicalPath);}let k=s.join(t,b$2);await h$1.ensureDir(s.dirname(k)),await h$1.writeJson(k,i,{spaces:2}),r.push(b$2);}return {skills:e.skills,index:i,writtenPaths:r,removedSkillIds:m.sort()}}function Lt(e){return ["## Operational skills (canonical)","","Read workspace-native playbooks from `.workspai/skills/` before generic repo scans. Legacy `.rapidkit/skills/` playbooks are read only when already present from older workspaces:","",...e.skills.map(r=>`- \`${r.path}\` \u2014 ${r.title} (\`${r.skillId}\`)`),"","Regenerate:","","```bash",z("workspace agent-sync --write --refresh-context"),"```",""].join(`
4
4
  `)}var gr={"workspai-diagnose-api-failure":A,"workspai-release-readiness":E},Je="## Workspace verification (hydrated)";function mr(e){let t=[Je,"","Verification commands for this workspace:","",...e.verificationCommands.length?e.verificationCommands.map(r=>`- \`${r}\``):["- `npx workspai workspace verify --json`"]];return e.scopedProjects.length>0&&t.push("","Scoped projects:","",...e.scopedProjects.map(r=>`- ${r}`)),t.push(""),t.join(`