arkgate 4.8.5 → 4.8.6

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 (62) hide show
  1. package/CHANGELOG.md +33 -2
  2. package/README.md +15 -9
  3. package/bin/lib/analysis-engine.mjs +4 -4
  4. package/bin/lib/ark-order-invariants.mjs +163 -14
  5. package/bin/lib/ark-order-types.mjs +3 -0
  6. package/bin/lib/diagnostic-catalog.mjs +5 -4
  7. package/bin/lib/remediation.mjs +11 -5
  8. package/dist/{diagnosticCatalog-DMO30svh.d.ts → diagnosticCatalog-D_DI7qrZ.d.ts} +1 -1
  9. package/dist/eslint/index.cjs +1 -1
  10. package/dist/eslint/index.js +1 -1
  11. package/dist/index.cjs +11 -11
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +10 -10
  14. package/dist/nestjs/index.cjs +5 -5
  15. package/dist/nestjs/index.d.ts +1 -1
  16. package/dist/nestjs/index.js +5 -5
  17. package/dist/order/index.cjs +1 -1
  18. package/dist/order/index.d.ts +61 -10
  19. package/dist/order/index.js +1 -1
  20. package/dist/runtime/index.cjs +11 -11
  21. package/dist/runtime/index.d.ts +3 -3
  22. package/dist/runtime/index.js +11 -11
  23. package/dist/{types-CzE6LMaW.d.ts → types-DrqsOiTY.d.ts} +21 -6
  24. package/docs/README.md +5 -4
  25. package/docs/agent-guide.md +2 -0
  26. package/docs/ai-gates.md +5 -2
  27. package/docs/arkorder.md +32 -14
  28. package/docs/configuration.md +5 -3
  29. package/docs/develop.md +7 -2
  30. package/docs/diagnostics.md +15 -5
  31. package/docs/package-surface.md +13 -10
  32. package/docs/product-voice.md +3 -3
  33. package/docs/use.md +1 -1
  34. package/package.json +1 -1
  35. package/server.json +2 -2
  36. package/templates/agent-skills/README.md +1 -1
  37. package/templates/agent-skills/ark-adopt/SKILL.md +4 -4
  38. package/templates/agent-skills/ark-architect/SKILL.md +1 -1
  39. package/templates/agent-skills/ark-autopilot/SKILL.md +4 -4
  40. package/templates/agent-skills/ark-contract/SKILL.md +1 -1
  41. package/templates/agent-skills/ark-coverage/SKILL.md +3 -2
  42. package/templates/agent-skills/ark-explain/SKILL.md +3 -2
  43. package/templates/agent-skills/ark-explore/SKILL.md +3 -2
  44. package/templates/agent-skills/ark-fix/SKILL.md +1 -1
  45. package/templates/agent-skills/ark-loop/SKILL.md +1 -1
  46. package/templates/agent-skills/ark-place/SKILL.md +8 -8
  47. package/templates/agent-skills/ark-runtime/SKILL.md +3 -0
  48. package/templates/agent-skills/ark-think/SKILL.md +2 -2
  49. package/templates/agent-skills/ark-upgrade/SKILL.md +2 -2
  50. package/templates/skills/ark-adopt.md +4 -4
  51. package/templates/skills/ark-architect.md +1 -1
  52. package/templates/skills/ark-autopilot.md +4 -4
  53. package/templates/skills/ark-contract.md +1 -1
  54. package/templates/skills/ark-coverage.md +3 -2
  55. package/templates/skills/ark-explain.md +3 -2
  56. package/templates/skills/ark-explore.md +3 -2
  57. package/templates/skills/ark-fix.md +1 -1
  58. package/templates/skills/ark-loop.md +1 -1
  59. package/templates/skills/ark-place.md +8 -8
  60. package/templates/skills/ark-runtime.md +3 -0
  61. package/templates/skills/ark-think.md +2 -2
  62. package/templates/skills/ark-upgrade.md +2 -2
@@ -1,10 +1,10 @@
1
- var we=Object.defineProperty;var yn=Object.getOwnPropertyDescriptor;var s=(t,e)=>we(t,"name",{value:e,configurable:!0});var M=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var hn=(t,e)=>{for(var n in e)we(t,n,{get:e[n],enumerable:!0})};var it=(t,e,n,r)=>{for(var o=r>1?void 0:r?yn(e,n):e,i=t.length-1,a;i>=0;i--)(a=t[i])&&(o=(r?a(e,n,o):a(o))||o);return r&&o&&we(e,n,o),o};function Ie(t,e){return t<e?-1:t>e?1:0}function An(t){return[...new Set(t)].sort(Ie)}function _(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return An(e)}function wn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function In(t){return typeof t=="string"&&Rn.has(t)?t:"singleton"}function En(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Object.keys(t).sort(Ie)){if(n.length===0)continue;let r=wn(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function Sn(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n={};typeof e.label=="string"&&e.label.length>0&&(n.label=e.label),typeof e.architectureKind=="string"&&e.architectureKind.length>0&&(n.architectureKind=e.architectureKind);let r=_(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=En(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Ee(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.id=="string"?e.id.trim():"";if(!n)return;let r={id:n,lifetime:In(e.lifetime),uses:_(e.uses),reactsTo:_(e.reactsTo),raises:_(e.raises),sends:_(e.sends)},o=Sn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function v(t){let e=typeof t.kernelInstanceId=="string"?t.kernelInstanceId:"",n=Array.isArray(t.components)?t.components:[],r=new Set,o=[];for(let i of n){let a=Ee(i);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((i,a)=>Ie(i.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:e,components:o}}var kn,Rn,L=M(()=>{"use strict";kn=["singleton","transient"],Rn=new Set(kn);s(Ie,"compare");s(An,"uniqueSorted");s(_,"nameList");s(wn,"jsonPrimitive");s(In,"closedLifetime");s(En,"sanitizeMetadata");s(Sn,"sanitizeArkRunExtendedInfo");s(Ee,"sanitizeArkRunComponent");s(v,"buildDependencyInformationPackage")});function F(t,e){return t<e?-1:t>e?1:0}function Se(t){return[...new Set(t)].sort(F)}function st(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function ve(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function w(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Se(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(t))throw new R(e);let n=[];for(let r of t){if(typeof r!="string")throw new R(e);let o=r.trim();o.length>0&&n.push(o)}return Se(n)}function lt(t,e){if(e==="*")return t.length>0;if(!e.includes("*"))return t===e;let n="^";for(let r of e)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(t)}function G(t,e){return t?e.some(n=>lt(t,n)):!1}function ut(t){if(t==null||t==="")return Pn;if(typeof t=="string"&&xn.has(t))return t;throw new R("slice")}function pt(t){if(t==null||t==="")return null;if(typeof t=="string"&&/^(0|[1-9]\d*)$/.test(t))return Number(t);if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;throw new R("degreesOfSeparation")}function at(t,e){if(t==null||t==="")return st();if(typeof t=="string"||Array.isArray(t))return{...st(),tokens:w(t,e)};if(typeof t!="object")throw new R(e);let n=t;for(let r of Object.keys(n))if(!On.has(r))throw new R(e);return{tokens:[],ids:w(n.ids,e),labels:w(n.labels,e),tags:w(n.tags,e),groups:w(n.groups,e),architectureKinds:w(n.architectureKinds,e)}}function ft(t={}){if(t==null||t==="")return ft({});if(typeof t!="object"||Array.isArray(t))throw new R("slice","ArkRun graph query must be an object.");let e=t;for(let n of Object.keys(e))if(!Cn.has(n))throw new R("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:ut(e.slice),nodeIds:w(e.nodeIds,"nodeIds"),degreesOfSeparation:pt(e.degreesOfSeparation),include:at(e.include,"include"),exclude:at(e.exclude,"exclude")}}function mt(t){let e={};t.slice&&(e.slice=ut(t.slice));let n=w(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=pt(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=w(t.include??void 0,"include");o.length>0&&(e.include=o);let i=w(t.exclude??void 0,"exclude");return i.length>0&&(e.exclude=i),e}function Nn(t){let e=[t.id];return t.label&&e.push(t.label),t.group&&e.push(t.group),t.architectureKind&&e.push(t.architectureKind),t.tags&&e.push(...t.tags),e}function ct(t,e){if(!ve(e))return!0;let n=Nn(t);return e.tokens.some(r=>n.some(o=>lt(o,r)))||G(t.id,e.ids)||G(t.label,e.labels)||t.tags?.some(r=>G(r,e.tags))||G(t.group,e.groups)?!0:G(t.architectureKind,e.architectureKinds)}function Dn(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return v({kernelInstanceId:e.kernelInstanceId,components:e.components})}return v({})}function Tn(t){let e={id:t.id,kind:"component",lifetime:t.lifetime},n=t.extendedInfo;return n?.label&&(e.label=n.label),n?.group&&(e.group=n.group),n?.architectureKind&&(e.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(e.tags=[...n.tags]),e}function te(t){return{id:t,kind:"interaction"}}function K(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function ne(t,e,n,r,o){let i=`${n}\0${o}\0${r}`;e.has(i)||(e.add(i),t.push({from:n,to:r,kind:o}))}function $n(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(K(n,Tn(i)),e==="technical"){for(let a of i.uses)K(n,n.get(a)??te(a)),ne(r,o,i.id,a,"uses");continue}for(let a of i.raises)K(n,n.get(a)??te(a)),ne(r,o,i.id,a,"raises");for(let a of i.reactsTo)K(n,n.get(a)??te(a)),ne(r,o,a,i.id,"reactsTo");for(let a of i.sends)K(n,n.get(a)??te(a)),ne(r,o,i.id,a,"sends")}return{nodes:n,edges:r}}function Mn(t){let e=new Map,n=s((r,o)=>{let i=e.get(r);i?i.push(o):e.set(r,[o])},"push");for(let r of t)n(r.from,r.to),n(r.to,r.from);return e}function _n(t,e,n,r){let o=e.filter(c=>t.has(c));if(o.length===0)return new Set;let i=new Set,a=o.map(c=>({id:c,depth:0}));for(;a.length>0;){let c=a.shift();if(!(!c||i.has(c.id))&&(i.add(c.id),!(n!==null&&c.depth>=n)))for(let d of r.get(c.id)??[])!i.has(d)&&t.has(d)&&a.push({id:d,depth:c.depth+1})}return i}function j(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function dt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Ln(t){let e=new Set,n=new Map;for(let r of t){let o=j(r),i=o,a=2;for(;e.has(i);)i=`${o}_${a}`,a+=1;e.add(i),n.set(r,i)}return n}function Gn(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=Ln(n),o=Se(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,d)=>{let l=r.get(c.id)??j(c.id),p=dt(c.label??c.id);i.push(`${d}${l}["${p}"]`)},"emitNode");for(let c of o){let d=j(`group_${c}`);i.push(` subgraph ${d}["${dt(c)}"]`);for(let l of t.nodes)l.group===c&&a(l," ");i.push(" end")}for(let c of t.nodes)c.group||a(c," ");for(let c of t.edges){let d=r.get(c.from)??j(c.from),l=r.get(c.to)??j(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
- `)}function Kn(t,e,n){let r=new Set(t.keys());if(ve(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&ct(d,n.include)}))),ve(n.exclude))for(let c of[...r]){let d=t.get(c);d&&ct(d,n.exclude)&&r.delete(c)}let o=e.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=_n(r,n.nodeIds,n.degreesOfSeparation,Mn(o)));let i=[...r].sort(F).map(c=>t.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,d)=>F(c.from,d.from)||F(c.kind,d.kind)||F(c.to,d.to));return{nodes:i,edges:a}}function gt(t={},e={}){let n=Dn(t),r=ft(e),o=$n(n.components,r.slice),i=Kn(o.nodes,o.edges,r),a={schemaVersion:vn,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=Gn(a),a}var vn,Pn,bn,R,xn,Cn,On,Pe=M(()=>{"use strict";L();vn="1.0",Pn="process",bn=["process","technical"],R=class extends Error{static{s(this,"InvalidArkRunGraphQueryError")}option;constructor(e,n){super(n??(e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=e}},xn=new Set(bn),Cn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),On=new Set(["ids","labels","tags","groups","architectureKinds"]);s(F,"compare");s(Se,"uniqueSorted");s(st,"emptyMatch");s(ve,"matchHasCriteria");s(w,"nameList");s(lt,"globMatch");s(G,"anyGlob");s(ut,"closedSlice");s(pt,"closedDegrees");s(at,"closedMatch");s(ft,"closeArkRunGraphQuery");s(mt,"arkRunGraphQueryFromSearchParams");s(Nn,"nodeFields");s(ct,"nodeMatches");s(Dn,"asPackage");s(Tn,"componentNode");s(te,"interactionNode");s(K,"addNode");s(ne,"addEdge");s($n,"buildSlice");s(Mn,"adjacency");s(_n,"neighborhood");s(j,"mermaidSafeId");s(dt,"mermaidLabel");s(Ln,"uniqueMermaidIds");s(Gn,"formatArkRunGraphMermaid");s(Kn,"filterGraph");s(gt,"requestArkRunGraph")});function jn(t){if(t===void 0)return"local";if(typeof t=="string"&&Fn.has(t))return t;throw new re("transport")}function Bn(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new re("ephemeral")}function yt(t){let e=jn(t.transport),n=Bn(t.ephemeral),r=e==="broker"&&t.brokerBound!==!0,o=e==="broker"&&!r?"broker":"local",i=e==="localBlocking";return{transport:e,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:i,awaitHandoff:n||i}}var be,Fn,re,oe=M(()=>{"use strict";be=["local","localBlocking","broker"],Fn=new Set(be),re=class extends Error{static{s(this,"InvalidArkRunSendOptionError")}option;constructor(e){super(e==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=e}};s(jn,"closedArkRunTransportKind");s(Bn,"closedArkRunEphemeral");s(yt,"resolveArkRunSendPlan")});function kt(t){return t==="production"}function Jn(t){let e=t.split(".");if(e.length!==4)return;let n=[];for(let r of e){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function Rt(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function se(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=Rt(e);if(n)return se(n);let r=Jn(e);return r!==void 0&&r[0]===127}function At(t){if(t===void 0)return ht;if(typeof t!="string")throw new I(String(t));let e=t.trim();if(zn.has(e.toLowerCase())||!se(e))throw new I(e);let n=e.toLowerCase();if(n==="localhost")return ht;if(n==="[::1]")return"::1";let r=Rt(n);return r?At(r):n}function Qn(t){if(t===void 0)return Un;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new I(`port:${String(t)}`);return t}function De(t={}){if(kt(t.nodeEnv)||kt(t.processNodeEnv))throw new ie;return{host:At(t.host),port:Qn(t.port)}}function B(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function Xn(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function Zn(t){return{kinds:[...be],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:qn}}function wt(t={}){let e=De({host:t.host,port:t.port}),n=v({kernelInstanceId:t.kernelInstanceId,components:t.package&&typeof t.package=="object"&&!Array.isArray(t.package)&&Array.isArray(t.package.components)?t.package.components:[]});return{schemaVersion:Vn,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Zn(t),observability:Xn(t.observability)??{}}}function Te(t){return`event: ${Wn}
1
+ var we=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var s=(t,e)=>we(t,"name",{value:e,configurable:!0});var $=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var kn=(t,e)=>{for(var n in e)we(t,n,{get:e[n],enumerable:!0})};var it=(t,e,n,r)=>{for(var o=r>1?void 0:r?hn(e,n):e,i=t.length-1,a;i>=0;i--)(a=t[i])&&(o=(r?a(e,n,o):a(o))||o);return r&&o&&we(e,n,o),o};function Ie(t,e){return t<e?-1:t>e?1:0}function In(t){return[...new Set(t)].sort(Ie)}function M(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return In(e)}function En(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function Sn(t){return typeof t=="string"&&wn.has(t)?t:"singleton"}function st(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Object.keys(t).sort(Ie)){if(n.length===0)continue;let r=En(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function vn(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n={};typeof e.label=="string"&&e.label.length>0&&(n.label=e.label),typeof e.architectureKind=="string"&&e.architectureKind.length>0&&(n.architectureKind=e.architectureKind);let r=M(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=st(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Ee(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.id=="string"?e.id.trim():"";if(!n)return;let r={id:n,lifetime:Sn(e.lifetime),uses:M(e.uses),reactsTo:M(e.reactsTo),raises:M(e.raises),sends:M(e.sends)},o=vn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function bn(t){return st(t)}function xn(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!n)return;let r=e.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,i=typeof o.kind=="string"?o.kind.trim():"";if(!i)return;let a=e.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let c=a,d=typeof c.kind=="string"&&Pn.has(c.kind)?c.kind:void 0;if(!d)return;let l={kind:i},p=bn(o.payload);p&&(l.payload=p);let y={kind:d};return typeof c.reasonCode=="string"&&c.reasonCode.length>0&&(y.reasonCode=c.reasonCode),typeof c.eventId=="string"&&c.eventId.length>0&&(y.eventId=c.eventId),typeof c.target=="string"&&c.target.length>0&&(y.target=c.target),{xiHash:n,event:l,residual:y}}function Cn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){let r=xn(n);r&&e.push(r)}return e}function v(t){let e=typeof t.kernelInstanceId=="string"?t.kernelInstanceId:"",n=Array.isArray(t.components)?t.components:[],r=new Set,o=[];for(let a of n){let c=Ee(a);!c||r.has(c.id)||(r.add(c.id),o.push(c))}o.sort((a,c)=>Ie(a.id,c.id));let i=Cn(t.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:o,...i.length>0?{decisionTape:i}:{}}}var Rn,An,wn,Pn,L=$(()=>{"use strict";Rn=["singleton","transient"],An=["absorb","escalate_up","hold"],wn=new Set(Rn);s(Ie,"compare");s(In,"uniqueSorted");s(M,"nameList");s(En,"jsonPrimitive");s(Sn,"closedLifetime");s(st,"sanitizeMetadata");s(vn,"sanitizeArkRunExtendedInfo");s(Ee,"sanitizeArkRunComponent");Pn=new Set(An);s(bn,"sanitizeTapePayload");s(xn,"sanitizeDecisionTapeRecord");s(Cn,"sanitizeDecisionTape");s(v,"buildDependencyInformationPackage")});function j(t,e){return t<e?-1:t>e?1:0}function Se(t){return[...new Set(t)].sort(j)}function at(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function ve(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function w(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Se(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(t))throw new R(e);let n=[];for(let r of t){if(typeof r!="string")throw new R(e);let o=r.trim();o.length>0&&n.push(o)}return Se(n)}function ut(t,e){if(e==="*")return t.length>0;if(!e.includes("*"))return t===e;let n="^";for(let r of e)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(t)}function K(t,e){return t?e.some(n=>ut(t,n)):!1}function pt(t){if(t==null||t==="")return Nn;if(typeof t=="string"&&Tn.has(t))return t;throw new R("slice")}function ft(t){if(t==null||t==="")return null;if(typeof t=="string"&&/^(0|[1-9]\d*)$/.test(t))return Number(t);if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;throw new R("degreesOfSeparation")}function ct(t,e){if(t==null||t==="")return at();if(typeof t=="string"||Array.isArray(t))return{...at(),tokens:w(t,e)};if(typeof t!="object")throw new R(e);let n=t;for(let r of Object.keys(n))if(!$n.has(r))throw new R(e);return{tokens:[],ids:w(n.ids,e),labels:w(n.labels,e),tags:w(n.tags,e),groups:w(n.groups,e),architectureKinds:w(n.architectureKinds,e)}}function gt(t={}){if(t==null||t==="")return gt({});if(typeof t!="object"||Array.isArray(t))throw new R("slice","ArkRun graph query must be an object.");let e=t;for(let n of Object.keys(e))if(!_n.has(n))throw new R("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:pt(e.slice),nodeIds:w(e.nodeIds,"nodeIds"),degreesOfSeparation:ft(e.degreesOfSeparation),include:ct(e.include,"include"),exclude:ct(e.exclude,"exclude")}}function mt(t){let e={};t.slice&&(e.slice=pt(t.slice));let n=w(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=ft(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=w(t.include??void 0,"include");o.length>0&&(e.include=o);let i=w(t.exclude??void 0,"exclude");return i.length>0&&(e.exclude=i),e}function Mn(t){let e=[t.id];return t.label&&e.push(t.label),t.group&&e.push(t.group),t.architectureKind&&e.push(t.architectureKind),t.tags&&e.push(...t.tags),e}function dt(t,e){if(!ve(e))return!0;let n=Mn(t);return e.tokens.some(r=>n.some(o=>ut(o,r)))||K(t.id,e.ids)||K(t.label,e.labels)||t.tags?.some(r=>K(r,e.tags))||K(t.group,e.groups)?!0:K(t.architectureKind,e.architectureKinds)}function Ln(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return v({kernelInstanceId:e.kernelInstanceId,components:e.components})}return v({})}function Kn(t){let e={id:t.id,kind:"component",lifetime:t.lifetime},n=t.extendedInfo;return n?.label&&(e.label=n.label),n?.group&&(e.group=n.group),n?.architectureKind&&(e.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(e.tags=[...n.tags]),e}function te(t){return{id:t,kind:"interaction"}}function G(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function ne(t,e,n,r,o){let i=`${n}\0${o}\0${r}`;e.has(i)||(e.add(i),t.push({from:n,to:r,kind:o}))}function Gn(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(G(n,Kn(i)),e==="technical"){for(let a of i.uses)G(n,n.get(a)??te(a)),ne(r,o,i.id,a,"uses");continue}for(let a of i.raises)G(n,n.get(a)??te(a)),ne(r,o,i.id,a,"raises");for(let a of i.reactsTo)G(n,n.get(a)??te(a)),ne(r,o,a,i.id,"reactsTo");for(let a of i.sends)G(n,n.get(a)??te(a)),ne(r,o,i.id,a,"sends")}return{nodes:n,edges:r}}function jn(t){let e=new Map,n=s((r,o)=>{let i=e.get(r);i?i.push(o):e.set(r,[o])},"push");for(let r of t)n(r.from,r.to),n(r.to,r.from);return e}function Fn(t,e,n,r){let o=e.filter(c=>t.has(c));if(o.length===0)return new Set;let i=new Set,a=o.map(c=>({id:c,depth:0}));for(;a.length>0;){let c=a.shift();if(!(!c||i.has(c.id))&&(i.add(c.id),!(n!==null&&c.depth>=n)))for(let d of r.get(c.id)??[])!i.has(d)&&t.has(d)&&a.push({id:d,depth:c.depth+1})}return i}function F(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function lt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Bn(t){let e=new Set,n=new Map;for(let r of t){let o=F(r),i=o,a=2;for(;e.has(i);)i=`${o}_${a}`,a+=1;e.add(i),n.set(r,i)}return n}function Hn(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=Bn(n),o=Se(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,d)=>{let l=r.get(c.id)??F(c.id),p=lt(c.label??c.id);i.push(`${d}${l}["${p}"]`)},"emitNode");for(let c of o){let d=F(`group_${c}`);i.push(` subgraph ${d}["${lt(c)}"]`);for(let l of t.nodes)l.group===c&&a(l," ");i.push(" end")}for(let c of t.nodes)c.group||a(c," ");for(let c of t.edges){let d=r.get(c.from)??F(c.from),l=r.get(c.to)??F(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
+ `)}function Vn(t,e,n){let r=new Set(t.keys());if(ve(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&dt(d,n.include)}))),ve(n.exclude))for(let c of[...r]){let d=t.get(c);d&&dt(d,n.exclude)&&r.delete(c)}let o=e.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=Fn(r,n.nodeIds,n.degreesOfSeparation,jn(o)));let i=[...r].sort(j).map(c=>t.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,d)=>j(c.from,d.from)||j(c.kind,d.kind)||j(c.to,d.to));return{nodes:i,edges:a}}function yt(t={},e={}){let n=Ln(t),r=gt(e),o=Gn(n.components,r.slice),i=Vn(o.nodes,o.edges,r),a={schemaVersion:On,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=Hn(a),a}var On,Nn,Dn,R,Tn,_n,$n,Pe=$(()=>{"use strict";L();On="1.0",Nn="process",Dn=["process","technical"],R=class extends Error{static{s(this,"InvalidArkRunGraphQueryError")}option;constructor(e,n){super(n??(e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=e}},Tn=new Set(Dn),_n=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),$n=new Set(["ids","labels","tags","groups","architectureKinds"]);s(j,"compare");s(Se,"uniqueSorted");s(at,"emptyMatch");s(ve,"matchHasCriteria");s(w,"nameList");s(ut,"globMatch");s(K,"anyGlob");s(pt,"closedSlice");s(ft,"closedDegrees");s(ct,"closedMatch");s(gt,"closeArkRunGraphQuery");s(mt,"arkRunGraphQueryFromSearchParams");s(Mn,"nodeFields");s(dt,"nodeMatches");s(Ln,"asPackage");s(Kn,"componentNode");s(te,"interactionNode");s(G,"addNode");s(ne,"addEdge");s(Gn,"buildSlice");s(jn,"adjacency");s(Fn,"neighborhood");s(F,"mermaidSafeId");s(lt,"mermaidLabel");s(Bn,"uniqueMermaidIds");s(Hn,"formatArkRunGraphMermaid");s(Vn,"filterGraph");s(yt,"requestArkRunGraph")});function Wn(t){if(t===void 0)return"local";if(typeof t=="string"&&Un.has(t))return t;throw new re("transport")}function qn(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new re("ephemeral")}function ht(t){let e=Wn(t.transport),n=qn(t.ephemeral),r=e==="broker"&&t.brokerBound!==!0,o=e==="broker"&&!r?"broker":"local",i=e==="localBlocking";return{transport:e,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:i,awaitHandoff:n||i}}var be,Un,re,oe=$(()=>{"use strict";be=["local","localBlocking","broker"],Un=new Set(be),re=class extends Error{static{s(this,"InvalidArkRunSendOptionError")}option;constructor(e){super(e==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=e}};s(Wn,"closedArkRunTransportKind");s(qn,"closedArkRunEphemeral");s(ht,"resolveArkRunSendPlan")});function Rt(t){return t==="production"}function er(t){let e=t.split(".");if(e.length!==4)return;let n=[];for(let r of e){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function At(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function se(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=At(e);if(n)return se(n);let r=er(e);return r!==void 0&&r[0]===127}function wt(t){if(t===void 0)return kt;if(typeof t!="string")throw new I(String(t));let e=t.trim();if(Yn.has(e.toLowerCase())||!se(e))throw new I(e);let n=e.toLowerCase();if(n==="localhost")return kt;if(n==="[::1]")return"::1";let r=At(n);return r?wt(r):n}function tr(t){if(t===void 0)return Qn;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new I(`port:${String(t)}`);return t}function De(t={}){if(Rt(t.nodeEnv)||Rt(t.processNodeEnv))throw new ie;return{host:wt(t.host),port:tr(t.port)}}function B(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function nr(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function rr(t){return{kinds:[...be],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:Zn}}function It(t={}){let e=De({host:t.host,port:t.port}),n=v({kernelInstanceId:t.kernelInstanceId,components:t.package&&typeof t.package=="object"&&!Array.isArray(t.package)&&Array.isArray(t.package.components)?t.package.components:[]});return{schemaVersion:Jn,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:rr(t),observability:nr(t.observability)??{}}}function Te(t){return`event: ${Xn}
3
3
  data: ${JSON.stringify(t)}
4
4
 
5
- `}var Vn,ht,Un,Ce,Oe,Ne,Wn,qn,ie,I,zn,ae=M(()=>{"use strict";L();oe();Vn="1.0",ht="127.0.0.1",Un=0,Ce="/snapshot",Oe="/events",Ne="/graph",Wn="snapshot",qn="in-process-local",ie=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},I=class extends Error{static{s(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},zn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(kt,"isArkRunInspectorProductionEnv");s(Jn,"ipv4Octets");s(Rt,"unwrapIpv4Mapped");s(se,"isArkRunInspectorLoopbackHost");s(At,"closedHost");s(Qn,"closedPort");s(De,"resolveArkRunInspectorBind");s(B,"arkRunInspectorUrl");s(Xn,"jsonClone");s(Zn,"closedTransportFacts");s(wt,"buildArkRunInspectorSnapshot");s(Te,"formatArkRunInspectorSseEvent")});var cn={};hn(cn,{listenArkRunInspector:()=>Mr});function Nr(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Dr(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Tr(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function ke(t,e,n){t.writeHead(e,Nr()),t.end(JSON.stringify(n))}function $r(t,e){let n=t.address();if(n===null||typeof n=="string")throw new I(e.host);if(!se(n.address))throw new I(n.address);return{host:e.host,port:n.port}}async function Mr(t,e){let n=await import("http"),r=new Set,o=new Set,i=typeof e.sseIntervalMs=="number"&&Number.isFinite(e.sseIntervalMs)?Math.max(0,e.sseIntervalMs):1e3,a=e.bind,c=s(()=>t.getInspectorSnapshot(a),"snapshot"),d=n.createServer((l,p)=>{let y=Tr(l.url),f=y.pathname;if(l.method==="GET"&&(f==="/"||f===Ce)){ke(p,200,c());return}if(l.method==="GET"&&f===Ne){try{ke(p,200,t.requestGraph(mt({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(m){if(m instanceof R){ke(p,400,{error:m.message,option:m.option});return}throw m}return}if(l.method==="GET"&&f===Oe){p.writeHead(200,Dr()),p.flushHeaders(),p.write(Te(c())),r.add(p);let m=i>0?setInterval(()=>{p.write(Te(c()))},i):void 0;m&&o.add(m);let h=s(()=>{r.delete(p),m&&(clearInterval(m),o.delete(m))},"drop");l.on("close",h),p.on("close",h);return}ke(p,404,{error:"not found"})});try{await new Promise((l,p)=>{let y=s(f=>p(f),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{a=$r(d,e.bind),l()}catch(f){p(f instanceof Error?f:new I(e.bind.host))}})})}catch(l){throw await new Promise(p=>{d.close(()=>p())}),l}return{host:a.host,port:a.port,url:B(a.host,a.port,"/"),snapshotUrl:B(a.host,a.port,Ce),eventsUrl:B(a.host,a.port,Oe),graphUrl:B(a.host,a.port,Ne),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,p)=>{d.close(y=>{y?p(y):l()})})}}}var dn=M(()=>{"use strict";Pe();ae();s(Nr,"jsonHeaders");s(Dr,"sseHeaders");s(Tr,"requestUrl");s(ke,"writeJson");s($r,"boundAddress");s(Mr,"listenArkRunInspector")});import{Inject as Fr,Module as jr}from"@nestjs/common";Pe();ae();L();oe();var It=0;function Yn(){return It+=1,`audit-${Date.now()}-${It}`}s(Yn,"createAuditId");function er(t,e){return!(e.type&&t.type!==e.type||e.intent&&t.intent!==e.intent||e.correlationId&&t.correlationId!==e.correlationId||e.subject&&t.subject!==e.subject||e.since&&t.timestamp<e.since||e.until&&t.timestamp>e.until)}s(er,"matchesQuery");var ce=class{constructor(e){this.maxRecords=e}maxRecords;static{s(this,"InMemoryAuditStore")}records=[];append(e){this.records.push(e),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(e={}){let n=this.records.filter(r=>er(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},de=class{constructor(e){this.store=e}store;static{s(this,"AuditTrailImpl")}async record(e){let n={id:Yn(),timestamp:e.timestamp??new Date().toISOString(),type:e.type,source:e.source,actor:e.actor,intent:e.intent,correlationId:e.correlationId,causationId:e.causationId,subject:e.subject,details:e.details};return await this.store.append(n),n}async query(e){return this.store.query(e)}async clear(){await this.store.clear()}};function $e(t={}){return new de(t.store??new ce(t.maxRecords))}s($e,"createAuditTrail");var P=class extends Error{static{s(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var Jn,kt,Qn,Ce,Oe,Ne,Xn,Zn,ie,I,Yn,ae=$(()=>{"use strict";L();oe();Jn="1.0",kt="127.0.0.1",Qn=0,Ce="/snapshot",Oe="/events",Ne="/graph",Xn="snapshot",Zn="in-process-local",ie=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},I=class extends Error{static{s(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},Yn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(Rt,"isArkRunInspectorProductionEnv");s(er,"ipv4Octets");s(At,"unwrapIpv4Mapped");s(se,"isArkRunInspectorLoopbackHost");s(wt,"closedHost");s(tr,"closedPort");s(De,"resolveArkRunInspectorBind");s(B,"arkRunInspectorUrl");s(nr,"jsonClone");s(rr,"closedTransportFacts");s(It,"buildArkRunInspectorSnapshot");s(Te,"formatArkRunInspectorSseEvent")});var dn={};kn(dn,{listenArkRunInspector:()=>jr});function Mr(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Lr(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Kr(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function ke(t,e,n){t.writeHead(e,Mr()),t.end(JSON.stringify(n))}function Gr(t,e){let n=t.address();if(n===null||typeof n=="string")throw new I(e.host);if(!se(n.address))throw new I(n.address);return{host:e.host,port:n.port}}async function jr(t,e){let n=await import("http"),r=new Set,o=new Set,i=typeof e.sseIntervalMs=="number"&&Number.isFinite(e.sseIntervalMs)?Math.max(0,e.sseIntervalMs):1e3,a=e.bind,c=s(()=>t.getInspectorSnapshot(a),"snapshot"),d=n.createServer((l,p)=>{let y=Kr(l.url),f=y.pathname;if(l.method==="GET"&&(f==="/"||f===Ce)){ke(p,200,c());return}if(l.method==="GET"&&f===Ne){try{ke(p,200,t.requestGraph(mt({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof R){ke(p,400,{error:g.message,option:g.option});return}throw g}return}if(l.method==="GET"&&f===Oe){p.writeHead(200,Lr()),p.flushHeaders(),p.write(Te(c())),r.add(p);let g=i>0?setInterval(()=>{p.write(Te(c()))},i):void 0;g&&o.add(g);let h=s(()=>{r.delete(p),g&&(clearInterval(g),o.delete(g))},"drop");l.on("close",h),p.on("close",h);return}ke(p,404,{error:"not found"})});try{await new Promise((l,p)=>{let y=s(f=>p(f),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{a=Gr(d,e.bind),l()}catch(f){p(f instanceof Error?f:new I(e.bind.host))}})})}catch(l){throw await new Promise(p=>{d.close(()=>p())}),l}return{host:a.host,port:a.port,url:B(a.host,a.port,"/"),snapshotUrl:B(a.host,a.port,Ce),eventsUrl:B(a.host,a.port,Oe),graphUrl:B(a.host,a.port,Ne),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,p)=>{d.close(y=>{y?p(y):l()})})}}}var ln=$(()=>{"use strict";Pe();ae();s(Mr,"jsonHeaders");s(Lr,"sseHeaders");s(Kr,"requestUrl");s(ke,"writeJson");s(Gr,"boundAddress");s(jr,"listenArkRunInspector")});import{Inject as Ur,Module as Wr}from"@nestjs/common";Pe();ae();L();oe();var Et=0;function or(){return Et+=1,`audit-${Date.now()}-${Et}`}s(or,"createAuditId");function ir(t,e){return!(e.type&&t.type!==e.type||e.intent&&t.intent!==e.intent||e.correlationId&&t.correlationId!==e.correlationId||e.subject&&t.subject!==e.subject||e.since&&t.timestamp<e.since||e.until&&t.timestamp>e.until)}s(ir,"matchesQuery");var ce=class{constructor(e){this.maxRecords=e}maxRecords;static{s(this,"InMemoryAuditStore")}records=[];append(e){this.records.push(e),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(e={}){let n=this.records.filter(r=>ir(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},de=class{constructor(e){this.store=e}store;static{s(this,"AuditTrailImpl")}async record(e){let n={id:or(),timestamp:e.timestamp??new Date().toISOString(),type:e.type,source:e.source,actor:e.actor,intent:e.intent,correlationId:e.correlationId,causationId:e.causationId,subject:e.subject,details:e.details};return await this.store.append(n),n}async query(e){return this.store.query(e)}async clear(){await this.store.clear()}};function _e(t={}){return new de(t.store??new ce(t.maxRecords))}s(_e,"createAuditTrail");var P=class extends Error{static{s(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
6
  `);super(`Hard policy violation(s) detected:
7
- ${n}`),this.name="PolicyViolationError",this.violations=e}};var C=class{static{s(this,"PolicyEngine")}policies=[];constructor(e=[]){for(let n of e)this.add(n)}add(e){if(this.policies.some(n=>n.name===e.name))throw new Error(`Policy "${e.name}" is already registered in this engine.`);this.policies.push(e)}getPolicies(){return[...this.policies]}evaluate(e){let n=[];for(let i of this.policies){let a=i.check(e);if(a!==!0){if(a===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(a))for(let c of a)n.push({policyName:i.name,severity:i.severity,message:c.message,details:c.details});else n.push({policyName:i.name,severity:i.severity,message:a.message,details:a.details})}}let r=n.filter(i=>i.severity==="hard"),o=n.filter(i=>i.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(e){let n=this.evaluate(e);if(n.hardViolations.length>0)throw new P(n.hardViolations);return n}clear(){this.policies.length=0}};function le(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}s(le,"definePolicy");function tr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(tr,"defaultLayerOf");function Et(t,e){return e.resolveLayer?.(t)??tr(t)}s(Et,"resolveLayer");function nr(t,e,n){return t===n.from&&e===n.to}s(nr,"matchesRule");function St(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return le({name:e,severity:n,tags:["layer"],check:s(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],i=[];for(let a of o){let c=Et(a.from,t),d=Et(a.to,t);for(let l of t.rules)!l.allowed&&nr(c,d,l)&&i.push({policyName:e,severity:n,message:l.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${d})`})}return i.length>0?i:!0},"check")})}s(St,"defineLayerPolicy");function Me(t){return t.tags?.includes("layer")??!1}s(Me,"isLayerPolicy");function _e(t,e={}){return St({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}s(_e,"defineArchitectureProfilePolicy");function Le(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Le,"buildPublishPolicyContext");var H=class extends Error{static{s(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},V=class extends Error{static{s(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},U=class extends Error{static{s(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},W=class extends Error{static{s(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},O=class extends Error{static{s(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},b=class extends Error{static{s(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},q=class extends Error{static{s(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}};var vt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ge(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!vt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${vt.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}s(Ge,"validateIntentName");function z(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ge(t);if(!n.valid)throw new V(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new H(t)}}s(z,"assertIntentAllowed");function Pt(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new O(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new O(t.intent,t.metadata.source)}}s(Pt,"assertSourceAllowed");function J(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new W(t.intent,n.issues)}s(J,"assertContractAllowed");function N(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}s(N,"isPlainRecord");function D(t){return Array.isArray(t)?t.map(D):N(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,D(n)])):t}s(D,"clonePatchValue");function Ke(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=D(i);continue}if(N(r[o])&&N(i)){r[o]=Ke(r[o],i,a);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=Fe(r[o],i,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}s(Ke,"mergeRecordPatch");function Fe(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let a=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=D(o);return}if(N(r[i])&&N(o)){r[i]=Ke(r[i],o,a);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=Fe(r[i],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}s(Fe,"mergeArrayPatch");function bt(t,e){if(Array.isArray(e)){if(t===void 0)return D(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return Fe(t,e)}if(t===void 0)return D(e);if(!N(t))throw new Error("Object interceptor patch requires an object payload.");return Ke(t,e)}s(bt,"applyPayloadPatch");async function xt(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:s(d=>{i.push(d)},"intercept")})),i.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let d of i)c={...c,payload:bt(c.payload,d),metadata:{...c.metadata}};J(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=a,e.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(a){await rr(o,r,a,e)}}return r}s(xt,"applyInterceptors");async function rr(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}s(rr,"recordInterceptorError");var Ct=new Map;function Ot(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}s(Ot,"escapeLiteral");function _t(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}s(_t,"normalizeGlobSeparators");function or(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}s(or,"bracesBalanced");function Nt(t){let e=Ct.get(t);if(e)return e;let n=_t(t),r=or(n),o="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(o+=Ot(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":d==="?"?o+="[^/]":d==="{"&&r?(o+="(?:",i+=1):d==="}"&&r&&i>0?(o+=")",i-=1):d===","&&r&&i>0?o+="|":o+=Ot(d)}let a=new RegExp(`^${o}$`);return Ct.set(t,a),a}s(Nt,"globToRegExp");function Dt(t,e){if(!e?.length)return;let n=String(t).split(/[/\\]/).filter(Boolean),r=new Set(e.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}s(Dt,"sliceIdForPath");function ir(t){let e=new Set;for(let n of t??[]){let o=_t(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let a=o[i];if((a==="**"||a==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}s(ir,"inferSliceFoldersFromPatterns");function sr(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return ir(r?.patterns)}s(sr,"resolveSliceFolders");function Tt(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}s(Tt,"normalizeSegments");function Lt(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}s(Lt,"trimTrailingSlashes");var ar=["src","app"];function cr(t){let e=Lt(t.replace(/^[./]+/,""));return e==="*"||e==="**"}s(cr,"isBlanketRoot");function $t(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Tt(n);for(let i of e){if(typeof i!="string"||i.length===0||cr(i))continue;if(i.includes("*")){let d=Lt(i.toLowerCase());if(Nt(d).test(r)||Nt(`${d}/**`).test(r))return!0;continue}let a=Tt(i);if(a.length===0)continue;let c=ar.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let d of c){if(d+a.length>o.length)continue;let l=!0;for(let p=0;p<a.length;p+=1)if(o[d+p]!==a[p]){l=!1;break}if(l)return!0}}return!1}s($t,"pathUnderSharedRoot");function Mt(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}s(Mt,"sliceMatchesDeclaration");function dr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Mt(r.from,e)&&Mt(r.to,n))}s(dr,"crossSliceEdgeAllowed");function lr(t){if(!t.fromPath||!t.toPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0,n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}s(lr,"peerIsolationDecision");function Gt(t,e,n,r){return ur(t,e,n,r)?.rule}s(Gt,"findDeniedEdgeRule");function ur(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,a=r?.toPath,c=sr(o,e,r?.layers),d=i&&a?Dt(i,c):void 0,l=i&&a?Dt(a,c):void 0,p=lr({fromPath:i,toPath:a,folderCount:c.length,fromSlice:d,toSlice:l,fromShared:!d&&$t(i,o.sharedRoots),toShared:!l&&$t(a,o.sharedRoots),crossSliceAllowed:dr(o.allowedCrossSlice,d,l)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:d,toSlice:l};continue}if(e!==n)return{rule:o}}}s(ur,"findDeniedEdgeDecision");async function Kt(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let a=Gt(r.rules,o,i);if(!a)return;let c=e.mode,d=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,l={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:c,message:d,rule:a};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:l}),await e.recordAudit("layer.observedViolation",t,l),c==="hard")throw new q(n,t.intent,o,i,d)}s(Kt,"assertObservedLayerFlowAllowed");async function Ft(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof P&&(e.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:o.violations}}),await e.recordAudit("policy.hardViolation",t,{violations:o.violations})),o}r.softViolations.length>0&&(e.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:r.softViolations}}),await e.recordAudit("policy.softViolation",t,{violations:r.softViolations}),e.onSoftViolation&&await e.safeHook(()=>e.onSoftViolation(r,t),"onSoftViolation",t))}s(Ft,"enforcePublishPolicy");function pr(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}s(pr,"appendHistory");function Q(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}s(Q,"appendTrace");async function ue(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){Q(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}s(ue,"recordAudit");async function jt(t,e){let n={intent:e.intent,source:e.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};Q(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await ue(t,"event.rawPublish",e,n)}s(jt,"recordRawPublishDiagnostic");async function Bt(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return pr(t,o),await t.eventBuffer?.enqueue(e,r),Q(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await ue(t,"event.published",e,{subscribersNotified:n}),o}s(Bt,"recordSuccessfulPublish");function je(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}s(je,"enrichMetadata");var Ht=0;function fr(){return Ht+=1,`interceptor-${Date.now()}-${Ht}`}s(fr,"nextInterceptorRegistrationId");var X=class{static{s(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new C(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Me)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new U;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Le({intentRegistry:e.intentRegistry,dependencyGraph:e.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(e,n,r,o){await this.dispatch(e,n,r,o)}async dispatch(e,n,r,o={}){let i=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,d,l=typeof e!="function";if(l){let f=e,m=r??n??{};d={...f,metadata:je(f.metadata,m,this.recording.instanceId)}}else{let f=e,m=n,h=r??{},u=f(m);d={...u,metadata:je(u.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await jt(this.recording,d),z(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Pt(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),J(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await xt(d,{interceptorsForIntent:s(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,m,h)=>this.recordAudit(f,m,h),"recordAudit")}),J(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Kt(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,m,h)=>this.recordAudit(f,m,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let p=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await Ft(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,m,h)=>this.recordAudit(f,m,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((f,m,h)=>this.safeHook(f,m,h),"safeHook")}),await Bt(this.recording,d,i?p.length:0,o.tx);let y=(async()=>{i&&await Promise.all(p.map(f=>this.invokeHandler(f,d))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(d),"onPublish",d)})();return a?await y:y.then(void 0,()=>{}),d}createPublisher(e){let n=typeof e=="string"?e:e.name;return z(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:s(async(r,o,i={},a)=>{if(i.source&&i.source!==n)throw new b(n,i.source);await this.publish(r,o,{...i,source:n},a)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;z(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let d=c.indexOf(o);d>=0&&c.splice(d,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(e,n,r){let o=typeof e=="string"?e:e.name;z(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:fr(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let a=this.interceptorsByIntent.get(o)??[];return a.push(i),this.interceptorsByIntent.set(o,a),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){Q(this.recording,e)}async recordAudit(e,n,r){await ue(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function mr(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}s(mr,"formatStandardSchemaPath");function gr(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}s(gr,"actualType");function yr(t,e){return t?`${t}.${e}`:e}s(yr,"formatPath");function Vt(t,e,n,r,o){let i=gr(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(a=>Object.is(a,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Ut(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{Vt(a,e.items,`${n}[${c}]`,r,o)})}s(Vt,"validateSchemaField");function Ut(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=yr(o,i),d=t[i];if(d===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}Vt(d,a,c,n,r)}}s(Ut,"validateObjectSchema");var pe=class{static{s(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Ut(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(i))r.schema[a]||o.push({intent:e.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(e.payload);if(a instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let c of a.issues)o.push({intent:e.intent,version:r.version,field:mr(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(e,n){return`${e}@${n}`}};function Be(){return new pe}s(Be,"createEventContractRegistry");var fe=class{static{s(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
7
+ ${n}`),this.name="PolicyViolationError",this.violations=e}};var C=class{static{s(this,"PolicyEngine")}policies=[];constructor(e=[]){for(let n of e)this.add(n)}add(e){if(this.policies.some(n=>n.name===e.name))throw new Error(`Policy "${e.name}" is already registered in this engine.`);this.policies.push(e)}getPolicies(){return[...this.policies]}evaluate(e){let n=[];for(let i of this.policies){let a=i.check(e);if(a!==!0){if(a===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(a))for(let c of a)n.push({policyName:i.name,severity:i.severity,message:c.message,details:c.details});else n.push({policyName:i.name,severity:i.severity,message:a.message,details:a.details})}}let r=n.filter(i=>i.severity==="hard"),o=n.filter(i=>i.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(e){let n=this.evaluate(e);if(n.hardViolations.length>0)throw new P(n.hardViolations);return n}clear(){this.policies.length=0}};function le(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}s(le,"definePolicy");function sr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(sr,"defaultLayerOf");function St(t,e){return e.resolveLayer?.(t)??sr(t)}s(St,"resolveLayer");function ar(t,e,n){return t===n.from&&e===n.to}s(ar,"matchesRule");function vt(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return le({name:e,severity:n,tags:["layer"],check:s(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],i=[];for(let a of o){let c=St(a.from,t),d=St(a.to,t);for(let l of t.rules)!l.allowed&&ar(c,d,l)&&i.push({policyName:e,severity:n,message:l.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${d})`})}return i.length>0?i:!0},"check")})}s(vt,"defineLayerPolicy");function $e(t){return t.tags?.includes("layer")??!1}s($e,"isLayerPolicy");function Me(t,e={}){return vt({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}s(Me,"defineArchitectureProfilePolicy");function Le(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Le,"buildPublishPolicyContext");var H=class extends Error{static{s(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},V=class extends Error{static{s(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},U=class extends Error{static{s(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},W=class extends Error{static{s(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},O=class extends Error{static{s(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},b=class extends Error{static{s(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},q=class extends Error{static{s(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}};var Pt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ke(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Pt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Pt.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}s(Ke,"validateIntentName");function z(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ke(t);if(!n.valid)throw new V(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new H(t)}}s(z,"assertIntentAllowed");function bt(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new O(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new O(t.intent,t.metadata.source)}}s(bt,"assertSourceAllowed");function J(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new W(t.intent,n.issues)}s(J,"assertContractAllowed");function N(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}s(N,"isPlainRecord");function D(t){return Array.isArray(t)?t.map(D):N(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,D(n)])):t}s(D,"clonePatchValue");function Ge(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=D(i);continue}if(N(r[o])&&N(i)){r[o]=Ge(r[o],i,a);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=je(r[o],i,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}s(Ge,"mergeRecordPatch");function je(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let a=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=D(o);return}if(N(r[i])&&N(o)){r[i]=Ge(r[i],o,a);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=je(r[i],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}s(je,"mergeArrayPatch");function xt(t,e){if(Array.isArray(e)){if(t===void 0)return D(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return je(t,e)}if(t===void 0)return D(e);if(!N(t))throw new Error("Object interceptor patch requires an object payload.");return Ge(t,e)}s(xt,"applyPayloadPatch");async function Ct(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:s(d=>{i.push(d)},"intercept")})),i.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let d of i)c={...c,payload:xt(c.payload,d),metadata:{...c.metadata}};J(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=a,e.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(a){await cr(o,r,a,e)}}return r}s(Ct,"applyInterceptors");async function cr(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}s(cr,"recordInterceptorError");var Ot=new Map;function Nt(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}s(Nt,"escapeLiteral");function Lt(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}s(Lt,"normalizeGlobSeparators");function dr(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}s(dr,"bracesBalanced");function Dt(t){let e=Ot.get(t);if(e)return e;let n=Lt(t),r=dr(n),o="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(o+=Nt(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":d==="?"?o+="[^/]":d==="{"&&r?(o+="(?:",i+=1):d==="}"&&r&&i>0?(o+=")",i-=1):d===","&&r&&i>0?o+="|":o+=Nt(d)}let a=new RegExp(`^${o}$`);return Ot.set(t,a),a}s(Dt,"globToRegExp");function Tt(t,e){if(!e?.length)return;let n=String(t).split(/[/\\]/).filter(Boolean),r=new Set(e.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}s(Tt,"sliceIdForPath");function lr(t){let e=new Set;for(let n of t??[]){let o=Lt(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let a=o[i];if((a==="**"||a==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}s(lr,"inferSliceFoldersFromPatterns");function ur(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return lr(r?.patterns)}s(ur,"resolveSliceFolders");function _t(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}s(_t,"normalizeSegments");function Kt(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}s(Kt,"trimTrailingSlashes");var pr=["src","app"];function fr(t){let e=Kt(t.replace(/^[./]+/,""));return e==="*"||e==="**"}s(fr,"isBlanketRoot");function $t(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=_t(n);for(let i of e){if(typeof i!="string"||i.length===0||fr(i))continue;if(i.includes("*")){let d=Kt(i.toLowerCase());if(Dt(d).test(r)||Dt(`${d}/**`).test(r))return!0;continue}let a=_t(i);if(a.length===0)continue;let c=pr.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let d of c){if(d+a.length>o.length)continue;let l=!0;for(let p=0;p<a.length;p+=1)if(o[d+p]!==a[p]){l=!1;break}if(l)return!0}}return!1}s($t,"pathUnderSharedRoot");function Mt(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}s(Mt,"sliceMatchesDeclaration");function gr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Mt(r.from,e)&&Mt(r.to,n))}s(gr,"crossSliceEdgeAllowed");function mr(t){if(!t.fromPath||!t.toPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0,n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}s(mr,"peerIsolationDecision");function Gt(t,e,n,r){return yr(t,e,n,r)?.rule}s(Gt,"findDeniedEdgeRule");function yr(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,a=r?.toPath,c=ur(o,e,r?.layers),d=i&&a?Tt(i,c):void 0,l=i&&a?Tt(a,c):void 0,p=mr({fromPath:i,toPath:a,folderCount:c.length,fromSlice:d,toSlice:l,fromShared:!d&&$t(i,o.sharedRoots),toShared:!l&&$t(a,o.sharedRoots),crossSliceAllowed:gr(o.allowedCrossSlice,d,l)});if(p.denied)return{rule:o,peerIsolationReason:p.reason,fromSlice:d,toSlice:l};continue}if(e!==n)return{rule:o}}}s(yr,"findDeniedEdgeDecision");async function jt(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let a=Gt(r.rules,o,i);if(!a)return;let c=e.mode,d=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,l={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:c,message:d,rule:a};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:l}),await e.recordAudit("layer.observedViolation",t,l),c==="hard")throw new q(n,t.intent,o,i,d)}s(jt,"assertObservedLayerFlowAllowed");async function Ft(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof P&&(e.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:o.violations}}),await e.recordAudit("policy.hardViolation",t,{violations:o.violations})),o}r.softViolations.length>0&&(e.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:r.softViolations}}),await e.recordAudit("policy.softViolation",t,{violations:r.softViolations}),e.onSoftViolation&&await e.safeHook(()=>e.onSoftViolation(r,t),"onSoftViolation",t))}s(Ft,"enforcePublishPolicy");function hr(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}s(hr,"appendHistory");function Q(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}s(Q,"appendTrace");async function ue(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){Q(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}s(ue,"recordAudit");async function Bt(t,e){let n={intent:e.intent,source:e.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};Q(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await ue(t,"event.rawPublish",e,n)}s(Bt,"recordRawPublishDiagnostic");async function Ht(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return hr(t,o),await t.eventBuffer?.enqueue(e,r),Q(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await ue(t,"event.published",e,{subscribersNotified:n}),o}s(Ht,"recordSuccessfulPublish");function Fe(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}s(Fe,"enrichMetadata");var Vt=0;function kr(){return Vt+=1,`interceptor-${Date.now()}-${Vt}`}s(kr,"nextInterceptorRegistrationId");var X=class{static{s(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new C(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some($e)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new U;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Le({intentRegistry:e.intentRegistry,dependencyGraph:e.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(e,n,r,o){await this.dispatch(e,n,r,o)}async dispatch(e,n,r,o={}){let i=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,d,l=typeof e!="function";if(l){let f=e,g=r??n??{};d={...f,metadata:Fe(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,h=r??{},u=f(g);d={...u,metadata:Fe(u.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await Bt(this.recording,d),z(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),bt(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),J(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await Ct(d,{interceptorsForIntent:s(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),J(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await jt(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let p=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await Ft(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,h)=>this.recordAudit(f,g,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((f,g,h)=>this.safeHook(f,g,h),"safeHook")}),await Ht(this.recording,d,i?p.length:0,o.tx);let y=(async()=>{i&&await Promise.all(p.map(f=>this.invokeHandler(f,d))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(d),"onPublish",d)})();return a?await y:y.then(void 0,()=>{}),d}createPublisher(e){let n=typeof e=="string"?e:e.name;return z(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:s(async(r,o,i={},a)=>{if(i.source&&i.source!==n)throw new b(n,i.source);await this.publish(r,o,{...i,source:n},a)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;z(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let d=c.indexOf(o);d>=0&&c.splice(d,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(e,n,r){let o=typeof e=="string"?e:e.name;z(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:kr(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let a=this.interceptorsByIntent.get(o)??[];return a.push(i),this.interceptorsByIntent.set(o,a),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){Q(this.recording,e)}async recordAudit(e,n,r){await ue(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function Rr(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}s(Rr,"formatStandardSchemaPath");function Ar(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}s(Ar,"actualType");function wr(t,e){return t?`${t}.${e}`:e}s(wr,"formatPath");function Ut(t,e,n,r,o){let i=Ar(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(a=>Object.is(a,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Wt(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{Ut(a,e.items,`${n}[${c}]`,r,o)})}s(Ut,"validateSchemaField");function Wt(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=wr(o,i),d=t[i];if(d===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}Ut(d,a,c,n,r)}}s(Wt,"validateObjectSchema");var pe=class{static{s(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Wt(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(i))r.schema[a]||o.push({intent:e.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(e.payload);if(a instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let c of a.issues)o.push({intent:e.intent,version:r.version,field:Rr(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(e,n){return`${e}@${n}`}};function Be(){return new pe}s(Be,"createEventContractRegistry");var fe=class{static{s(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
8
8
  `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
9
9
  `}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(e+=` ${this.safeId(r)}
10
10
  `);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let a=e.resolveLayer(i)??"Unclassified",c=n.get(a)??[];c.push(i),n.set(a,c)}let r=`flowchart TD
@@ -15,4 +15,4 @@ ${n}`),this.name="PolicyViolationError",this.violations=e}};var C=class{static{s
15
15
  `;for(let i of o)r+=` ${this.safeId(i)}[${i}]
16
16
  `;r+=` end
17
17
  `}for(let i of this.edges){let a=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${a} ${this.safeId(i.to)}
18
- `}return r.trim()}detectViolations(e=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of e)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(e){this.nodes.has(e)||this.nodes.set(e,{id:e})}addEdge(e){this.edges.some(r=>r.from===e.from&&r.to===e.to&&r.kind===e.kind)||this.edges.push(e)}findSimpleCycles(){let e=new Map;for(let c of this.edges)e.has(c.from)||e.set(c.from,[]),e.get(c.from).push(c.to);let n=[],r=new Set,o=[],i=s(c=>{r.add(c),o.push(c);for(let d of e.get(c)||[])if(!r.has(d))i(d);else if(o.includes(d)){let l=o.indexOf(d),p=o.slice(l).concat(d);n.push(p)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function He(){return new fe}s(He,"createDependencyGraph");function Ve(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}s(Ve,"syncRegistryToGraph");var Z=class{static{s(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=s(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ni=new Z;function Ue(){return new Z}s(Ue,"createIntentRegistry");var T={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Wt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...T,default:[]},kernelRoots:{...T},managedLayers:{...T,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},qt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...T,default:[]},managedLayers:{...T,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...T,default:[]}}};var zt="1.3",Jt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Qt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],hr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function kr(){let t=[];for(let e of Qt)for(let n of Qt)e===n||hr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(kr,"createDefaultRules");var We=kr();var A={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},zi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Jt,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:Jt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:zt,default:zt},name:{type:"string",minLength:1},include:{...A,minItems:1,default:["src"]},exclude:{...A,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:We,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...A,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...A,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...A,minItems:1},exclude:A,intentPrefixes:A,description:{type:"string",minLength:1},forbiddenGlobals:A,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...A,minItems:1},sharedRoots:{...A,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...A,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...A,minItems:1}}},arkRun:Wt,arkOrder:qt}};function Rr(t){return t.endsWith(".")?t:`${t}.`}s(Rr,"normalizePrefix");function Ar(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}s(Ar,"byLongestPrefix");function Xt(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Rr)})),n=[...e].sort(Ar),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(a=>o.startsWith(a)))?.name}}}s(Xt,"createArchitectureProfile");var wr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],qe=Xt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:wr,rules:We.map(t=>({...t}))});var Zt="4.8.5";function Er(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Er,"policyId");var ze=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Je(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,a=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(g=>({name:g.name,dependencies:e.getDependencies(g.name),productions:e.getProductions(g.name)})):[],p=e?e.getAllRelationships():[],y=n?n.getPolicies().map(g=>({id:Er(g.name),name:g.name,severity:g.severity,tags:g.tags?[...g.tags]:void 0,owner:g.owner,version:g.version,rationale:g.rationale,enforcementMode:g.enforcementMode,deprecated:g.deprecated,replacedBy:g.replacedBy,description:g.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],m=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(g=>(g.emits?.length??0)>0||(g.consumes?.length??0)>0).map(g=>({entity:g.name,emits:g.emits,consumes:g.consumes})),u=a?a.list().map(g=>({name:g.name,sourceIntents:g.sourceIntents,checkpoint:a.getCheckpoint(g.name)})):[],E={schemaVersion:"1.0",version:Zt,exportedAt:new Date().toISOString(),intents:l,relationships:p,policies:y,entities:f,graph:m,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:u,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new ze(E)}s(Je,"createArkManifest");var me=class{static{s(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function Qe(){return new me}s(Qe,"createMetadataRegistry");function Xe(t){return`${t.from}->${t.to}`}s(Xe,"flowKey");function en(t){let e=new Set,n=[];for(let r of t){let o=Xe(r);e.has(o)||(e.add(o),n.push(r))}return n}s(en,"uniqueFlows");function tn(t,e){let n=new Set(e.map(Xe));return t.filter(r=>!n.has(Xe(r)))}s(tn,"difference");function Ze(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})),a=n?.getHistory().map(u=>({from:u.event.metadata.source,to:u.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="observed").map(u=>({from:u.from,to:u.to})),d=en([...o,...i]),l=en([...a,...c]),p=l.filter(u=>!u.from||u.from==="unknown"),y=e?Array.from(new Set(l.map(u=>u.from).filter(u=>u&&u!=="unknown"&&!e.has(u)))):[],f=e?Array.from(new Set(l.map(u=>u.to).filter(u=>!e.has(u)))):[],m=new Set(l.flatMap(u=>[u.from,u.to])),h=e?e.list().map(u=>u.name).filter(u=>!m.has(u)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:tn(d,l),observedButUndeclared:tn(l.filter(u=>u.from!=="unknown"),d),unknownSources:p,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}s(Ze,"createObservabilityReporter");var nn=0;function Sr(){return nn+=1,`outbox-${Date.now()}-${nn}`}s(Sr,"nextOutboxId");function rn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(rn,"cloneRecord");var Y=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Sr(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),rn(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(rn)}async clear(){this.records.clear()}};var ge=class{static{s(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function vr(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(vr,"initialState");var ye=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new ge,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??vr(r),i=await r.project(e,o);await this.store.save(r.name,i);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function Ye(t){return new ye(t)}s(Ye,"createProjectionRegistry");var on=0;function Pr(t){return on+=1,`${t}-${Date.now()}-${on}`}s(Pr,"createWorkflowId");function et(t){return t instanceof Error?t.message:String(t)}s(et,"errorMessage");function br(t){return new Promise(e=>{setTimeout(e,t)})}s(br,"sleep");async function xr(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((a,c)=>{o=setTimeout(()=>{let d=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(d),c(d)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}s(xr,"withTimeout");var he=class{static{s(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let a=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||a){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},tt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new he}bus;options;static{s(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),a={id:r.id??Pr(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:e}),this.executeSnapshot(a,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=et(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let a=1;a<=i;a+=1){e.attempts[n.name]=a,await this.store.save(e,r);let c;try{c=await xr(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await br(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:a,error:et(d)}),d}c&&Object.assign(e.context,c),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(a=>e.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let c=i[a];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(d){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:et(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function nt(t,e){return new tt(t,e)}s(nt,"createWorkflowEngine");L();var Cr=new Set(["singleton","transient"]);function sn(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}s(sn,"cloneComponent");function Or(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Cr.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(Or,"closedLifetime");function an(){let t=new Map,e=new Map,n=new Set;function r(a){let c=t.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}s(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,c){if(e.has(a))return e.get(a);let d=o(a,c);return e.set(a,d),d}return s(i,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let d=Or(a.lifetime),l=Ee({id:c,lifetime:d,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let p=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:p}),sn(l)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):i(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,c)},snapshotComponents(){return[...t.values()].map(a=>sn(a.component))}}}s(an,"createComponentRegistry");ae();async function ln(t,e={}){let n=De({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(dn(),cn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(ln,"startArkRunInspector");oe();function _r(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new b(t.source,e.source);return e.source=t.source,e}s(_r,"stampMetadata");function Lr(){}s(Lr,"ignoreDetachedFailure");async function rt(t,e,n,r={}){let o=yt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=_r(r),a=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(a));o.awaitHandoff?await c:c.then(void 0,Lr)}return o}s(rt,"sendOnArkRunTransport");var Gr=1e3,un=0;function Kr(){return un+=1,`ark-kernel-${Date.now()}-${un}`}s(Kr,"nextKernelInstanceId");function pn(t={}){let e=t.strict??!0,n=t.instanceId??Kr(),r=t.profile??qe,o=t.maxHistorySize??Gr,i=Ue(),a=He(),c=t.metadata??Qe(),d=t.auditTrail??$e({maxRecords:o}),l=t.eventContracts??Be(),p=t.eventBuffer??t.outbox??new Y,y=t.projections??Ye({auditTrail:d}),f=new C([_e(r),...t.policies??[]]),m=s(()=>{Ve(i,a,{requireRegisteredTargets:!0})},"syncGraph"),h=t.ephemeral??!0,u=t.broker,E=new X({intentRegistry:i,dependencyGraph:a,policyEngine:f,strictRegistry:!0,validateIntentNaming:!0,auditTrail:d,eventContracts:l,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await y.apply(k)}}),g=nt(E,{auditTrail:d}),Re=Ze({registry:i,eventBus:E,graph:a}),x=an(),fn=typeof u?.send=="function",ot={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:d,eventContracts:l,eventBuffer:p,outbox:p,projections:y,policyEngine:f,eventBus:E,workflowEngine:g,observability:Re,publisher(k){let $=E.createPublisher(k);return{source:$.source,publish:$.publish,send(Ae,mn,gn={}){return rt({eventBus:E,broker:u,defaultEphemeral:h},Ae,mn,{...gn,source:$.source})}}},send(k,$,Ae={}){return rt({eventBus:E,broker:u,defaultEphemeral:h},k,$,Ae)},register(k){return x.register(k)},resolve(k){return x.resolve(k)},resolveSingleton(k){return x.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:x.snapshotComponents()})},requestGraph(k){return gt({kernelInstanceId:n,components:x.snapshotComponents()},k)},getInspectorSnapshot(k){return wt({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:x.snapshotComponents()},observability:Re.report(),ephemeralDefault:h,brokerBound:fn})},startInspector(k){return ln(ot,k)},syncGraph:m,manifest(){return m(),Je({registry:i,policyEngine:f,metadata:c,graph:a,profile:r,projections:y,eventContracts:l,observability:Re})}};return ot}s(pn,"createArkKernel");var ee=Symbol("ARK_KERNEL"),Sa=s(()=>Fr(ee),"InjectArk"),S=class{static forRoot(e){let n=e&&"registry"in e?e:pn(e);return{module:S,global:!0,providers:[{provide:ee,useValue:n}],exports:[ee]}}static forRootAsync(e){return{module:S,global:!0,providers:[{provide:ee,useFactory:e.useFactory,inject:e.inject??[]}],exports:[ee]}}};s(S,"ArkModule"),S=it([jr({})],S);export{ee as ARK_KERNEL,S as ArkModule,Sa as InjectArk};
18
+ `}return r.trim()}detectViolations(e=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of e)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(e){this.nodes.has(e)||this.nodes.set(e,{id:e})}addEdge(e){this.edges.some(r=>r.from===e.from&&r.to===e.to&&r.kind===e.kind)||this.edges.push(e)}findSimpleCycles(){let e=new Map;for(let c of this.edges)e.has(c.from)||e.set(c.from,[]),e.get(c.from).push(c.to);let n=[],r=new Set,o=[],i=s(c=>{r.add(c),o.push(c);for(let d of e.get(c)||[])if(!r.has(d))i(d);else if(o.includes(d)){let l=o.indexOf(d),p=o.slice(l).concat(d);n.push(p)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function He(){return new fe}s(He,"createDependencyGraph");function Ve(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}s(Ve,"syncRegistryToGraph");var Z=class{static{s(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=s(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Mi=new Z;function Ue(){return new Z}s(Ue,"createIntentRegistry");var T={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},qt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...T,default:[]},kernelRoots:{...T},managedLayers:{...T,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},zt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...T,default:[]},managedLayers:{...T,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...T,default:[]}}};var Jt="1.3",Qt="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Xt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Ir=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Er(){let t=[];for(let e of Xt)for(let n of Xt)e===n||Ir.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(Er,"createDefaultRules");var We=Er();var A={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Qt,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:Qt,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:Jt,default:Jt},name:{type:"string",minLength:1},include:{...A,minItems:1,default:["src"]},exclude:{...A,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:We,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...A,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...A,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...A,minItems:1},exclude:A,intentPrefixes:A,description:{type:"string",minLength:1},forbiddenGlobals:A,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...A,minItems:1},sharedRoots:{...A,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget; coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant.",properties:{testGlobs:{...A,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...A,minItems:1}}},arkRun:qt,arkOrder:zt}};function Sr(t){return t.endsWith(".")?t:`${t}.`}s(Sr,"normalizePrefix");function vr(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}s(vr,"byLongestPrefix");function Zt(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Sr)})),n=[...e].sort(vr),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(a=>o.startsWith(a)))?.name}}}s(Zt,"createArchitectureProfile");var Pr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],qe=Zt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Pr,rules:We.map(t=>({...t}))});var Yt="4.8.6";function xr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(xr,"policyId");var ze=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Je(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,a=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],p=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:xr(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),u=a?a.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:a.getCheckpoint(m.name)})):[],E={schemaVersion:"1.0",version:Yt,exportedAt:new Date().toISOString(),intents:l,relationships:p,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:u,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new ze(E)}s(Je,"createArkManifest");var ge=class{static{s(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function Qe(){return new ge}s(Qe,"createMetadataRegistry");function Xe(t){return`${t.from}->${t.to}`}s(Xe,"flowKey");function tn(t){let e=new Set,n=[];for(let r of t){let o=Xe(r);e.has(o)||(e.add(o),n.push(r))}return n}s(tn,"uniqueFlows");function nn(t,e){let n=new Set(e.map(Xe));return t.filter(r=>!n.has(Xe(r)))}s(nn,"difference");function Ze(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})),a=n?.getHistory().map(u=>({from:u.event.metadata.source,to:u.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="observed").map(u=>({from:u.from,to:u.to})),d=tn([...o,...i]),l=tn([...a,...c]),p=l.filter(u=>!u.from||u.from==="unknown"),y=e?Array.from(new Set(l.map(u=>u.from).filter(u=>u&&u!=="unknown"&&!e.has(u)))):[],f=e?Array.from(new Set(l.map(u=>u.to).filter(u=>!e.has(u)))):[],g=new Set(l.flatMap(u=>[u.from,u.to])),h=e?e.list().map(u=>u.name).filter(u=>!g.has(u)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:nn(d,l),observedButUndeclared:nn(l.filter(u=>u.from!=="unknown"),d),unknownSources:p,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}s(Ze,"createObservabilityReporter");var rn=0;function Cr(){return rn+=1,`outbox-${Date.now()}-${rn}`}s(Cr,"nextOutboxId");function on(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(on,"cloneRecord");var Y=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Cr(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),on(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(on)}async clear(){this.records.clear()}};var me=class{static{s(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function Or(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(Or,"initialState");var ye=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new me,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??Or(r),i=await r.project(e,o);await this.store.save(r.name,i);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function Ye(t){return new ye(t)}s(Ye,"createProjectionRegistry");var sn=0;function Nr(t){return sn+=1,`${t}-${Date.now()}-${sn}`}s(Nr,"createWorkflowId");function et(t){return t instanceof Error?t.message:String(t)}s(et,"errorMessage");function Dr(t){return new Promise(e=>{setTimeout(e,t)})}s(Dr,"sleep");async function Tr(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((a,c)=>{o=setTimeout(()=>{let d=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(d),c(d)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}s(Tr,"withTimeout");var he=class{static{s(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let a=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||a){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},tt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new he}bus;options;static{s(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),a={id:r.id??Nr(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:e}),this.executeSnapshot(a,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=et(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let a=1;a<=i;a+=1){e.attempts[n.name]=a,await this.store.save(e,r);let c;try{c=await Tr(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await Dr(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:a,error:et(d)}),d}c&&Object.assign(e.context,c),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(a=>e.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let c=i[a];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(d){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:et(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function nt(t,e){return new tt(t,e)}s(nt,"createWorkflowEngine");L();var _r=new Set(["singleton","transient"]);function an(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}s(an,"cloneComponent");function $r(t){if(t===void 0)return"singleton";if(typeof t=="string"&&_r.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s($r,"closedLifetime");function cn(){let t=new Map,e=new Map,n=new Set;function r(a){let c=t.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}s(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,c){if(e.has(a))return e.get(a);let d=o(a,c);return e.set(a,d),d}return s(i,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let d=$r(a.lifetime),l=Ee({id:c,lifetime:d,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let p=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:p}),an(l)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):i(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,c)},snapshotComponents(){return[...t.values()].map(a=>an(a.component))}}}s(cn,"createComponentRegistry");ae();async function un(t,e={}){let n=De({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ln(),dn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(un,"startArkRunInspector");oe();function Fr(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new b(t.source,e.source);return e.source=t.source,e}s(Fr,"stampMetadata");function Br(){}s(Br,"ignoreDetachedFailure");async function rt(t,e,n,r={}){let o=ht({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Fr(r),a=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(a));o.awaitHandoff?await c:c.then(void 0,Br)}return o}s(rt,"sendOnArkRunTransport");var Hr=1e3,pn=0;function Vr(){return pn+=1,`ark-kernel-${Date.now()}-${pn}`}s(Vr,"nextKernelInstanceId");function fn(t={}){let e=t.strict??!0,n=t.instanceId??Vr(),r=t.profile??qe,o=t.maxHistorySize??Hr,i=Ue(),a=He(),c=t.metadata??Qe(),d=t.auditTrail??_e({maxRecords:o}),l=t.eventContracts??Be(),p=t.eventBuffer??t.outbox??new Y,y=t.projections??Ye({auditTrail:d}),f=new C([Me(r),...t.policies??[]]),g=s(()=>{Ve(i,a,{requireRegisteredTargets:!0})},"syncGraph"),h=t.ephemeral??!0,u=t.broker,E=new X({intentRegistry:i,dependencyGraph:a,policyEngine:f,strictRegistry:!0,validateIntentNaming:!0,auditTrail:d,eventContracts:l,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:p,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await y.apply(k)}}),m=nt(E,{auditTrail:d}),Re=Ze({registry:i,eventBus:E,graph:a}),x=cn(),gn=typeof u?.send=="function",ot={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:d,eventContracts:l,eventBuffer:p,outbox:p,projections:y,policyEngine:f,eventBus:E,workflowEngine:m,observability:Re,publisher(k){let _=E.createPublisher(k);return{source:_.source,publish:_.publish,send(Ae,mn,yn={}){return rt({eventBus:E,broker:u,defaultEphemeral:h},Ae,mn,{...yn,source:_.source})}}},send(k,_,Ae={}){return rt({eventBus:E,broker:u,defaultEphemeral:h},k,_,Ae)},register(k){return x.register(k)},resolve(k){return x.resolve(k)},resolveSingleton(k){return x.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:x.snapshotComponents()})},requestGraph(k){return yt({kernelInstanceId:n,components:x.snapshotComponents()},k)},getInspectorSnapshot(k){return It({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:x.snapshotComponents()},observability:Re.report(),ephemeralDefault:h,brokerBound:gn})},startInspector(k){return un(ot,k)},syncGraph:g,manifest(){return g(),Je({registry:i,policyEngine:f,metadata:c,graph:a,profile:r,projections:y,eventContracts:l,observability:Re})}};return ot}s(fn,"createArkKernel");var ee=Symbol("ARK_KERNEL"),Ca=s(()=>Ur(ee),"InjectArk"),S=class{static forRoot(e){let n=e&&"registry"in e?e:fn(e);return{module:S,global:!0,providers:[{provide:ee,useValue:n}],exports:[ee]}}static forRootAsync(e){return{module:S,global:!0,providers:[{provide:ee,useFactory:e.useFactory,inject:e.inject??[]}],exports:[ee]}}};s(S,"ArkModule"),S=it([Wr({})],S);export{ee as ARK_KERNEL,S as ArkModule,Ca as InjectArk};
@@ -1 +1 @@
1
- "use strict";var g=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});var P=(e,r)=>{for(var t in r)g(e,t,{get:r[t],enumerable:!0})},X=(e,r,t,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of _(r))!b.call(e,n)&&n!==t&&g(e,n,{get:()=>r[n],enumerable:!(a=k(r,n))||a.enumerable});return e};var K=e=>X(g({},"__esModule",{value:!0}),e);var F={};P(F,{ArkOrderError:()=>s,DEFAULT_MAX_XI_KEYS:()=>m,createOrderPlane:()=>S});module.exports=K(F);var s=class extends Error{static{i(this,"ArkOrderError")}code;constructor(r,t){super(t),this.name="ArkOrderError",this.code=r}};var m=7;function E(e){let r=2166136261;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return`fnv1a-${(r>>>0).toString(16).padStart(8,"0")}`}i(E,"deterministicHash");function f(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(f).join(",")}]`;let r=e;return`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${f(r[t])}`).join(",")}}`}i(f,"stableSerialize");var T=["update","patch","set","mutate"];function h(e){return T.includes(e)}i(h,"isForbiddenPlaneMethod");function j(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}i(j,"isPrimitive");function O(e,r){let t=Object.keys(e);if(t.length===0&&r==="\u03BE")throw new s("ARKORDER_EMPTY_XI","\u03BE must name at least one slow mode");let a={};for(let n of t.sort()){let o=e[n];if(!j(o))throw new s("ARKORDER_NESTED_XI",`${r} key ${JSON.stringify(n)} is not a slow primitive (nested values are microstate)`);a[n]=o}return Object.freeze(a)}i(O,"freezeRecord");function I(e,r){let t=Object.keys(e).length;if(t===0)throw new s("ARKORDER_EMPTY_XI","\u03BE must name at least one slow mode");if(t>r)throw new s("ARKORDER_TOO_MANY_PARAMS",`\u03BE has ${t} keys; maxXiKeys is ${r} (Haken: few slow modes)`)}i(I,"assertXiKeyCap");function D(e,r){if(!r)return;let t=r.properties??{},a=r.additionalProperties!==!1;for(let n of Object.keys(e)){let o=t[n];if(!o){if(!a)throw new s("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(n)} is not in xiSchema.properties`);continue}if(o.enum&&!o.enum.some(l=>l===e[n]))throw new s("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(n)} value is not in enum`);if(o.type==="null"&&e[n]!==null)throw new s("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(n)} must be null`);if(o.type&&o.type!=="null"&&typeof e[n]!==o.type)throw new s("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(n)} must be ${o.type}`)}}i(D,"assertXiSchema");function v(e,r){return E(f({xi:e,sigma:r}))}i(v,"hashReleasePayload");function u(e){I(e.xi,e.maxXiKeys);let r=O(e.xi,"\u03BE");C(r),D(r,e.xiSchema);let t=O(e.sigma??{},"\u03C3");return Object.freeze({version:e.version,hash:v(r,t),xi:r,sigma:t,releasedAt:e.now})}i(u,"createFrozenRelease");var M=/^(ttl|freshUntil|fresh_until|maxAge|max_age)$/i;function C(e){for(let r of Object.keys(e))if(M.test(r))throw new s("ARKORDER_XI_TTL",`\u03BE key ${JSON.stringify(r)} is a freshness field; TTL belongs on \u03C3, never on \u03BE`)}i(C,"assertXiHasNoTtl");function y(e,r){if(!r||r.cannotObserve.length===0)return;let t=new Set(r.cannotObserve);for(let a of e.allowedKinds)if(t.has(a))throw new s("ARKORDER_INFORMATION_BUDGET",`projection allows ${JSON.stringify(a)}; informationBudget.cannotObserve forbids it`)}i(y,"assertInformationBudget");function A(e){if(e.maxAgeMs===void 0)return;let r=e.sigma.freshUntil;if(typeof r=="number"){if(e.now>r)throw new s("ARKORDER_STALE_SIGMA","\u03C3 freshUntil has elapsed; \u03BE does not TTL");return}let t=typeof e.sigma.releasedAt=="number"?e.sigma.releasedAt:e.releasedAt;if(typeof t=="number"&&e.now-t>e.maxAgeMs)throw new s("ARKORDER_STALE_SIGMA","\u03C3 is older than sigmaMaxAgeMs; \u03BE does not TTL")}i(A,"assertSigmaFresh");function x(e,r,t=[]){let a=r.kind;for(let n of t)if(n.escalateKinds?.includes(a)){let o=n.escalateTarget??"human";return{kind:"escalate",event:r,reason:`pack ${n.id} slaves kind ${JSON.stringify(a)} to a pattern change`,target:o}}return e.allowedKinds.includes(a)?{kind:"absorb",event:r}:{kind:"escalate",event:r,reason:`kind ${JSON.stringify(a)} is not allowed by h(\u03BE); field cannot rewrite the pattern`,target:"human"}}i(x,"classifyIngest");function N(e,r){let t=new Set(e.allowedKinds),a=new Set(r.allowedKinds),n=new Set;for(let o of t)a.has(o)||n.add(o);for(let o of a)t.has(o)||n.add(o);for(let o of r.invalidated)n.add(o);return{blastRadius:[...n].sort(),invalidations:[...r.invalidated].sort()}}i(N,"blastRadiusOf");function w(e){let r={...e.current.xi};for(let[R,c]of Object.entries(e.delta)){if(c===void 0){delete r[R];continue}r[R]=c}let t=u({xi:r,sigma:{...e.current.sigma},version:e.current.version+1,now:e.now,maxXiKeys:e.maxXiKeys,xiSchema:e.xiSchema});if(t.hash===e.current.hash)throw new s("ARKORDER_EMPTY_BLAST","delta does not change \u03BE; that is not a pattern change");let a=e.projector(e.current,e.current.sigma),n=e.projector(t,t.sigma),{blastRadius:o,invalidations:l}=N(a,n);if(o.length===0)throw new s("ARKORDER_EMPTY_BLAST","pattern change has empty blast radius; that key is not an order parameter");return{nextXi:t.xi,blastRadius:o,invalidations:l}}i(w,"proposePatternChange");function S(e){if(typeof e?.projector!="function")throw new s("ARKORDER_SCHEMA","createOrderPlane requires a consumer projector h(\u03BE)");let r=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7,t=e.packs??[],a=e.clocks??{now(){return 0}},n=null,o=0;function l(){if(!n)throw new s("ARKORDER_NO_RELEASE","no pattern is frozen; call release(\u03BE) first");return n}i(l,"requireCurrent");let R={release(c,d){return o+=1,n=u({xi:c,sigma:d,version:o,now:a.now(),maxXiKeys:r,xiSchema:e.xiSchema}),n},project(){let c=l(),d=e.projector(c,c.sigma);return y(d,e.informationBudget),d},ingest(c){let d=l();A({sigma:d.sigma,now:a.now(),maxAgeMs:e.sigmaMaxAgeMs,releasedAt:d.releasedAt});let p=e.projector(d,d.sigma);return y(p,e.informationBudget),x(p,c,t)},proposeRelease(c){return w({current:l(),delta:c,projector:e.projector,maxXiKeys:r,xiSchema:e.xiSchema,now:a.now()})},current(){return n}};for(let c of["update","patch","set","mutate"])Object.defineProperty(R,c,{enumerable:!1,configurable:!1,get(){throw new s("ARKORDER_FORBIDDEN_METHOD",`${c}() is not a Haken operation; freeze a pattern with release() or proposeRelease()`)}});return Object.freeze(R)}i(S,"createOrderPlane");0&&(module.exports={ArkOrderError,DEFAULT_MAX_XI_KEYS,createOrderPlane});
1
+ "use strict";var x=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var n=(e,r)=>x(e,"name",{value:r,configurable:!0});var z=(e,r)=>{for(var t in r)x(e,t,{get:r[t],enumerable:!0})},J=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Y(r))!U.call(e,o)&&o!==t&&x(e,o,{get:()=>r[o],enumerable:!(s=$(r,o))||s.enumerable});return e};var G=e=>J(x({},"__esModule",{value:!0}),e);var ie={};z(ie,{ArkOrderError:()=>i,CAPACITY_OPS:()=>S,DEFAULT_MAX_XI_KEYS:()=>m,createMemoryReleaseStore:()=>B,createOrderPlane:()=>F,ingestTravelAction:()=>I});module.exports=G(ie);var i=class extends Error{static{n(this,"ArkOrderError")}code;constructor(r,t){super(t),this.name="ArkOrderError",this.code=r}};var m=7;var S=["lte","lt","gte","gt"];function u(e){let r=2166136261;for(let t=0;t<e.length;t+=1)r^=e.charCodeAt(t),r=Math.imul(r,16777619);return`fnv1a-${(r>>>0).toString(16).padStart(8,"0")}`}n(u,"deterministicHash");function R(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(R).join(",")}]`;let r=e;return`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${R(r[t])}`).join(",")}}`}n(R,"stableSerialize");function I(e){return e.kind==="absorb"?"send":e.kind==="escalate_up"&&e.target==="human"?"raises":"none"}n(I,"ingestTravelAction");var V=["update","patch","set","mutate"];function P(e){return V.includes(e)}n(P,"isForbiddenPlaneMethod");function q(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}n(q,"isPrimitive");function f(e,r){let t=Object.keys(e);if(t.length===0&&r==="\u03BE")throw new i("ARKORDER_EMPTY_XI","\u03BE must name at least one slow mode");let s={};for(let o of t.sort()){let a=e[o];if(!q(a))throw new i("ARKORDER_NESTED_XI",`${r} key ${JSON.stringify(o)} is not a slow primitive (nested values are microstate)`);s[o]=a}return Object.freeze(s)}n(f,"freezeRecord");function W(e,r){let t=Object.keys(e).length;if(t===0)throw new i("ARKORDER_EMPTY_XI","\u03BE must name at least one slow mode");if(t>r)throw new i("ARKORDER_TOO_MANY_PARAMS",`\u03BE has ${t} keys; maxXiKeys is ${r} (Haken: few slow modes)`)}n(W,"assertXiKeyCap");function Q(e,r){if(!r)return;let t=r.properties??{},s=r.additionalProperties!==!1;for(let o of Object.keys(e)){let a=t[o];if(!a){if(!s)throw new i("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(o)} is not in xiSchema.properties`);continue}if(a.enum&&!a.enum.some(l=>l===e[o]))throw new i("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(o)} value is not in enum`);if(a.type==="null"&&e[o]!==null)throw new i("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(o)} must be null`);if(a.type&&a.type!=="null"&&typeof e[o]!==a.type)throw new i("ARKORDER_SCHEMA",`\u03BE key ${JSON.stringify(o)} must be ${a.type}`)}}n(Q,"assertXiSchema");function D(e,r){if(typeof r=="string"&&Object.prototype.hasOwnProperty.call(e,"catalogReleaseId"))return r}n(D,"catalogDigestFor");function T(e,r,t){let s=D(e,t);return s!==void 0?u(R({xi:e,sigma:r,catalogDigest:s})):u(R({xi:e,sigma:r}))}n(T,"hashReleasePayload");function Z(e,r){let t=D(e,r);return t!==void 0?u(R({xi:e,catalogDigest:t})):u(R({xi:e}))}n(Z,"hashXiIdentity");function X(e){return u(R({sigma:e}))}n(X,"hashSigmaIdentity");function K(e,r){return R(e)===R(r)}n(K,"xiRecordsEqual");function C(e,r){if(e&&!K(e.xi,r))throw new i("ARKORDER_UNVALVED_RELEASE","\u03BE is frozen; change the pattern with proposeRelease then apply(ProposeResult)")}n(C,"assertUnvalvedRelease");function A(e){W(e.xi,e.maxXiKeys);let r=f(e.xi,"\u03BE");re(r),Q(r,e.xiSchema);let t=f(e.sigma??{},"\u03C3");return Object.freeze({version:e.version,hash:T(r,t,e.catalogDigest),xiHash:Z(r,e.catalogDigest),sigmaHash:X(t),xi:r,sigma:t,releasedAt:e.now})}n(A,"createFrozenRelease");function j(e){let r=f(e.sigma,"\u03C3");return Object.freeze({version:e.current.version,hash:T(e.current.xi,r,e.catalogDigest),xiHash:e.current.xiHash,sigmaHash:X(r),xi:e.current.xi,sigma:r,releasedAt:e.now})}n(j,"refreshSigmaRecord");var ee=/^(ttl|freshUntil|fresh_until|maxAge|max_age)$/i;function re(e){for(let r of Object.keys(e))if(ee.test(r))throw new i("ARKORDER_XI_TTL",`\u03BE key ${JSON.stringify(r)} is a freshness field; TTL belongs on \u03C3, never on \u03BE`)}n(re,"assertXiHasNoTtl");function O(e,r){if(!r||r.cannotObserve.length===0)return;let t=new Set(r.cannotObserve);for(let s of e.allowedKinds)if(t.has(s))throw new i("ARKORDER_INFORMATION_BUDGET",`projection allows ${JSON.stringify(s)}; informationBudget.cannotObserve forbids it`)}n(O,"assertInformationBudget");function v(e){if(e.maxAgeMs===void 0)return;let r=e.sigma.freshUntil;if(typeof r=="number"){if(e.now>r)throw new i("ARKORDER_STALE_SIGMA","\u03C3 freshUntil has elapsed; \u03BE does not TTL");return}let t=typeof e.sigma.releasedAt=="number"?e.sigma.releasedAt:e.releasedAt;if(typeof t=="number"&&e.now-t>e.maxAgeMs)throw new i("ARKORDER_STALE_SIGMA","\u03C3 is older than sigmaMaxAgeMs; \u03BE does not TTL")}n(v,"assertSigmaFresh");function k(e){return u(R({kind:e.kind,payload:e.payload??null}))}n(k,"fieldEventIdentity");function te(e,r){return{event:e,xiHash:r,eventId:k(e)}}n(te,"bindResidual");var ne=new Set(S);function oe(e){return typeof e=="string"&&ne.has(e)}n(oe,"isCapacityOp");function b(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}n(b,"numericLeaf");function ae(e,r,t){return r==="lte"?e<=t:r==="lt"?e<t:r==="gte"?e>=t:e>t}n(ae,"compareCapacity");function h(e){return typeof e=="function"?!0:e===null||typeof e!="object"?!1:Array.isArray(e)?e.some(h):Object.values(e).some(h)}n(h,"packHasFunction");function se(e,r,t){let s=t.capacity??[];for(let o of s){if(h(o)||!oe(o.op))return"pack";if(o.kind!==e.kind)continue;let a=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?b(e.payload[o.payloadKey]):void 0,l=b(r[o.sigmaKey]);if(a===void 0||l===void 0)return"pack";if(!ae(a,o.op,l))return"capacity"}return"ok"}n(se,"evaluateCapacity");function M(e,r,t=[],s="",o=Object.freeze({})){let a=r.kind,l=te(r,s);for(let d of t){if(h(d.capacity)||h(d.escalateKinds))return{...l,kind:"hold",reasonCode:"pack",reason:`pack ${d.id} is not data-only; user predicates are forbidden`};if(d.escalateKinds?.includes(a)){let p=d.escalateTarget??"human";return{...l,kind:"escalate_up",reasonCode:"pack",reason:`pack ${d.id} slaves kind ${JSON.stringify(a)} to a pattern change`,target:p}}}if(!e.allowedKinds.includes(a))return{...l,kind:"escalate_up",reasonCode:"not-in-pattern",reason:`kind ${JSON.stringify(a)} is not allowed by h(\u03BE); field cannot rewrite the pattern`,target:"human"};for(let d of t){let p=se(r,o,d);if(p!=="ok")return{...l,kind:"hold",reasonCode:p,reason:p==="capacity"?`pack ${d.id} capacity ${JSON.stringify(r.kind)} does not hold`:`pack ${d.id} capacity is not numeric data`}}return{...l,kind:"absorb"}}n(M,"classifyIngest");function N(e,r){let t=new Set(e.allowedKinds),s=new Set(r.allowedKinds),o=new Set;for(let a of t)s.has(a)||o.add(a);for(let a of s)t.has(a)||o.add(a);for(let a of r.invalidated)o.add(a);return{blastRadius:[...o].sort(),invalidations:[...r.invalidated].sort()}}n(N,"blastRadiusOf");function H(e){let r={...e.current.xi};for(let[d,p]of Object.entries(e.delta)){if(p===void 0){delete r[d];continue}r[d]=p}let t=A({xi:r,sigma:{...e.current.sigma},version:e.current.version+1,now:e.now,maxXiKeys:e.maxXiKeys,xiSchema:e.xiSchema,catalogDigest:e.catalogDigest});if(t.hash===e.current.hash)throw new i("ARKORDER_EMPTY_BLAST","delta does not change \u03BE; that is not a pattern change");let s=e.projector(e.current,e.current.sigma),o=e.projector(t,t.sigma),{blastRadius:a,invalidations:l}=N(s,o);if(a.length===0)throw new i("ARKORDER_EMPTY_BLAST","pattern change has empty blast radius; that key is not an order parameter");return{nextXi:t.xi,blastRadius:a,invalidations:l}}n(H,"proposePatternChange");function L(e){let r=A({xi:{...e.proposal.nextXi},sigma:{...e.current.sigma},version:e.current.version+1,now:e.now,maxXiKeys:e.maxXiKeys,xiSchema:e.xiSchema,catalogDigest:e.catalogDigest});if(K(r.xi,e.current.xi))throw new i("ARKORDER_EMPTY_BLAST","delta does not change \u03BE; that is not a pattern change");let t=e.projector(e.current,e.current.sigma),s=e.projector(r,r.sigma),{blastRadius:o}=N(t,s);if(o.length===0)throw new i("ARKORDER_EMPTY_BLAST","pattern change has empty blast radius; that key is not an order parameter");return r}n(L,"applyProposedRelease");function F(e){if(typeof e?.projector!="function")throw new i("ARKORDER_SCHEMA","createOrderPlane requires a consumer projector h(\u03BE)");let r=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7,t=e.packs??[],s=e.clocks??{now(){return 0}},o=e.store,a=o?.load()??null,l=a?.version??0,d=e.catalogDigest;function p(c){return a=c,l=c.version,o?.save(c),c}n(p,"persist");function y(){if(!a)throw new i("ARKORDER_NO_RELEASE","no pattern is frozen; call release(\u03BE) first");return a}n(y,"requireCurrent");let w={release(c,g){return a&&C(a,f(c,"\u03BE")),p(A({xi:c,sigma:g,version:l+1,now:s.now(),maxXiKeys:r,xiSchema:e.xiSchema,catalogDigest:d}))},project(){let c=y(),g=e.projector(c,c.sigma);return O(g,e.informationBudget),g},ingest(c){let g=y();try{v({sigma:g.sigma,now:s.now(),maxAgeMs:e.sigmaMaxAgeMs,releasedAt:g.releasedAt})}catch(E){if(E instanceof i&&E.code==="ARKORDER_STALE_SIGMA")return{kind:"hold",event:c,xiHash:g.xiHash,eventId:k(c),reasonCode:"stale-sigma",reason:E.message};throw E}let _=e.projector(g,g.sigma);return O(_,e.informationBudget),M(_,c,t,g.xiHash,g.sigma)},proposeRelease(c){return H({current:y(),delta:c,projector:e.projector,maxXiKeys:r,xiSchema:e.xiSchema,now:s.now(),catalogDigest:d})},apply(c){return p(L({current:y(),proposal:c,projector:e.projector,maxXiKeys:r,xiSchema:e.xiSchema,now:s.now(),catalogDigest:d}))},refreshSigma(c){return p(j({current:y(),sigma:c,now:s.now(),catalogDigest:d}))},current(){return a}};for(let c of["update","patch","set","mutate"])Object.defineProperty(w,c,{enumerable:!1,configurable:!1,get(){throw new i("ARKORDER_FORBIDDEN_METHOD",`${c}() is not a Haken operation; freeze a pattern with release() or proposeRelease()`)}});return Object.freeze(w)}n(F,"createOrderPlane");function B(e){let r=e??null;return{load(){return r},save(t){r=t}}}n(B,"createMemoryReleaseStore");0&&(module.exports={ArkOrderError,CAPACITY_OPS,DEFAULT_MAX_XI_KEYS,createMemoryReleaseStore,createOrderPlane,ingestTravelAction});
@@ -12,7 +12,12 @@ type FieldEvent = {
12
12
  };
13
13
  type Release = {
14
14
  readonly version: number;
15
+ /** Combined ξ+σ fingerprint. 4.8.x compatible when no catalog digest is mixed in. */
15
16
  readonly hash: string;
17
+ /** ξ identity. Saldo / clock refresh must not change this. */
18
+ readonly xiHash: string;
19
+ /** σ stamp. Independent of xiHash. */
20
+ readonly sigmaHash: string;
16
21
  readonly xi: XiRecord;
17
22
  readonly sigma: SigmaRecord;
18
23
  readonly releasedAt: number;
@@ -21,28 +26,54 @@ type Projection = {
21
26
  readonly allowedKinds: readonly string[];
22
27
  readonly invalidated: readonly string[];
23
28
  };
24
- type IngestAbsorb = {
25
- readonly kind: 'absorb';
26
- readonly event: FieldEvent;
27
- };
28
29
  type EscalationTarget = 'human' | 'scale' | 'hold';
29
- type IngestEscalate = {
30
- readonly kind: 'escalate';
30
+ declare const INGEST_REASON_CODES: readonly ["not-in-pattern", "stale-sigma", "pack", "capacity"];
31
+ type IngestReasonCode = (typeof INGEST_REASON_CODES)[number];
32
+ type IngestResidualBind = {
31
33
  readonly event: FieldEvent;
32
- readonly reason: string;
34
+ readonly xiHash: string;
35
+ readonly eventId: string;
36
+ };
37
+ type IngestAbsorb = IngestResidualBind & {
38
+ readonly kind: 'absorb';
39
+ };
40
+ type IngestHold = IngestResidualBind & {
41
+ readonly kind: 'hold';
42
+ readonly reasonCode: IngestReasonCode;
43
+ readonly reason?: string;
44
+ };
45
+ type IngestEscalateUp = IngestResidualBind & {
46
+ readonly kind: 'escalate_up';
47
+ readonly reasonCode: IngestReasonCode;
48
+ readonly reason?: string;
33
49
  readonly target: EscalationTarget;
50
+ readonly proposed_patch?: {
51
+ readonly nextXi: XiRecord;
52
+ };
34
53
  };
35
- type IngestResult = IngestAbsorb | IngestEscalate;
54
+ /** Compatibility name target remains on escalate_up (ADR 0033 D4 / 0034 D4). */
55
+ type IngestEscalate = IngestEscalateUp;
56
+ type IngestResult = IngestAbsorb | IngestHold | IngestEscalateUp;
36
57
  type ProposeResult = {
37
58
  readonly nextXi: XiRecord;
38
59
  readonly blastRadius: readonly string[];
39
60
  readonly invalidations: readonly string[];
40
61
  };
41
62
  type Projector = (release: Release, sigma: SigmaRecord) => Projection;
63
+ declare const CAPACITY_OPS: readonly ["lte", "lt", "gte", "gt"];
64
+ type CapacityOp = (typeof CAPACITY_OPS)[number];
65
+ /** Data-only cap. No user predicates (ADR 0016 / 0034 D5). */
66
+ type CapacityConstraint = {
67
+ readonly kind: string;
68
+ readonly sigmaKey: string;
69
+ readonly payloadKey: string;
70
+ readonly op: CapacityOp;
71
+ };
42
72
  type ConstraintPack = {
43
73
  readonly id: string;
44
74
  readonly escalateKinds?: readonly string[];
45
75
  readonly escalateTarget?: EscalationTarget;
76
+ readonly capacity?: readonly CapacityConstraint[];
46
77
  };
47
78
  /** What a scale may not observe (XP04). Denied kinds never appear in allowedKinds. */
48
79
  type InformationBudget = {
@@ -59,7 +90,18 @@ type XiSchema = {
59
90
  type InjectedClock = {
60
91
  now(): number;
61
92
  };
62
- type ArkOrderErrorCode = 'ARKORDER_EMPTY_XI' | 'ARKORDER_TOO_MANY_PARAMS' | 'ARKORDER_NESTED_XI' | 'ARKORDER_SCHEMA' | 'ARKORDER_NO_RELEASE' | 'ARKORDER_EMPTY_BLAST' | 'ARKORDER_FORBIDDEN_METHOD' | 'ARKORDER_UNKNOWN_KEY' | 'ARKORDER_INFORMATION_BUDGET' | 'ARKORDER_XI_TTL' | 'ARKORDER_STALE_SIGMA';
93
+ type ArkOrderErrorCode = 'ARKORDER_EMPTY_XI' | 'ARKORDER_TOO_MANY_PARAMS' | 'ARKORDER_NESTED_XI' | 'ARKORDER_SCHEMA' | 'ARKORDER_NO_RELEASE' | 'ARKORDER_EMPTY_BLAST' | 'ARKORDER_FORBIDDEN_METHOD' | 'ARKORDER_UNKNOWN_KEY' | 'ARKORDER_INFORMATION_BUDGET' | 'ARKORDER_XI_TTL' | 'ARKORDER_STALE_SIGMA' | 'ARKORDER_UNVALVED_RELEASE';
94
+
95
+ /**
96
+ * Injected ReleaseStore port (ADR 0034 D8). In-memory default is not durable.
97
+ * Does not close K01.
98
+ */
99
+
100
+ type ReleaseStore = {
101
+ load(): Release | null;
102
+ save(release: Release): void;
103
+ };
104
+ declare function createMemoryReleaseStore(initial?: Release | null): ReleaseStore;
63
105
 
64
106
  type CreateOrderPlaneOptions = {
65
107
  projector: Projector;
@@ -69,12 +111,18 @@ type CreateOrderPlaneOptions = {
69
111
  packs?: readonly ConstraintPack[];
70
112
  informationBudget?: InformationBudget;
71
113
  sigmaMaxAgeMs?: number;
114
+ /** Injected. Default is process-local memory — not durable, not K01. */
115
+ store?: ReleaseStore;
116
+ /** Optional catalog digest keyed by ξ.catalogReleaseId. SKU set does not enter the hash. */
117
+ catalogDigest?: string;
72
118
  };
73
119
  type OrderPlane = {
74
120
  release(xi: Record<string, unknown>, sigma?: Record<string, unknown>): Release;
75
121
  project(): Projection;
76
122
  ingest(event: FieldEvent): IngestResult;
77
123
  proposeRelease(delta: Record<string, unknown>): ProposeResult;
124
+ apply(proposal: ProposeResult): Release;
125
+ refreshSigma(sigma: Record<string, unknown>): Release;
78
126
  current(): Release | null;
79
127
  };
80
128
  declare function createOrderPlane(options: CreateOrderPlaneOptions): OrderPlane;
@@ -85,4 +133,7 @@ declare class ArkOrderError extends Error {
85
133
  constructor(code: ArkOrderErrorCode, message: string);
86
134
  }
87
135
 
88
- export { ArkOrderError, type ConstraintPack, type CreateOrderPlaneOptions, DEFAULT_MAX_XI_KEYS, type EscalationTarget, type FieldEvent, type InformationBudget, type IngestResult, type InjectedClock, type OrderPlane, type Projection, type Projector, type ProposeResult, type Release, type SigmaRecord, type XiRecord, type XiSchema, createOrderPlane };
136
+ /** D7: consumer still owns handlers this only names the travel verb. */
137
+ declare function ingestTravelAction(residual: IngestResult): 'send' | 'raises' | 'none';
138
+
139
+ export { ArkOrderError, CAPACITY_OPS, type CapacityConstraint, type CapacityOp, type ConstraintPack, type CreateOrderPlaneOptions, DEFAULT_MAX_XI_KEYS, type EscalationTarget, type FieldEvent, type InformationBudget, type IngestEscalate, type IngestEscalateUp, type IngestHold, type IngestReasonCode, type IngestResult, type InjectedClock, type OrderPlane, type Projection, type Projector, type ProposeResult, type Release, type ReleaseStore, type SigmaRecord, type XiRecord, type XiSchema, createMemoryReleaseStore, createOrderPlane, ingestTravelAction };