arkgate 4.8.2 → 4.8.3

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 (51) hide show
  1. package/CHANGELOG.md +15 -3
  2. package/README.md +39 -8
  3. package/bin/lib/analysis-engine.mjs +6 -6
  4. package/bin/lib/ark-order-facts.mjs +59 -0
  5. package/bin/lib/ark-order-sensors.mjs +31 -2
  6. package/bin/lib/arkrule-file-hints.mjs +6 -2
  7. package/bin/lib/arkrules-contract.mjs +1 -0
  8. package/bin/lib/arkrules-sensors.mjs +22 -2
  9. package/bin/lib/config-extras.mjs +2 -0
  10. package/bin/lib/diagnostic-catalog.mjs +2 -1
  11. package/bin/lib/remediation.mjs +9 -1
  12. package/bin/lib/resolved-candidate-facts.mjs +31 -0
  13. package/dist/{configTypes-BdCe_gvv.d.ts → configTypes-dNJ2C0yx.d.ts} +5 -0
  14. package/dist/{diagnosticCatalog-CPzH-MLN.d.ts → diagnosticCatalog-C5GgeyEE.d.ts} +97 -7
  15. package/dist/eslint/index.cjs +6 -6
  16. package/dist/eslint/index.d.ts +1 -1
  17. package/dist/eslint/index.js +6 -6
  18. package/dist/index.cjs +34 -34
  19. package/dist/index.d.ts +24 -7
  20. package/dist/index.js +34 -34
  21. package/dist/nestjs/index.cjs +5 -5
  22. package/dist/nestjs/index.d.ts +3 -3
  23. package/dist/nestjs/index.js +5 -5
  24. package/dist/runtime/index.cjs +15 -15
  25. package/dist/runtime/index.d.ts +6 -6
  26. package/dist/runtime/index.js +15 -15
  27. package/dist/{types-C9KApBzX.d.ts → types-DeK7SYGC.d.ts} +1 -1
  28. package/dist/{types-DCSlrRnV.d.ts → types-dK24fDZa.d.ts} +1 -1
  29. package/docs/README.md +4 -4
  30. package/docs/configuration.md +12 -8
  31. package/docs/develop.md +23 -2
  32. package/docs/diagnostics.md +9 -0
  33. package/docs/enthusiast/README.md +6 -4
  34. package/docs/package-surface.md +4 -2
  35. package/docs/product-voice.md +15 -5
  36. package/docs/use.md +8 -5
  37. package/package.json +1 -1
  38. package/schemas/ark.arkrules.schema.json +1 -0
  39. package/schemas/ark.config.schema.json +9 -0
  40. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  41. package/server.json +2 -2
  42. package/templates/agent-skills/README.md +1 -1
  43. package/templates/agent-skills/ark-adopt/SKILL.md +8 -3
  44. package/templates/agent-skills/ark-autopilot/SKILL.md +1 -1
  45. package/templates/agent-skills/ark-contract/SKILL.md +4 -0
  46. package/templates/agent-skills/ark-place/SKILL.md +6 -2
  47. package/templates/arkrules/ApplicationOrchestration.json +6 -0
  48. package/templates/skills/ark-adopt.md +8 -3
  49. package/templates/skills/ark-autopilot.md +1 -1
  50. package/templates/skills/ark-contract.md +4 -0
  51. package/templates/skills/ark-place.md +6 -2
@@ -1,10 +1,10 @@
1
- "use strict";var pn=Object.create;var C=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var mn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var s=(t,e)=>C(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 at=(t,e)=>{for(var n in e)C(t,n,{get:e[n],enumerable:!0})},ct=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fn(e))!gn.call(t,o)&&o!==n&&C(t,o,{get:()=>e[o],enumerable:!(r=st(e,o))||r.enumerable});return t};var yn=(t,e,n)=>(n=t!=null?pn(mn(t)):{},ct(e||!t||!t.__esModule?C(n,"default",{value:t,enumerable:!0}):n,t)),hn=t=>ct(C({},"__esModule",{value:!0}),t),dt=(t,e,n,r)=>{for(var o=r>1?void 0:r?st(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&&C(e,n,o),o};function Ee(t,e){return t<e?-1:t>e?1:0}function An(t){return[...new Set(t)].sort(Ee)}function L(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(Ee)){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 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=L(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 ve(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:L(e.uses),reactsTo:L(e.reactsTo),raises:L(e.raises),sends:L(e.sends)},o=vn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function P(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=ve(i);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((i,a)=>Ee(i.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:e,components:o}}var kn,Rn,G=_(()=>{"use strict";kn=["singleton","transient"],Rn=new Set(kn);s(Ee,"compare");s(An,"uniqueSorted");s(L,"nameList");s(wn,"jsonPrimitive");s(In,"closedLifetime");s(En,"sanitizeMetadata");s(vn,"sanitizeArkRunExtendedInfo");s(ve,"sanitizeArkRunComponent");s(P,"buildDependencyInformationPackage")});function j(t,e){return t<e?-1:t>e?1:0}function Pe(t){return[...new Set(t)].sort(j)}function lt(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Se(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function A(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Pe(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 Pe(n)}function mt(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=>mt(t,n)):!1}function gt(t){if(t==null||t==="")return Sn;if(typeof t=="string"&&bn.has(t))return t;throw new R("slice")}function yt(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 ut(t,e){if(t==null||t==="")return lt();if(typeof t=="string"||Array.isArray(t))return{...lt(),tokens:A(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:A(n.ids,e),labels:A(n.labels,e),tags:A(n.tags,e),groups:A(n.groups,e),architectureKinds:A(n.architectureKinds,e)}}function ht(t={}){if(t==null||t==="")return ht({});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:gt(e.slice),nodeIds:A(e.nodeIds,"nodeIds"),degreesOfSeparation:yt(e.degreesOfSeparation),include:ut(e.include,"include"),exclude:ut(e.exclude,"exclude")}}function kt(t){let e={};t.slice&&(e.slice=gt(t.slice));let n=A(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=yt(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=A(t.include??void 0,"include");o.length>0&&(e.include=o);let i=A(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 pt(t,e){if(!Se(e))return!0;let n=Nn(t);return e.tokens.some(r=>n.some(o=>mt(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 Dn(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return P({kernelInstanceId:e.kernelInstanceId,components:e.components})}return P({})}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 ne(t){return{id:t,kind:"interaction"}}function F(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function re(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(F(n,Tn(i)),e==="technical"){for(let a of i.uses)F(n,n.get(a)??ne(a)),re(r,o,i.id,a,"uses");continue}for(let a of i.raises)F(n,n.get(a)??ne(a)),re(r,o,i.id,a,"raises");for(let a of i.reactsTo)F(n,n.get(a)??ne(a)),re(r,o,a,i.id,"reactsTo");for(let a of i.sends)F(n,n.get(a)??ne(a)),re(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 B(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function ft(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=B(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=Pe(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,d)=>{let l=r.get(c.id)??B(c.id),f=ft(c.label??c.id);i.push(`${d}${l}["${f}"]`)},"emitNode");for(let c of o){let d=B(`group_${c}`);i.push(` subgraph ${d}["${ft(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)??B(c.from),l=r.get(c.to)??B(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
- `)}function Kn(t,e,n){let r=new Set(t.keys());if(Se(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&pt(d,n.include)}))),Se(n.exclude))for(let c of[...r]){let d=t.get(c);d&&pt(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(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 Rt(t={},e={}){let n=Dn(t),r=ht(e),o=$n(n.components,r.slice),i=Kn(o.nodes,o.edges,r),a={schemaVersion:Pn,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=Gn(a),a}var Pn,Sn,xn,R,bn,Cn,On,xe=_(()=>{"use strict";G();Pn="1.0",Sn="process",xn=["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}},bn=new Set(xn),Cn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),On=new Set(["ids","labels","tags","groups","architectureKinds"]);s(j,"compare");s(Pe,"uniqueSorted");s(lt,"emptyMatch");s(Se,"matchHasCriteria");s(A,"nameList");s(mt,"globMatch");s(K,"anyGlob");s(gt,"closedSlice");s(yt,"closedDegrees");s(ut,"closedMatch");s(ht,"closeArkRunGraphQuery");s(kt,"arkRunGraphQueryFromSearchParams");s(Nn,"nodeFields");s(pt,"nodeMatches");s(Dn,"asPackage");s(Tn,"componentNode");s(ne,"interactionNode");s(F,"addNode");s(re,"addEdge");s($n,"buildSlice");s(Mn,"adjacency");s(_n,"neighborhood");s(B,"mermaidSafeId");s(ft,"mermaidLabel");s(Ln,"uniqueMermaidIds");s(Gn,"formatArkRunGraphMermaid");s(Kn,"filterGraph");s(Rt,"requestArkRunGraph")});function jn(t){if(t===void 0)return"local";if(typeof t=="string"&&Fn.has(t))return t;throw new oe("transport")}function Bn(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new oe("ephemeral")}function At(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,oe,ie=_(()=>{"use strict";be=["local","localBlocking","broker"],Fn=new Set(be),oe=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(At,"resolveArkRunSendPlan")});function It(t){return t==="production"}function zn(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 Et(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function ae(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=Et(e);if(n)return ae(n);let r=zn(e);return r!==void 0&&r[0]===127}function vt(t){if(t===void 0)return wt;if(typeof t!="string")throw new w(String(t));let e=t.trim();if(Jn.has(e.toLowerCase())||!ae(e))throw new w(e);let n=e.toLowerCase();if(n==="localhost")return wt;if(n==="[::1]")return"::1";let r=Et(n);return r?vt(r):n}function Qn(t){if(t===void 0)return Un;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new w(`port:${String(t)}`);return t}function Te(t={}){if(It(t.nodeEnv)||It(t.processNodeEnv))throw new se;return{host:vt(t.host),port:Qn(t.port)}}function H(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function Zn(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function Xn(t){return{kinds:[...be],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:qn}}function Pt(t={}){let e=Te({host:t.host,port:t.port}),n=P({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:Xn(t),observability:Zn(t.observability)??{}}}function $e(t){return`event: ${Wn}
1
+ "use strict";var pn=Object.create;var C=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var mn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var s=(t,e)=>C(t,"name",{value:e,configurable:!0});var L=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var at=(t,e)=>{for(var n in e)C(t,n,{get:e[n],enumerable:!0})},ct=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fn(e))!gn.call(t,o)&&o!==n&&C(t,o,{get:()=>e[o],enumerable:!(r=st(e,o))||r.enumerable});return t};var yn=(t,e,n)=>(n=t!=null?pn(mn(t)):{},ct(e||!t||!t.__esModule?C(n,"default",{value:t,enumerable:!0}):n,t)),hn=t=>ct(C({},"__esModule",{value:!0}),t),dt=(t,e,n,r)=>{for(var o=r>1?void 0:r?st(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&&C(e,n,o),o};function Ee(t,e){return t<e?-1:t>e?1:0}function An(t){return[...new Set(t)].sort(Ee)}function K(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(Ee)){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 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=K(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 ve(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:K(e.uses),reactsTo:K(e.reactsTo),raises:K(e.raises),sends:K(e.sends)},o=vn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function P(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=ve(i);!a||r.has(a.id)||(r.add(a.id),o.push(a))}return o.sort((i,a)=>Ee(i.id,a.id)),{schemaVersion:"1.0",kernelInstanceId:e,components:o}}var kn,Rn,G=L(()=>{"use strict";kn=["singleton","transient"],Rn=new Set(kn);s(Ee,"compare");s(An,"uniqueSorted");s(K,"nameList");s(wn,"jsonPrimitive");s(In,"closedLifetime");s(En,"sanitizeMetadata");s(vn,"sanitizeArkRunExtendedInfo");s(ve,"sanitizeArkRunComponent");s(P,"buildDependencyInformationPackage")});function B(t,e){return t<e?-1:t>e?1:0}function Pe(t){return[...new Set(t)].sort(B)}function lt(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Se(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function A(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Pe(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 Pe(n)}function mt(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 F(t,e){return t?e.some(n=>mt(t,n)):!1}function gt(t){if(t==null||t==="")return Sn;if(typeof t=="string"&&bn.has(t))return t;throw new R("slice")}function yt(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 ut(t,e){if(t==null||t==="")return lt();if(typeof t=="string"||Array.isArray(t))return{...lt(),tokens:A(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:A(n.ids,e),labels:A(n.labels,e),tags:A(n.tags,e),groups:A(n.groups,e),architectureKinds:A(n.architectureKinds,e)}}function ht(t={}){if(t==null||t==="")return ht({});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:gt(e.slice),nodeIds:A(e.nodeIds,"nodeIds"),degreesOfSeparation:yt(e.degreesOfSeparation),include:ut(e.include,"include"),exclude:ut(e.exclude,"exclude")}}function kt(t){let e={};t.slice&&(e.slice=gt(t.slice));let n=A(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=yt(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=A(t.include??void 0,"include");o.length>0&&(e.include=o);let i=A(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 pt(t,e){if(!Se(e))return!0;let n=Nn(t);return e.tokens.some(r=>n.some(o=>mt(o,r)))||F(t.id,e.ids)||F(t.label,e.labels)||t.tags?.some(r=>F(r,e.tags))||F(t.group,e.groups)?!0:F(t.architectureKind,e.architectureKinds)}function Dn(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return P({kernelInstanceId:e.kernelInstanceId,components:e.components})}return P({})}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 ne(t){return{id:t,kind:"interaction"}}function j(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function re(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(j(n,Tn(i)),e==="technical"){for(let a of i.uses)j(n,n.get(a)??ne(a)),re(r,o,i.id,a,"uses");continue}for(let a of i.raises)j(n,n.get(a)??ne(a)),re(r,o,i.id,a,"raises");for(let a of i.reactsTo)j(n,n.get(a)??ne(a)),re(r,o,a,i.id,"reactsTo");for(let a of i.sends)j(n,n.get(a)??ne(a)),re(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 H(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function ft(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=H(r),i=o,a=2;for(;e.has(i);)i=`${o}_${a}`,a+=1;e.add(i),n.set(r,i)}return n}function Kn(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=Ln(n),o=Pe(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,d)=>{let l=r.get(c.id)??H(c.id),f=ft(c.label??c.id);i.push(`${d}${l}["${f}"]`)},"emitNode");for(let c of o){let d=H(`group_${c}`);i.push(` subgraph ${d}["${ft(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)??H(c.from),l=r.get(c.to)??H(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
+ `)}function Gn(t,e,n){let r=new Set(t.keys());if(Se(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&pt(d,n.include)}))),Se(n.exclude))for(let c of[...r]){let d=t.get(c);d&&pt(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(B).map(c=>t.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,d)=>B(c.from,d.from)||B(c.kind,d.kind)||B(c.to,d.to));return{nodes:i,edges:a}}function Rt(t={},e={}){let n=Dn(t),r=ht(e),o=$n(n.components,r.slice),i=Gn(o.nodes,o.edges,r),a={schemaVersion:Pn,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=Kn(a),a}var Pn,Sn,xn,R,bn,Cn,On,xe=L(()=>{"use strict";G();Pn="1.0",Sn="process",xn=["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}},bn=new Set(xn),Cn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),On=new Set(["ids","labels","tags","groups","architectureKinds"]);s(B,"compare");s(Pe,"uniqueSorted");s(lt,"emptyMatch");s(Se,"matchHasCriteria");s(A,"nameList");s(mt,"globMatch");s(F,"anyGlob");s(gt,"closedSlice");s(yt,"closedDegrees");s(ut,"closedMatch");s(ht,"closeArkRunGraphQuery");s(kt,"arkRunGraphQueryFromSearchParams");s(Nn,"nodeFields");s(pt,"nodeMatches");s(Dn,"asPackage");s(Tn,"componentNode");s(ne,"interactionNode");s(j,"addNode");s(re,"addEdge");s($n,"buildSlice");s(Mn,"adjacency");s(_n,"neighborhood");s(H,"mermaidSafeId");s(ft,"mermaidLabel");s(Ln,"uniqueMermaidIds");s(Kn,"formatArkRunGraphMermaid");s(Gn,"filterGraph");s(Rt,"requestArkRunGraph")});function jn(t){if(t===void 0)return"local";if(typeof t=="string"&&Fn.has(t))return t;throw new oe("transport")}function Bn(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new oe("ephemeral")}function At(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,oe,ie=L(()=>{"use strict";be=["local","localBlocking","broker"],Fn=new Set(be),oe=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(At,"resolveArkRunSendPlan")});function It(t){return t==="production"}function zn(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 Et(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function ae(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=Et(e);if(n)return ae(n);let r=zn(e);return r!==void 0&&r[0]===127}function vt(t){if(t===void 0)return wt;if(typeof t!="string")throw new w(String(t));let e=t.trim();if(Jn.has(e.toLowerCase())||!ae(e))throw new w(e);let n=e.toLowerCase();if(n==="localhost")return wt;if(n==="[::1]")return"::1";let r=Et(n);return r?vt(r):n}function Qn(t){if(t===void 0)return Un;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new w(`port:${String(t)}`);return t}function Te(t={}){if(It(t.nodeEnv)||It(t.processNodeEnv))throw new se;return{host:vt(t.host),port:Qn(t.port)}}function V(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function Zn(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function Xn(t){return{kinds:[...be],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:qn}}function Pt(t={}){let e=Te({host:t.host,port:t.port}),n=P({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:Xn(t),observability:Zn(t.observability)??{}}}function $e(t){return`event: ${Wn}
3
3
  data: ${JSON.stringify(t)}
4
4
 
5
- `}var Vn,wt,Un,Oe,Ne,De,Wn,qn,se,w,Jn,ce=_(()=>{"use strict";G();ie();Vn="1.0",wt="127.0.0.1",Un=0,Oe="/snapshot",Ne="/events",De="/graph",Wn="snapshot",qn="in-process-local",se=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},w=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"}},Jn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(It,"isArkRunInspectorProductionEnv");s(zn,"ipv4Octets");s(Et,"unwrapIpv4Mapped");s(ae,"isArkRunInspectorLoopbackHost");s(vt,"closedHost");s(Qn,"closedPort");s(Te,"resolveArkRunInspectorBind");s(H,"arkRunInspectorUrl");s(Zn,"jsonClone");s(Xn,"closedTransportFacts");s(Pt,"buildArkRunInspectorSnapshot");s($e,"formatArkRunInspectorSseEvent")});var rn={};at(rn,{listenArkRunInspector:()=>Nr});function xr(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function br(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Cr(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function Re(t,e,n){t.writeHead(e,xr()),t.end(JSON.stringify(n))}function Or(t,e){let n=t.address();if(n===null||typeof n=="string")throw new w(e.host);if(!ae(n.address))throw new w(n.address);return{host:e.host,port:n.port}}async function Nr(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,f)=>{let y=Cr(l.url),p=y.pathname;if(l.method==="GET"&&(p==="/"||p===Oe)){Re(f,200,c());return}if(l.method==="GET"&&p===De){try{Re(f,200,t.requestGraph(kt({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){Re(f,400,{error:m.message,option:m.option});return}throw m}return}if(l.method==="GET"&&p===Ne){f.writeHead(200,br()),f.flushHeaders(),f.write($e(c())),r.add(f);let m=i>0?setInterval(()=>{f.write($e(c()))},i):void 0;m&&o.add(m);let h=s(()=>{r.delete(f),m&&(clearInterval(m),o.delete(m))},"drop");l.on("close",h),f.on("close",h);return}Re(f,404,{error:"not found"})});try{await new Promise((l,f)=>{let y=s(p=>f(p),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{a=Or(d,e.bind),l()}catch(p){f(p instanceof Error?p:new w(e.bind.host))}})})}catch(l){throw await new Promise(f=>{d.close(()=>f())}),l}return{host:a.host,port:a.port,url:H(a.host,a.port,"/"),snapshotUrl:H(a.host,a.port,Oe),eventsUrl:H(a.host,a.port,Ne),graphUrl:H(a.host,a.port,De),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,f)=>{d.close(y=>{y?f(y):l()})})}}}var on=_(()=>{"use strict";xe();ce();s(xr,"jsonHeaders");s(br,"sseHeaders");s(Cr,"requestUrl");s(Re,"writeJson");s(Or,"boundAddress");s(Nr,"listenArkRunInspector")});var Lr={};at(Lr,{ARK_KERNEL:()=>$,ArkModule:()=>E,InjectArk:()=>_r});module.exports=hn(Lr);var Ae=require("@nestjs/common");xe();ce();G();ie();var St=0;function Yn(){return St+=1,`audit-${Date.now()}-${St}`}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 de=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}},le=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 Me(t={}){return new le(t.store??new de(t.maxRecords))}s(Me,"createAuditTrail");var S=class extends Error{static{s(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
5
+ `}var Vn,wt,Un,Oe,Ne,De,Wn,qn,se,w,Jn,ce=L(()=>{"use strict";G();ie();Vn="1.0",wt="127.0.0.1",Un=0,Oe="/snapshot",Ne="/events",De="/graph",Wn="snapshot",qn="in-process-local",se=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},w=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"}},Jn=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(It,"isArkRunInspectorProductionEnv");s(zn,"ipv4Octets");s(Et,"unwrapIpv4Mapped");s(ae,"isArkRunInspectorLoopbackHost");s(vt,"closedHost");s(Qn,"closedPort");s(Te,"resolveArkRunInspectorBind");s(V,"arkRunInspectorUrl");s(Zn,"jsonClone");s(Xn,"closedTransportFacts");s(Pt,"buildArkRunInspectorSnapshot");s($e,"formatArkRunInspectorSseEvent")});var rn={};at(rn,{listenArkRunInspector:()=>Nr});function xr(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function br(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Cr(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function Re(t,e,n){t.writeHead(e,xr()),t.end(JSON.stringify(n))}function Or(t,e){let n=t.address();if(n===null||typeof n=="string")throw new w(e.host);if(!ae(n.address))throw new w(n.address);return{host:e.host,port:n.port}}async function Nr(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,f)=>{let y=Cr(l.url),p=y.pathname;if(l.method==="GET"&&(p==="/"||p===Oe)){Re(f,200,c());return}if(l.method==="GET"&&p===De){try{Re(f,200,t.requestGraph(kt({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){Re(f,400,{error:m.message,option:m.option});return}throw m}return}if(l.method==="GET"&&p===Ne){f.writeHead(200,br()),f.flushHeaders(),f.write($e(c())),r.add(f);let m=i>0?setInterval(()=>{f.write($e(c()))},i):void 0;m&&o.add(m);let h=s(()=>{r.delete(f),m&&(clearInterval(m),o.delete(m))},"drop");l.on("close",h),f.on("close",h);return}Re(f,404,{error:"not found"})});try{await new Promise((l,f)=>{let y=s(p=>f(p),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{a=Or(d,e.bind),l()}catch(p){f(p instanceof Error?p:new w(e.bind.host))}})})}catch(l){throw await new Promise(f=>{d.close(()=>f())}),l}return{host:a.host,port:a.port,url:V(a.host,a.port,"/"),snapshotUrl:V(a.host,a.port,Oe),eventsUrl:V(a.host,a.port,Ne),graphUrl:V(a.host,a.port,De),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,f)=>{d.close(y=>{y?f(y):l()})})}}}var on=L(()=>{"use strict";xe();ce();s(xr,"jsonHeaders");s(br,"sseHeaders");s(Cr,"requestUrl");s(Re,"writeJson");s(Or,"boundAddress");s(Nr,"listenArkRunInspector")});var Lr={};at(Lr,{ARK_KERNEL:()=>M,ArkModule:()=>E,InjectArk:()=>_r});module.exports=hn(Lr);var Ae=require("@nestjs/common");xe();ce();G();ie();var St=0;function Yn(){return St+=1,`audit-${Date.now()}-${St}`}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 de=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}},le=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 Me(t={}){return new le(t.store??new de(t.maxRecords))}s(Me,"createAuditTrail");var S=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 O=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 S(n.hardViolations);return n}clear(){this.policies.length=0}};function ue(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(ue,"definePolicy");function tr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(tr,"defaultLayerOf");function xt(t,e){return e.resolveLayer?.(t)??tr(t)}s(xt,"resolveLayer");function nr(t,e,n){return t===n.from&&e===n.to}s(nr,"matchesRule");function bt(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return ue({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=xt(a.from,t),d=xt(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(bt,"defineLayerPolicy");function _e(t){return t.tags?.includes("layer")??!1}s(_e,"isLayerPolicy");function Le(t,e={}){return bt({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}s(Le,"defineArchitectureProfilePolicy");function Ge(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Ge,"buildPublishPolicyContext");var V=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}},U=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}},W=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"}},q=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}},N=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}},x=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}},J=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 Ct=["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(!Ct.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Ct.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 U(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new V(t)}}s(z,"assertIntentAllowed");function Ot(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new N(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new N(t.intent,t.metadata.source)}}s(Ot,"assertSourceAllowed");function Q(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new q(t.intent,n.issues)}s(Q,"assertContractAllowed");function D(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}s(D,"isPlainRecord");function T(t){return Array.isArray(t)?t.map(T):D(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,T(n)])):t}s(T,"clonePatchValue");function Fe(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]=T(i);continue}if(D(r[o])&&D(i)){r[o]=Fe(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(Fe,"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]=T(o);return}if(D(r[i])&&D(o)){r[i]=Fe(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 Nt(t,e){if(Array.isArray(e)){if(t===void 0)return T(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return je(t,e)}if(t===void 0)return T(e);if(!D(t))throw new Error("Object interceptor patch requires an object payload.");return Fe(t,e)}s(Nt,"applyPayloadPatch");async function Dt(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:Nt(c.payload,d),metadata:{...c.metadata}};Q(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(Dt,"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");function or(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(or,"normalizeGlobSeparators");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 ir(t){let e=new Set;for(let n of t??[]){let o=or(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 ar(t){return!t.fromPath||!t.toPath||t.folderCount<=0||!t.fromSlice||!t.toSlice?!0:t.fromSlice!==t.toSlice}s(ar,"peerIsolationMustDeny");function $t(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?Tt(i,c):void 0,l=i&&a?Tt(a,c):void 0;if(ar({fromPath:i,toPath:a,folderCount:c.length,fromSlice:d,toSlice:l}))return o;continue}if(e!==n)return o}}s($t,"findDeniedEdgeRule");async function Mt(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=$t(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 J(n,t.intent,o,i,d)}s(Mt,"assertObservedLayerFlowAllowed");async function _t(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof S&&(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(_t,"enforcePublishPolicy");function cr(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(cr,"appendHistory");function Z(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(Z,"appendTrace");async function pe(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){Z(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(pe,"recordAudit");async function Lt(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."};Z(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 pe(t,"event.rawPublish",e,n)}s(Lt,"recordRawPublishDiagnostic");async function Gt(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return cr(t,o),await t.eventBuffer?.enqueue(e,r),Z(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 pe(t,"event.published",e,{subscribersNotified:n}),o}s(Gt,"recordSuccessfulPublish");function Be(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(Be,"enrichMetadata");var Kt=0;function dr(){return Kt+=1,`interceptor-${Date.now()}-${Kt}`}s(dr,"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 O(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(_e)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new W;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ge({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 p=e,m=r??n??{};d={...p,metadata:Be(p.metadata,m,this.recording.instanceId)}}else{let p=e,m=n,h=r??{},u=p(m);d={...u,metadata:Be(u.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await Lt(this.recording,d),z(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ot(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Q(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await Dt(d,{interceptorsForIntent:s(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit")}),Q(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Mt(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let f=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await _t(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((p,m,h)=>this.safeHook(p,m,h),"safeHook")}),await Gt(this.recording,d,i?f.length:0,o.tx);let y=(async()=>{i&&await Promise.all(f.map(p=>this.invokeHandler(p,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 x(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:dr(),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){Z(this.recording,e)}async recordAudit(e,n,r){await pe(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 lr(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(lr,"formatStandardSchemaPath");function ur(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(ur,"actualType");function pr(t,e){return t?`${t}.${e}`:e}s(pr,"formatPath");function Ft(t,e,n,r,o){let i=ur(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}jt(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{Ft(a,e.items,`${n}[${c}]`,r,o)})}s(Ft,"validateSchemaField");function jt(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=pr(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}Ft(d,a,c,n,r)}}s(jt,"validateObjectSchema");var fe=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(jt(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:lr(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 He(){return new fe}s(He,"createEventContractRegistry");var me=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 O=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 S(n.hardViolations);return n}clear(){this.policies.length=0}};function ue(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(ue,"definePolicy");function tr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(tr,"defaultLayerOf");function xt(t,e){return e.resolveLayer?.(t)??tr(t)}s(xt,"resolveLayer");function nr(t,e,n){return t===n.from&&e===n.to}s(nr,"matchesRule");function bt(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return ue({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=xt(a.from,t),d=xt(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(bt,"defineLayerPolicy");function _e(t){return t.tags?.includes("layer")??!1}s(_e,"isLayerPolicy");function Le(t,e={}){return bt({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}s(Le,"defineArchitectureProfilePolicy");function Ke(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Ke,"buildPublishPolicyContext");var U=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}},W=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}},q=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"}},J=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}},N=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}},x=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}},z=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 Ct=["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(!Ct.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Ct.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 Q(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ge(t);if(!n.valid)throw new W(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new U(t)}}s(Q,"assertIntentAllowed");function Ot(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new N(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new N(t.intent,t.metadata.source)}}s(Ot,"assertSourceAllowed");function Z(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new J(t.intent,n.issues)}s(Z,"assertContractAllowed");function D(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}s(D,"isPlainRecord");function T(t){return Array.isArray(t)?t.map(T):D(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,T(n)])):t}s(T,"clonePatchValue");function Fe(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]=T(i);continue}if(D(r[o])&&D(i)){r[o]=Fe(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(Fe,"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]=T(o);return}if(D(r[i])&&D(o)){r[i]=Fe(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 Nt(t,e){if(Array.isArray(e)){if(t===void 0)return T(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return je(t,e)}if(t===void 0)return T(e);if(!D(t))throw new Error("Object interceptor patch requires an object payload.");return Fe(t,e)}s(Nt,"applyPayloadPatch");async function Dt(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:Nt(c.payload,d),metadata:{...c.metadata}};Z(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(Dt,"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");function or(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(or,"normalizeGlobSeparators");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 ir(t){let e=new Set;for(let n of t??[]){let o=or(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 ar(t){return!t.fromPath||!t.toPath||t.folderCount<=0||!t.fromSlice||!t.toSlice?!0:t.fromSlice!==t.toSlice}s(ar,"peerIsolationMustDeny");function $t(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?Tt(i,c):void 0,l=i&&a?Tt(a,c):void 0;if(ar({fromPath:i,toPath:a,folderCount:c.length,fromSlice:d,toSlice:l}))return o;continue}if(e!==n)return o}}s($t,"findDeniedEdgeRule");async function Mt(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=$t(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 z(n,t.intent,o,i,d)}s(Mt,"assertObservedLayerFlowAllowed");async function _t(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof S&&(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(_t,"enforcePublishPolicy");function cr(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(cr,"appendHistory");function X(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(X,"appendTrace");async function pe(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){X(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(pe,"recordAudit");async function Lt(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."};X(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 pe(t,"event.rawPublish",e,n)}s(Lt,"recordRawPublishDiagnostic");async function Kt(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return cr(t,o),await t.eventBuffer?.enqueue(e,r),X(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 pe(t,"event.published",e,{subscribersNotified:n}),o}s(Kt,"recordSuccessfulPublish");function Be(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(Be,"enrichMetadata");var Gt=0;function dr(){return Gt+=1,`interceptor-${Date.now()}-${Gt}`}s(dr,"nextInterceptorRegistrationId");var Y=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 O(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(_e)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new q;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ke({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 p=e,m=r??n??{};d={...p,metadata:Be(p.metadata,m,this.recording.instanceId)}}else{let p=e,m=n,h=r??{},u=p(m);d={...u,metadata:Be(u.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await Lt(this.recording,d),Q(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ot(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),Z(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await Dt(d,{interceptorsForIntent:s(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit")}),Z(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Mt(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let f=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await _t(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(p=>this.appendTrace(p),"appendTrace"),recordAudit:s((p,m,h)=>this.recordAudit(p,m,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((p,m,h)=>this.safeHook(p,m,h),"safeHook")}),await Kt(this.recording,d,i?f.length:0,o.tx);let y=(async()=>{i&&await Promise.all(f.map(p=>this.invokeHandler(p,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 Q(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 x(n,i.source);await this.publish(r,o,{...i,source:n},a)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;Q(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;Q(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:dr(),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){X(this.recording,e)}async recordAudit(e,n,r){await pe(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 lr(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(lr,"formatStandardSchemaPath");function ur(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(ur,"actualType");function pr(t,e){return t?`${t}.${e}`:e}s(pr,"formatPath");function Ft(t,e,n,r,o){let i=ur(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}jt(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{Ft(a,e.items,`${n}[${c}]`,r,o)})}s(Ft,"validateSchemaField");function jt(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=pr(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}Ft(d,a,c,n,r)}}s(jt,"validateObjectSchema");var fe=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(jt(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:lr(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 He(){return new fe}s(He,"createEventContractRegistry");var me=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 O=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),f=o.slice(l).concat(d);n.push(f)}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 Ve(){return new me}s(Ve,"createDependencyGraph");function Ue(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(Ue,"syncRegistryToGraph");var Y=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 xi=new Y;function We(){return new Y}s(We,"createIntentRegistry");var ee={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...ee,default:[]},kernelRoots:{...ee},managedLayers:{...ee,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ht={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...ee,default:[]},managedLayers:{...ee,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7}}};var Vt="1.3",Ut="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Wt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function mr(){let t=[];for(let e of Wt)for(let n of Wt)e===n||fr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(mr,"createDefaultRules");var qe=mr();var I={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Vi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ut,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:Ut,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:Vt,default:Vt},name:{type:"string",minLength:1},include:{...I,minItems:1,default:["src"]},exclude:{...I,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:qe,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...I,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...I,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...I,minItems:1},exclude:I,intentPrefixes:I,description:{type:"string",minLength:1},forbiddenGlobals:I,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:{...I,minItems: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}}},arkRun:Bt,arkOrder:Ht}};function gr(t){return t.endsWith(".")?t:`${t}.`}s(gr,"normalizePrefix");function yr(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(yr,"byLongestPrefix");function qt(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(gr)})),n=[...e].sort(yr),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(qt,"createArchitectureProfile");var hr=[{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}],Je=qt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:hr,rules:qe.map(t=>({...t}))});var Jt="4.8.2";function Rr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Rr,"policyId");var ze=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Qe(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)})):[],f=e?e.getAllRelationships():[],y=n?n.getPolicies().map(g=>({id:Rr(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})):[],p=r?r.toJSON():[],m=o?o.toJSON():{nodes:[],edges:[]},h=p.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)})):[],v={schemaVersion:"1.0",version:Jt,exportedAt:new Date().toISOString(),intents:l,relationships:f,policies:y,entities:p,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(v)}s(Qe,"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 Ze(){return new ge}s(Ze,"createMetadataRegistry");function Xe(t){return`${t.from}->${t.to}`}s(Xe,"flowKey");function Qt(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(Qt,"uniqueFlows");function Zt(t,e){let n=new Set(e.map(Xe));return t.filter(r=>!n.has(Xe(r)))}s(Zt,"difference");function Ye(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=Qt([...o,...i]),l=Qt([...a,...c]),f=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)))):[],p=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:Zt(d,l),observedButUndeclared:Zt(l.filter(u=>u.from!=="unknown"),d),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:h}}}}s(Ye,"createObservabilityReporter");var Xt=0;function Ar(){return Xt+=1,`outbox-${Date.now()}-${Xt}`}s(Ar,"nextOutboxId");function Yt(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(Yt,"cloneRecord");var te=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Ar(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Yt(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(Yt)}async clear(){this.records.clear()}};var ye=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 wr(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(wr,"initialState");var he=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new ye,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)??wr(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 et(t){return new he(t)}s(et,"createProjectionRegistry");var en=0;function Ir(t){return en+=1,`${t}-${Date.now()}-${en}`}s(Ir,"createWorkflowId");function tt(t){return t instanceof Error?t.message:String(t)}s(tt,"errorMessage");function Er(t){return new Promise(e=>{setTimeout(e,t)})}s(Er,"sleep");async function vr(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(vr,"withTimeout");var ke=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()}},nt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new ke}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??Ir(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=tt(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 vr(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await Er(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:tt(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:tt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function rt(t,e){return new nt(t,e)}s(rt,"createWorkflowEngine");G();var Pr=new Set(["singleton","transient"]);function tn(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(tn,"cloneComponent");function Sr(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Pr.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(Sr,"closedLifetime");function nn(){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=Sr(a.lifetime),l=ve({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 f=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:f}),tn(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=>tn(a.component))}}}s(nn,"createComponentRegistry");ce();async function sn(t,e={}){let n=Te({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(on(),rn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(sn,"startArkRunInspector");ie();function Dr(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new x(t.source,e.source);return e.source=t.source,e}s(Dr,"stampMetadata");function Tr(){}s(Tr,"ignoreDetachedFailure");async function ot(t,e,n,r={}){let o=At({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Dr(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,Tr)}return o}s(ot,"sendOnArkRunTransport");var $r=1e3,an=0;function Mr(){return an+=1,`ark-kernel-${Date.now()}-${an}`}s(Mr,"nextKernelInstanceId");function cn(t={}){let e=t.strict??!0,n=t.instanceId??Mr(),r=t.profile??Je,o=t.maxHistorySize??$r,i=We(),a=Ve(),c=t.metadata??Ze(),d=t.auditTrail??Me({maxRecords:o}),l=t.eventContracts??He(),f=t.eventBuffer??t.outbox??new te,y=t.projections??et({auditTrail:d}),p=new O([Le(r),...t.policies??[]]),m=s(()=>{Ue(i,a,{requireRegisteredTargets:!0})},"syncGraph"),h=t.ephemeral??!0,u=t.broker,v=new X({intentRegistry:i,dependencyGraph:a,policyEngine:p,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:f,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await y.apply(k)}}),g=rt(v,{auditTrail:d}),we=Ye({registry:i,eventBus:v,graph:a}),b=nn(),dn=typeof u?.send=="function",it={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:d,eventContracts:l,eventBuffer:f,outbox:f,projections:y,policyEngine:p,eventBus:v,workflowEngine:g,observability:we,publisher(k){let M=v.createPublisher(k);return{source:M.source,publish:M.publish,send(Ie,ln,un={}){return ot({eventBus:v,broker:u,defaultEphemeral:h},Ie,ln,{...un,source:M.source})}}},send(k,M,Ie={}){return ot({eventBus:v,broker:u,defaultEphemeral:h},k,M,Ie)},register(k){return b.register(k)},resolve(k){return b.resolve(k)},resolveSingleton(k){return b.resolveSingleton(k)},getDependencyInformationPackage(){return P({kernelInstanceId:n,components:b.snapshotComponents()})},requestGraph(k){return Rt({kernelInstanceId:n,components:b.snapshotComponents()},k)},getInspectorSnapshot(k){return Pt({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:b.snapshotComponents()},observability:we.report(),ephemeralDefault:h,brokerBound:dn})},startInspector(k){return sn(it,k)},syncGraph:m,manifest(){return m(),Qe({registry:i,policyEngine:p,metadata:c,graph:a,profile:r,projections:y,eventContracts:l,observability:we})}};return it}s(cn,"createArkKernel");var $=Symbol("ARK_KERNEL"),_r=s(()=>(0,Ae.Inject)($),"InjectArk"),E=class{static forRoot(e){let n=e&&"registry"in e?e:cn(e);return{module:E,global:!0,providers:[{provide:$,useValue:n}],exports:[$]}}static forRootAsync(e){return{module:E,global:!0,providers:[{provide:$,useFactory:e.useFactory,inject:e.inject??[]}],exports:[$]}}};s(E,"ArkModule"),E=dt([(0,Ae.Module)({})],E);0&&(module.exports={ARK_KERNEL,ArkModule,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),f=o.slice(l).concat(d);n.push(f)}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 Ve(){return new me}s(Ve,"createDependencyGraph");function Ue(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(Ue,"syncRegistryToGraph");var ee=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 xi=new ee;function We(){return new ee}s(We,"createIntentRegistry");var $={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...$,default:[]},kernelRoots:{...$},managedLayers:{...$,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Ht={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...$,default:[]},managedLayers:{...$,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...$,default:[]}}};var Vt="1.3",Ut="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Wt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],fr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function mr(){let t=[];for(let e of Wt)for(let n of Wt)e===n||fr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(mr,"createDefaultRules");var qe=mr();var I={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Vi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ut,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:Ut,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:Vt,default:Vt},name:{type:"string",minLength:1},include:{...I,minItems:1,default:["src"]},exclude:{...I,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:qe,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...I,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...I,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...I,minItems:1},exclude:I,intentPrefixes:I,description:{type:"string",minLength:1},forbiddenGlobals:I,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:{...I,minItems: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}}},arkRun:Bt,arkOrder:Ht}};function gr(t){return t.endsWith(".")?t:`${t}.`}s(gr,"normalizePrefix");function yr(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(yr,"byLongestPrefix");function qt(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(gr)})),n=[...e].sort(yr),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(qt,"createArchitectureProfile");var hr=[{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}],Je=qt({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:hr,rules:qe.map(t=>({...t}))});var Jt="4.8.3";function Rr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Rr,"policyId");var ze=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Qe(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)})):[],f=e?e.getAllRelationships():[],y=n?n.getPolicies().map(g=>({id:Rr(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})):[],p=r?r.toJSON():[],m=o?o.toJSON():{nodes:[],edges:[]},h=p.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)})):[],v={schemaVersion:"1.0",version:Jt,exportedAt:new Date().toISOString(),intents:l,relationships:f,policies:y,entities:p,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(v)}s(Qe,"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 Ze(){return new ge}s(Ze,"createMetadataRegistry");function Xe(t){return`${t.from}->${t.to}`}s(Xe,"flowKey");function Qt(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(Qt,"uniqueFlows");function Zt(t,e){let n=new Set(e.map(Xe));return t.filter(r=>!n.has(Xe(r)))}s(Zt,"difference");function Ye(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=Qt([...o,...i]),l=Qt([...a,...c]),f=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)))):[],p=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:Zt(d,l),observedButUndeclared:Zt(l.filter(u=>u.from!=="unknown"),d),unknownSources:f,unregisteredObservedSources:y,unregisteredObservedIntents:p,registeredButNeverObserved:h}}}}s(Ye,"createObservabilityReporter");var Xt=0;function Ar(){return Xt+=1,`outbox-${Date.now()}-${Xt}`}s(Ar,"nextOutboxId");function Yt(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(Yt,"cloneRecord");var te=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Ar(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Yt(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(Yt)}async clear(){this.records.clear()}};var ye=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 wr(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(wr,"initialState");var he=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new ye,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)??wr(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 et(t){return new he(t)}s(et,"createProjectionRegistry");var en=0;function Ir(t){return en+=1,`${t}-${Date.now()}-${en}`}s(Ir,"createWorkflowId");function tt(t){return t instanceof Error?t.message:String(t)}s(tt,"errorMessage");function Er(t){return new Promise(e=>{setTimeout(e,t)})}s(Er,"sleep");async function vr(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(vr,"withTimeout");var ke=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()}},nt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new ke}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??Ir(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=tt(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 vr(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(a<i){o.delayMs&&await Er(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:tt(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:tt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function rt(t,e){return new nt(t,e)}s(rt,"createWorkflowEngine");G();var Pr=new Set(["singleton","transient"]);function tn(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(tn,"cloneComponent");function Sr(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Pr.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(Sr,"closedLifetime");function nn(){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=Sr(a.lifetime),l=ve({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 f=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:l,factory:f}),tn(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=>tn(a.component))}}}s(nn,"createComponentRegistry");ce();async function sn(t,e={}){let n=Te({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(on(),rn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(sn,"startArkRunInspector");ie();function Dr(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new x(t.source,e.source);return e.source=t.source,e}s(Dr,"stampMetadata");function Tr(){}s(Tr,"ignoreDetachedFailure");async function ot(t,e,n,r={}){let o=At({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Dr(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,Tr)}return o}s(ot,"sendOnArkRunTransport");var $r=1e3,an=0;function Mr(){return an+=1,`ark-kernel-${Date.now()}-${an}`}s(Mr,"nextKernelInstanceId");function cn(t={}){let e=t.strict??!0,n=t.instanceId??Mr(),r=t.profile??Je,o=t.maxHistorySize??$r,i=We(),a=Ve(),c=t.metadata??Ze(),d=t.auditTrail??Me({maxRecords:o}),l=t.eventContracts??He(),f=t.eventBuffer??t.outbox??new te,y=t.projections??et({auditTrail:d}),p=new O([Le(r),...t.policies??[]]),m=s(()=>{Ue(i,a,{requireRegisteredTargets:!0})},"syncGraph"),h=t.ephemeral??!0,u=t.broker,v=new Y({intentRegistry:i,dependencyGraph:a,policyEngine:p,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:f,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await y.apply(k)}}),g=rt(v,{auditTrail:d}),we=Ye({registry:i,eventBus:v,graph:a}),b=nn(),dn=typeof u?.send=="function",it={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:d,eventContracts:l,eventBuffer:f,outbox:f,projections:y,policyEngine:p,eventBus:v,workflowEngine:g,observability:we,publisher(k){let _=v.createPublisher(k);return{source:_.source,publish:_.publish,send(Ie,ln,un={}){return ot({eventBus:v,broker:u,defaultEphemeral:h},Ie,ln,{...un,source:_.source})}}},send(k,_,Ie={}){return ot({eventBus:v,broker:u,defaultEphemeral:h},k,_,Ie)},register(k){return b.register(k)},resolve(k){return b.resolve(k)},resolveSingleton(k){return b.resolveSingleton(k)},getDependencyInformationPackage(){return P({kernelInstanceId:n,components:b.snapshotComponents()})},requestGraph(k){return Rt({kernelInstanceId:n,components:b.snapshotComponents()},k)},getInspectorSnapshot(k){return Pt({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:b.snapshotComponents()},observability:we.report(),ephemeralDefault:h,brokerBound:dn})},startInspector(k){return sn(it,k)},syncGraph:m,manifest(){return m(),Qe({registry:i,policyEngine:p,metadata:c,graph:a,profile:r,projections:y,eventContracts:l,observability:we})}};return it}s(cn,"createArkKernel");var M=Symbol("ARK_KERNEL"),_r=s(()=>(0,Ae.Inject)(M),"InjectArk"),E=class{static forRoot(e){let n=e&&"registry"in e?e:cn(e);return{module:E,global:!0,providers:[{provide:M,useValue:n}],exports:[M]}}static forRootAsync(e){return{module:E,global:!0,providers:[{provide:M,useFactory:e.useFactory,inject:e.inject??[]}],exports:[M]}}};s(E,"ArkModule"),E=dt([(0,Ae.Module)({})],E);0&&(module.exports={ARK_KERNEL,ArkModule,InjectArk});
@@ -1,7 +1,7 @@
1
1
  import { DynamicModule, InjectionToken, OptionalFactoryDependency } from '@nestjs/common';
2
- import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-C9KApBzX.js';
3
- import '../types-DCSlrRnV.js';
4
- import '../configTypes-BdCe_gvv.js';
2
+ import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-DeK7SYGC.js';
3
+ import '../types-dK24fDZa.js';
4
+ import '../configTypes-dNJ2C0yx.js';
5
5
 
6
6
  /** Injection token for the Ark kernel instance. */
7
7
  declare const ARK_KERNEL: unique symbol;