arkgate 4.8.22 → 4.8.24

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 (136) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +7 -5
  3. package/bin/ark-check-runtime.mjs +27 -78
  4. package/bin/ark-dashboard.mjs +56 -53
  5. package/bin/ark-layer-match.mjs +1117 -38
  6. package/bin/ark-mcp-runtime.mjs +412 -138
  7. package/bin/ark-mcp.mjs +68 -4
  8. package/bin/ark-shared.mjs +39 -0
  9. package/bin/ark.mjs +65 -97
  10. package/bin/lib/adapter-contract-types.mjs +5 -0
  11. package/bin/lib/adapter-contract.mjs +15 -0
  12. package/bin/lib/agent-projection-command.mjs +5 -1
  13. package/bin/lib/analysis-engine.mjs +15 -11
  14. package/bin/lib/architecture-scan.mjs +50 -6
  15. package/bin/lib/ark-order-doctor.mjs +1 -1
  16. package/bin/lib/ark-order-facts.mjs +410 -15
  17. package/bin/lib/ark-order-invariants.mjs +51 -9
  18. package/bin/lib/ark-order-sensors.mjs +28 -101
  19. package/bin/lib/ark-order-types.mjs +2 -0
  20. package/bin/lib/ark-run-doctor.mjs +14 -0
  21. package/bin/lib/ark-run-facts.mjs +434 -11
  22. package/bin/lib/ark-run-sensors.mjs +5 -3
  23. package/bin/lib/arkgate-pins.mjs +91 -0
  24. package/bin/lib/arkrules-sensors.mjs +50 -249
  25. package/bin/lib/check-args.mjs +23 -1
  26. package/bin/lib/ci-and-commands.mjs +16 -6
  27. package/bin/lib/class-source-scan.mjs +479 -0
  28. package/bin/lib/codex-home.mjs +4 -2
  29. package/bin/lib/config-contract-slices.mjs +701 -0
  30. package/bin/lib/config-contract.mjs +5 -2
  31. package/bin/lib/config-warnings.mjs +32 -0
  32. package/bin/lib/dashboard-cli.mjs +62 -0
  33. package/bin/lib/design-delta.mjs +1 -1
  34. package/bin/lib/diagnostic-catalog.mjs +45 -6
  35. package/bin/lib/doctor-advisories.mjs +84 -1
  36. package/bin/lib/doctor-next-actions.mjs +17 -2
  37. package/bin/lib/doctor-plan.mjs +7 -9
  38. package/bin/lib/effective-contract-load.mjs +121 -59
  39. package/bin/lib/enforcement-honesty.mjs +22 -0
  40. package/bin/lib/enforcement-profiles.mjs +40 -4
  41. package/bin/lib/first-run-help.mjs +3 -2
  42. package/bin/lib/flat-parent-importers.mjs +137 -0
  43. package/bin/lib/flat-parent-pilot.mjs +192 -0
  44. package/bin/lib/gate-files.mjs +29 -2
  45. package/bin/lib/git-change-scope.mjs +109 -0
  46. package/bin/lib/github-enforcement.mjs +1 -1
  47. package/bin/lib/hook-templates.mjs +18 -16
  48. package/bin/lib/host-support-matrix.mjs +3 -1
  49. package/bin/lib/html-report-advisories.mjs +2 -0
  50. package/bin/lib/html-report-depth.mjs +3 -1
  51. package/bin/lib/import-resolve.mjs +13 -1
  52. package/bin/lib/install-migrate.mjs +50 -73
  53. package/bin/lib/invariant-coverage.mjs +59 -11
  54. package/bin/lib/mcp-adoption.mjs +9 -1
  55. package/bin/lib/mcp-hook-payload.mjs +401 -61
  56. package/bin/lib/package-manager.mjs +59 -1
  57. package/bin/lib/passthrough-commands.mjs +83 -0
  58. package/bin/lib/persistence-write-hint.mjs +81 -0
  59. package/bin/lib/physical-cohesion.mjs +16 -18
  60. package/bin/lib/pilot-loop.mjs +21 -8
  61. package/bin/lib/pin-dependent-gates.mjs +117 -0
  62. package/bin/lib/policy-delta-io.mjs +168 -10
  63. package/bin/lib/prepare-change.mjs +120 -6
  64. package/bin/lib/prepare-write.mjs +1 -0
  65. package/bin/lib/presets.mjs +3 -5
  66. package/bin/lib/remediation.mjs +23 -4
  67. package/bin/lib/resolved-candidate-facts.mjs +315 -55
  68. package/bin/lib/rules-inventory.mjs +22 -3
  69. package/bin/lib/rules-under-contract.mjs +179 -5
  70. package/bin/lib/scan-files.mjs +32 -0
  71. package/bin/lib/snippet-analysis.mjs +140 -6
  72. package/bin/lib/source-policy.mjs +34 -0
  73. package/bin/lib/stable-hash.mjs +90 -0
  74. package/bin/lib/start-install-recovery.mjs +71 -1
  75. package/bin/lib/start-preview.mjs +30 -0
  76. package/bin/lib/status-command.mjs +33 -4
  77. package/bin/lib/status-manifest.mjs +32 -4
  78. package/bin/lib/team-parliament-io.mjs +79 -75
  79. package/bin/lib/team-parliament.mjs +6 -1
  80. package/bin/lib/write-path-capabilities.mjs +4 -2
  81. package/dist/chunk-A5EIY3HI.cjs +5 -0
  82. package/dist/chunk-MBXCFLO4.js +16 -0
  83. package/dist/chunk-RNQHRDCQ.cjs +16 -0
  84. package/dist/chunk-SVSQVGFJ.js +5 -0
  85. package/dist/{configTypes-CTELo87-.d.ts → configTypes-BJbaeoj4.d.cts} +53 -4
  86. package/dist/configTypes-BJbaeoj4.d.ts +246 -0
  87. package/dist/eslint/index.cjs +17 -4
  88. package/dist/eslint/index.d.cts +359 -0
  89. package/dist/eslint/index.d.ts +178 -158
  90. package/dist/eslint/index.js +10 -4
  91. package/dist/index.cjs +38 -37
  92. package/dist/index.d.cts +5475 -0
  93. package/dist/index.d.ts +3408 -296
  94. package/dist/index.js +38 -37
  95. package/dist/inspectorListen-6DQVJ4DC.js +1 -0
  96. package/dist/inspectorListen-KGMIQ2TF.cjs +1 -0
  97. package/dist/nestjs/index.cjs +1 -18
  98. package/dist/nestjs/index.d.cts +22 -0
  99. package/dist/nestjs/index.d.ts +1 -3
  100. package/dist/nestjs/index.js +1 -18
  101. package/dist/order/index.cjs +1 -1
  102. package/dist/order/index.d.cts +155 -0
  103. package/dist/order/index.d.ts +15 -3
  104. package/dist/order/index.js +1 -1
  105. package/dist/runtime/index.cjs +13 -30
  106. package/dist/{diagnosticCatalog-WD2TPSwZ.d.ts → runtime/index.d.cts} +814 -290
  107. package/dist/runtime/index.d.ts +2678 -108
  108. package/dist/runtime/index.js +13 -30
  109. package/dist/{types-yDNEQ603.d.ts → types-DRinG-vT.d.cts} +576 -140
  110. package/dist/types-DRinG-vT.d.ts +1792 -0
  111. package/docs/README.md +3 -1
  112. package/docs/agent-guide.md +92 -15
  113. package/docs/ai-gates.md +160 -26
  114. package/docs/arkorder.md +32 -15
  115. package/docs/brownfield-adoption.md +5 -1
  116. package/docs/configuration.md +273 -12
  117. package/docs/develop.md +2 -1
  118. package/docs/diagnostics.md +122 -13
  119. package/docs/package-surface.md +31 -8
  120. package/docs/product-voice.md +1 -1
  121. package/package.json +59 -18
  122. package/schemas/ark.analysis-result.schema.json +15 -0
  123. package/schemas/ark.config.schema.json +163 -4
  124. package/schemas/ark.resolved-candidate-facts.schema.json +1 -1
  125. package/schemas/ark.status-manifest.schema.json +22 -0
  126. package/server.json +3 -9
  127. package/templates/agent-skills/README.md +1 -1
  128. package/templates/agent-skills/ark-adopt/SKILL.md +4 -1
  129. package/templates/agent-skills/ark-order/SKILL.md +4 -2
  130. package/templates/agent-skills/ark-runtime/SKILL.md +6 -1
  131. package/templates/arkrules/PersistenceAdapters.json +1 -1
  132. package/templates/arkrules/PresentationAdapters.json +1 -1
  133. package/templates/skills/ark-adopt.md +4 -1
  134. package/templates/skills/ark-order.md +4 -2
  135. package/templates/skills/ark-runtime.md +6 -1
  136. package/dist/types-fQ9-KrBj.d.ts +0 -183
@@ -0,0 +1 @@
1
+ import{B as I,C as m,D as w,E as A,F as g,I as v,K as R,M as O,O as l,R as _,S as x,T as M,U as T,W as b,a,n as S,p as E}from"./chunk-SVSQVGFJ.js";function U(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}a(U,"jsonHeaders");function N(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}a(N,"sseHeaders");function H(r){let n=(r&&r.length>0?r:"/").replace(/^\/+/,"/");return new URL(n,"http://127.0.0.1")}a(H,"requestUrl");function u(r,n,c){if(!(r.writableEnded||r.destroyed))try{r.writeHead(n,U()),r.end(JSON.stringify(c))}catch{}}a(u,"writeJson");function G(r,n){let c=r.address();if(c===null||typeof c=="string")throw new R(n.host);if(!O(c.address))throw new R(c.address);return{host:n.host,port:c.port}}a(G,"boundAddress");async function L(r){if(typeof r.listInspectorOutbox=="function")return r.listInspectorOutbox();let n=r.outbox??r.eventBuffer;if(!n||typeof n.list!="function")return x();let[c,d]=await Promise.all([n.list("pending"),n.list("failed")]);return _([...c??[],...d??[]],{sampleLimit:v})}a(L,"resolveOutboxMonitor");async function W(r){return typeof r.listInspectorWorkflows=="function"?r.listInspectorWorkflows():!r.workflowEngine||typeof r.workflowEngine.list!="function"?T():M(await r.workflowEngine.list(),{sampleLimit:v})}a(W,"resolveWorkflowsMonitor");async function C(r,n){let c=await import("http"),d=new Set,h=new Set,y=typeof n.sseIntervalMs=="number"&&Number.isFinite(n.sseIntervalMs)?Math.max(0,n.sseIntervalMs):1e3,s=n.bind,k=a(()=>r.getInspectorSnapshot(s),"snapshot"),f=c.createServer((o,t)=>{let i=H(o.url),p=i.pathname;if(o.method==="GET"&&(p==="/"||p===I)){u(t,200,k());return}if(o.method==="GET"&&p===w){try{u(t,200,r.requestGraph(E({slice:i.searchParams.get("slice"),nodeIds:i.searchParams.get("nodeIds"),degreesOfSeparation:i.searchParams.get("degreesOfSeparation"),include:i.searchParams.get("include"),exclude:i.searchParams.get("exclude")})))}catch(e){if(e instanceof S){u(t,400,{error:e.message,option:e.option});return}throw e}return}if(o.method==="GET"&&p===A){L(r).then(e=>u(t,200,e)).catch(e=>{u(t,500,{error:e instanceof Error?e.message:"outbox monitor failed"})});return}if(o.method==="GET"&&p===g){W(r).then(e=>u(t,200,e)).catch(e=>{u(t,500,{error:e instanceof Error?e.message:"workflows monitor failed"})});return}if(o.method==="GET"&&p===m){t.writeHead(200,N()),t.flushHeaders(),t.write(b(k())),d.add(t);let e=y>0?setInterval(()=>{t.write(b(k()))},y):void 0;e&&h.add(e);let P=a(()=>{d.delete(t),e&&(clearInterval(e),h.delete(e))},"drop");o.on("close",P),t.on("close",P);return}u(t,404,{error:"not found"})});try{await new Promise((o,t)=>{let i=a(p=>t(p),"onError");f.once("error",i),f.listen({host:n.bind.host,port:n.bind.port},()=>{f.off("error",i);try{s=G(f,n.bind),o()}catch(p){t(p instanceof Error?p:new R(n.bind.host))}})})}catch(o){throw await new Promise(t=>{f.close(()=>t())}),o}return{host:s.host,port:s.port,url:l(s.host,s.port,"/"),snapshotUrl:l(s.host,s.port,I),eventsUrl:l(s.host,s.port,m),graphUrl:l(s.host,s.port,w),outboxUrl:l(s.host,s.port,A),workflowsUrl:l(s.host,s.port,g),close(){for(let o of h)clearInterval(o);h.clear();for(let o of d)o.end();return d.clear(),new Promise((o,t)=>{f.close(i=>{i?t(i):o()})})}}}a(C,"listenArkRunInspector");export{C as listenArkRunInspector};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkA5EIY3HIcjs = require('./chunk-A5EIY3HI.cjs');function U(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}_chunkA5EIY3HIcjs.a.call(void 0, U,"jsonHeaders");function N(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}_chunkA5EIY3HIcjs.a.call(void 0, N,"sseHeaders");function H(r){let n=(r&&r.length>0?r:"/").replace(/^\/+/,"/");return new URL(n,"http://127.0.0.1")}_chunkA5EIY3HIcjs.a.call(void 0, H,"requestUrl");function u(r,n,c){if(!(r.writableEnded||r.destroyed))try{r.writeHead(n,U()),r.end(JSON.stringify(c))}catch (e2){}}_chunkA5EIY3HIcjs.a.call(void 0, u,"writeJson");function G(r,n){let c=r.address();if(c===null||typeof c=="string")throw new (0, _chunkA5EIY3HIcjs.K)(n.host);if(!_chunkA5EIY3HIcjs.M.call(void 0, c.address))throw new (0, _chunkA5EIY3HIcjs.K)(c.address);return{host:n.host,port:c.port}}_chunkA5EIY3HIcjs.a.call(void 0, G,"boundAddress");async function L(r){if(typeof r.listInspectorOutbox=="function")return r.listInspectorOutbox();let n=_nullishCoalesce(r.outbox, () => (r.eventBuffer));if(!n||typeof n.list!="function")return _chunkA5EIY3HIcjs.S.call(void 0, );let[c,d]=await Promise.all([n.list("pending"),n.list("failed")]);return _chunkA5EIY3HIcjs.R.call(void 0, [..._nullishCoalesce(c, () => ([])),..._nullishCoalesce(d, () => ([]))],{sampleLimit:_chunkA5EIY3HIcjs.I})}_chunkA5EIY3HIcjs.a.call(void 0, L,"resolveOutboxMonitor");async function W(r){return typeof r.listInspectorWorkflows=="function"?r.listInspectorWorkflows():!r.workflowEngine||typeof r.workflowEngine.list!="function"?_chunkA5EIY3HIcjs.U.call(void 0, ):_chunkA5EIY3HIcjs.T.call(void 0, await r.workflowEngine.list(),{sampleLimit:_chunkA5EIY3HIcjs.I})}_chunkA5EIY3HIcjs.a.call(void 0, W,"resolveWorkflowsMonitor");async function C(r,n){let c=await Promise.resolve().then(() => _interopRequireWildcard(require("http"))),d=new Set,h=new Set,y=typeof n.sseIntervalMs=="number"&&Number.isFinite(n.sseIntervalMs)?Math.max(0,n.sseIntervalMs):1e3,s=n.bind,k=_chunkA5EIY3HIcjs.a.call(void 0, ()=>r.getInspectorSnapshot(s),"snapshot"),f=c.createServer((o,t)=>{let i=H(o.url),p=i.pathname;if(o.method==="GET"&&(p==="/"||p===_chunkA5EIY3HIcjs.B)){u(t,200,k());return}if(o.method==="GET"&&p===_chunkA5EIY3HIcjs.D){try{u(t,200,r.requestGraph(_chunkA5EIY3HIcjs.p.call(void 0, {slice:i.searchParams.get("slice"),nodeIds:i.searchParams.get("nodeIds"),degreesOfSeparation:i.searchParams.get("degreesOfSeparation"),include:i.searchParams.get("include"),exclude:i.searchParams.get("exclude")})))}catch(e){if(e instanceof _chunkA5EIY3HIcjs.n){u(t,400,{error:e.message,option:e.option});return}throw e}return}if(o.method==="GET"&&p===_chunkA5EIY3HIcjs.E){L(r).then(e=>u(t,200,e)).catch(e=>{u(t,500,{error:e instanceof Error?e.message:"outbox monitor failed"})});return}if(o.method==="GET"&&p===_chunkA5EIY3HIcjs.F){W(r).then(e=>u(t,200,e)).catch(e=>{u(t,500,{error:e instanceof Error?e.message:"workflows monitor failed"})});return}if(o.method==="GET"&&p===_chunkA5EIY3HIcjs.C){t.writeHead(200,N()),t.flushHeaders(),t.write(_chunkA5EIY3HIcjs.W.call(void 0, k())),d.add(t);let e=y>0?setInterval(()=>{t.write(_chunkA5EIY3HIcjs.W.call(void 0, k()))},y):void 0;e&&h.add(e);let P=_chunkA5EIY3HIcjs.a.call(void 0, ()=>{d.delete(t),e&&(clearInterval(e),h.delete(e))},"drop");o.on("close",P),t.on("close",P);return}u(t,404,{error:"not found"})});try{await new Promise((o,t)=>{let i=_chunkA5EIY3HIcjs.a.call(void 0, p=>t(p),"onError");f.once("error",i),f.listen({host:n.bind.host,port:n.bind.port},()=>{f.off("error",i);try{s=G(f,n.bind),o()}catch(p){t(p instanceof Error?p:new (0, _chunkA5EIY3HIcjs.K)(n.bind.host))}})})}catch(o){throw await new Promise(t=>{f.close(()=>t())}),o}return{host:s.host,port:s.port,url:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,"/"),snapshotUrl:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,_chunkA5EIY3HIcjs.B),eventsUrl:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,_chunkA5EIY3HIcjs.C),graphUrl:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,_chunkA5EIY3HIcjs.D),outboxUrl:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,_chunkA5EIY3HIcjs.E),workflowsUrl:_chunkA5EIY3HIcjs.O.call(void 0, s.host,s.port,_chunkA5EIY3HIcjs.F),close(){for(let o of h)clearInterval(o);h.clear();for(let o of d)o.end();return d.clear(),new Promise((o,t)=>{f.close(i=>{i?t(i):o()})})}}}_chunkA5EIY3HIcjs.a.call(void 0, C,"listenArkRunInspector");exports.listenArkRunInspector = C;
@@ -1,18 +1 @@
1
- "use strict";var Gn=Object.create;var _=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var jn=Object.getPrototypeOf,Fn=Object.prototype.hasOwnProperty;var a=(t,e)=>_(t,"name",{value:e,configurable:!0});var H=(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)_(t,n,{get:e[n],enumerable:!0})},It=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Bn(e))!Fn.call(t,o)&&o!==n&&_(t,o,{get:()=>e[o],enumerable:!(r=Rt(e,o))||r.enumerable});return t};var Hn=(t,e,n)=>(n=t!=null?Gn(jn(t)):{},It(e||!t||!t.__esModule?_(n,"default",{value:t,enumerable:!0}):n,t)),Vn=t=>It(_({},"__esModule",{value:!0}),t),bt=(t,e,n,r)=>{for(var o=r>1?void 0:r?Rt(e,n):e,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(e,n,o):s(o))||o);return r&&o&&_(e,n,o),o};function Me(t,e){return t<e?-1:t>e?1:0}function zn(t){return[...new Set(t)].sort(Me)}function V(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return zn(e)}function Jn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function Qn(t){return typeof t=="string"&&qn.has(t)?t:"singleton"}function St(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Object.keys(t).sort(Me)){if(n.length===0)continue;let r=Jn(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function Xn(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=V(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=St(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Le(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:Qn(e.lifetime),uses:V(e.uses),reactsTo:V(e.reactsTo),raises:V(e.raises),sends:V(e.sends)},o=Xn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function Yn(t){return St(t)}function er(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!n)return;let r=e.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,i=typeof o.kind=="string"?o.kind.trim():"";if(!i)return;let s=e.residual;if(s===null||typeof s!="object"||Array.isArray(s))return;let c=s,d=typeof c.kind=="string"&&Zn.has(c.kind)?c.kind:void 0;if(!d)return;let l={kind:i},u=Yn(o.payload);u&&(l.payload=u);let y={kind:d};return typeof c.reasonCode=="string"&&c.reasonCode.length>0&&(y.reasonCode=c.reasonCode),typeof c.eventId=="string"&&c.eventId.length>0&&(y.eventId=c.eventId),typeof c.target=="string"&&c.target.length>0&&(y.target=c.target),{xiHash:n,event:l,residual:y}}function tr(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){let r=er(n);r&&e.push(r)}return e}function v(t){let e=typeof t.kernelInstanceId=="string"?t.kernelInstanceId:"",n=Array.isArray(t.components)?t.components:[],r=new Set,o=[];for(let s of n){let c=Le(s);!c||r.has(c.id)||(r.add(c.id),o.push(c))}o.sort((s,c)=>Me(s.id,c.id));let i=tr(t.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:o,...i.length>0?{decisionTape:i}:{}}}var Un,Wn,qn,Zn,U=H(()=>{"use strict";Un=["singleton","transient"],Wn=["absorb","escalate_up","hold"],qn=new Set(Un);a(Me,"compare");a(zn,"uniqueSorted");a(V,"nameList");a(Jn,"jsonPrimitive");a(Qn,"closedLifetime");a(St,"sanitizeMetadata");a(Xn,"sanitizeArkRunExtendedInfo");a(Le,"sanitizeArkRunComponent");Zn=new Set(Wn);a(Yn,"sanitizeTapePayload");a(er,"sanitizeDecisionTapeRecord");a(tr,"sanitizeDecisionTape");a(v,"buildDependencyInformationPackage")});function z(t,e){return t<e?-1:t>e?1:0}function _e(t){return[...new Set(t)].sort(z)}function xt(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function $e(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function I(t,e){if(t==null||t==="")return[];if(typeof t=="string")return _e(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 _e(n)}function Ct(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 W(t,e){return t?e.some(n=>Ct(t,n)):!1}function Ot(t){if(t==null||t==="")return rr;if(typeof t=="string"&&ir.has(t))return t;throw new R("slice")}function Nt(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 Et(t,e){if(t==null||t==="")return xt();if(typeof t=="string"||Array.isArray(t))return{...xt(),tokens:I(t,e)};if(typeof t!="object")throw new R(e);let n=t;for(let r of Object.keys(n))if(!ar.has(r))throw new R(e);return{tokens:[],ids:I(n.ids,e),labels:I(n.labels,e),tags:I(n.tags,e),groups:I(n.groups,e),architectureKinds:I(n.architectureKinds,e)}}function Dt(t={}){if(t==null||t==="")return Dt({});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(!sr.has(n))throw new R("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Ot(e.slice),nodeIds:I(e.nodeIds,"nodeIds"),degreesOfSeparation:Nt(e.degreesOfSeparation),include:Et(e.include,"include"),exclude:Et(e.exclude,"exclude")}}function Tt(t){let e={};t.slice&&(e.slice=Ot(t.slice));let n=I(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=Nt(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=I(t.include??void 0,"include");o.length>0&&(e.include=o);let i=I(t.exclude??void 0,"exclude");return i.length>0&&(e.exclude=i),e}function cr(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(!$e(e))return!0;let n=cr(t);return e.tokens.some(r=>n.some(o=>Ct(o,r)))||W(t.id,e.ids)||W(t.label,e.labels)||t.tags?.some(r=>W(r,e.tags))||W(t.group,e.groups)?!0:W(t.architectureKind,e.architectureKinds)}function dr(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return v({kernelInstanceId:e.kernelInstanceId,components:e.components})}return v({})}function lr(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 pe(t){return{id:t,kind:"interaction"}}function q(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function fe(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 ur(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(q(n,lr(i)),e==="technical"){for(let s of i.uses)q(n,n.get(s)??pe(s)),fe(r,o,i.id,s,"uses");continue}for(let s of i.raises)q(n,n.get(s)??pe(s)),fe(r,o,i.id,s,"raises");for(let s of i.reactsTo)q(n,n.get(s)??pe(s)),fe(r,o,s,i.id,"reactsTo");for(let s of i.sends)q(n,n.get(s)??pe(s)),fe(r,o,i.id,s,"sends")}return{nodes:n,edges:r}}function pr(t){let e=new Map,n=a((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 fr(t,e,n,r){let o=e.filter(c=>t.has(c));if(o.length===0)return new Set;let i=new Set,s=o.map(c=>({id:c,depth:0}));for(;s.length>0;){let c=s.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)&&s.push({id:d,depth:c.depth+1})}return i}function J(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function vt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function gr(t){let e=new Set,n=new Map;for(let r of t){let o=J(r),i=o,s=2;for(;e.has(i);)i=`${o}_${s}`,s+=1;e.add(i),n.set(r,i)}return n}function mr(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=gr(n),o=_e(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],s=a((c,d)=>{let l=r.get(c.id)??J(c.id),u=vt(c.label??c.id);i.push(`${d}${l}["${u}"]`)},"emitNode");for(let c of o){let d=J(`group_${c}`);i.push(` subgraph ${d}["${vt(c)}"]`);for(let l of t.nodes)l.group===c&&s(l," ");i.push(" end")}for(let c of t.nodes)c.group||s(c," ");for(let c of t.edges){let d=r.get(c.from)??J(c.from),l=r.get(c.to)??J(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
- `)}function yr(t,e,n){let r=new Set(t.keys());if($e(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&Pt(d,n.include)}))),$e(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=fr(r,n.nodeIds,n.degreesOfSeparation,pr(o)));let i=[...r].sort(z).map(c=>t.get(c)).filter(c=>!!c),s=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,d)=>z(c.from,d.from)||z(c.kind,d.kind)||z(c.to,d.to));return{nodes:i,edges:s}}function Mt(t={},e={}){let n=dr(t),r=Dt(e),o=ur(n.components,r.slice),i=yr(o.nodes,o.edges,r),s={schemaVersion:nr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return s.mermaid=mr(s),s}var nr,rr,or,R,ir,sr,ar,Ke=H(()=>{"use strict";U();nr="1.0",rr="process",or=["process","technical"],R=class extends Error{static{a(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}},ir=new Set(or),sr=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),ar=new Set(["ids","labels","tags","groups","architectureKinds"]);a(z,"compare");a(_e,"uniqueSorted");a(xt,"emptyMatch");a($e,"matchHasCriteria");a(I,"nameList");a(Ct,"globMatch");a(W,"anyGlob");a(Ot,"closedSlice");a(Nt,"closedDegrees");a(Et,"closedMatch");a(Dt,"closeArkRunGraphQuery");a(Tt,"arkRunGraphQueryFromSearchParams");a(cr,"nodeFields");a(Pt,"nodeMatches");a(dr,"asPackage");a(lr,"componentNode");a(pe,"interactionNode");a(q,"addNode");a(fe,"addEdge");a(ur,"buildSlice");a(pr,"adjacency");a(fr,"neighborhood");a(J,"mermaidSafeId");a(vt,"mermaidLabel");a(gr,"uniqueMermaidIds");a(mr,"formatArkRunGraphMermaid");a(yr,"filterGraph");a(Mt,"requestArkRunGraph")});function kr(t){if(t===void 0)return"local";if(typeof t=="string"&&hr.has(t))return t;throw new ge("transport")}function wr(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new ge("ephemeral")}function Lt(t){let e=kr(t.transport),n=wr(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 Ge,hr,ge,me=H(()=>{"use strict";Ge=["local","localBlocking","broker"],hr=new Set(Ge),ge=class extends Error{static{a(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}};a(kr,"closedArkRunTransportKind");a(wr,"closedArkRunEphemeral");a(Lt,"resolveArkRunSendPlan")});function $t(t){return t==="production"}function Er(t){let e=t.split(".");if(e.length!==4)return;let n=[];for(let r of e){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function Kt(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function he(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=Kt(e);if(n)return he(n);let r=Er(e);return r!==void 0&&r[0]===127}function Gt(t){if(t===void 0)return _t;if(typeof t!="string")throw new b(String(t));let e=t.trim();if(xr.has(e.toLowerCase())||!he(e))throw new b(e);let n=e.toLowerCase();if(n==="localhost")return _t;if(n==="[::1]")return"::1";let r=Kt(n);return r?Gt(r):n}function Pr(t){if(t===void 0)return Ir;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new b(`port:${String(t)}`);return t}function We(t={}){if($t(t.nodeEnv)||$t(t.processNodeEnv))throw new ye;return{host:Gt(t.host),port:Pr(t.port)}}function C(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function vr(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function Cr(t){return{kinds:[...Ge],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:Sr}}function E(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Or(t){let e=E(t);if(!e||typeof e.id!="string")return;let n=e.status;if(n!=="pending"&&n!=="failed")return;let r=E(e.event),o=r&&typeof r.intent=="string"?r.intent:typeof e.intent=="string"?e.intent:void 0,i={id:e.id,status:n,attempts:typeof e.attempts=="number"&&Number.isFinite(e.attempts)?e.attempts:0};return o&&(i.intent=o),typeof e.error=="string"&&e.error.length>0&&(i.error=e.error),typeof e.updatedAt=="string"&&(i.updatedAt=e.updatedAt),i}function ke(t){if(typeof t!="number"||!Number.isFinite(t))return A;let e=Math.trunc(t);return e<0?0:e>A?A:e}function Z(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():t&&typeof t=="object"&&"constructor"in t?String(t.constructor?.name??e):e,r=/^InMemory/i.test(n)?"memory":"durable";return{role:e,id:n,kind:r}}function qe(t={}){let e=E(t),n=E(e?.durability)??e,r=Array.isArray(n?.stores)?n.stores:Array.isArray(e?.stores)?e.stores:[],o=[];for(let i of r){let s=E(i);if(!s)continue;let c=s.role;if(c!=="outbox"&&c!=="audit"&&c!=="workflow")continue;let d=typeof s.id=="string"?s.id:typeof s.name=="string"?s.name:void 0;if(!d)continue;let l=s.kind==="memory"||s.kind==="durable"?s.kind:Z(d,c).kind;o.push({role:c,id:d,kind:l})}return{durability:{stores:o}}}function Y(t=[],e={}){let n=ke(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=[];for(let s of r){let c=Or(s);c&&(c.status==="pending"?o.push(c):i.push(c))}return{available:!0,pendingCount:o.length,failedCount:i.length,pending:o.slice(0,n),failed:i.slice(0,n),sampleLimit:n}}function Q(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:A}}function Nr(t){let e=E(t);if(!e||typeof e.id!="string")return;let n=typeof e.workflowName=="string"?e.workflowName:typeof e.name=="string"?e.name:void 0;if(!n)return;let r={id:e.id,name:n,status:typeof e.status=="string"?e.status:"unknown"};return typeof e.currentStep=="string"&&(r.currentStep=e.currentStep),typeof e.error=="string"&&e.error.length>0&&(r.error=e.error),r}function Dr(t){return t==="idle"||t==="waiting"}function ee(t=[],e={}){let n=ke(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=0,s=0,c=0,d=0;for(let l of r){let u=Nr(l);u&&(o.push(u),u.status==="running"?i+=1:u.status==="compensating"?s+=1:u.status==="failed"?c+=1:Dr(u.status)&&(d+=1))}return{available:!0,total:o.length,runningCount:i,compensatingCount:s,failedCount:c,pendingCount:d,workflows:o.slice(0,n),sampleLimit:n}}function X(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:A}}function Tr(t){if(t===void 0)return;let e=E(t);if(!e||e.available===!1)return Q();let n=ke(e.sampleLimit);if(Array.isArray(e.pending)||Array.isArray(e.failed)||Array.isArray(e.records)){let r=[...Array.isArray(e.pending)?e.pending:[],...Array.isArray(e.failed)?e.failed:[],...Array.isArray(e.records)?e.records:[]],o=Y(r,{sampleLimit:n}),i=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):o.pendingCount,s=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):o.failedCount;return{...o,pendingCount:i,failedCount:s,sampleLimit:n}}return Q()}function Mr(t){if(t===void 0)return;let e=E(t);if(!e||e.available===!1)return X();let n=ke(e.sampleLimit);if(Array.isArray(e.workflows)){let r=ee(e.workflows,{sampleLimit:n}),o=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):r.total,i=typeof e.runningCount=="number"&&Number.isFinite(e.runningCount)?Math.max(0,Math.trunc(e.runningCount)):r.runningCount,s=typeof e.compensatingCount=="number"&&Number.isFinite(e.compensatingCount)?Math.max(0,Math.trunc(e.compensatingCount)):r.compensatingCount,c=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):r.failedCount,d=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:i,compensatingCount:s,failedCount:c,pendingCount:d,sampleLimit:n}}return X()}function Bt(t={}){let e=We({host:t.host,port:t.port}),n=v({kernelInstanceId:t.kernelInstanceId,components:t.package&&typeof t.package=="object"&&!Array.isArray(t.package)&&Array.isArray(t.package.components)?t.package.components:[]}),r=Tr(t.outbox),o=Mr(t.workflows),i={schemaVersion:Ar,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Cr(t),observability:vr(t.observability)??{},hardening:qe(t.hardening)};return r&&(i.outbox=r),o&&(i.workflows=o),i}function ze(t){return`event: ${br}
3
- data: ${JSON.stringify(t)}
4
-
5
- `}var Ar,_t,Ir,je,Fe,He,Ve,Ue,br,Sr,A,ye,b,xr,we=H(()=>{"use strict";U();me();Ar="1.0",_t="127.0.0.1",Ir=0,je="/snapshot",Fe="/events",He="/graph",Ve="/outbox",Ue="/workflows",br="snapshot",Sr="in-process-local",A=32,ye=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},b=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},xr=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a($t,"isArkRunInspectorProductionEnv");a(Er,"ipv4Octets");a(Kt,"unwrapIpv4Mapped");a(he,"isArkRunInspectorLoopbackHost");a(Gt,"closedHost");a(Pr,"closedPort");a(We,"resolveArkRunInspectorBind");a(C,"arkRunInspectorUrl");a(vr,"jsonClone");a(Cr,"closedTransportFacts");a(E,"asRecord");a(Or,"closedOutboxSummary");a(ke,"closedSampleLimit");a(Z,"classifyArkRunInspectorStoreDurability");a(qe,"buildArkRunInspectorHardening");a(Y,"buildArkRunInspectorOutboxMonitor");a(Q,"unavailableArkRunInspectorOutboxMonitor");a(Nr,"closedWorkflowSummary");a(Dr,"isPendingWorkflowStatus");a(ee,"buildArkRunInspectorWorkflowsMonitor");a(X,"unavailableArkRunInspectorWorkflowsMonitor");a(Tr,"closedOutboxMonitor");a(Mr,"closedWorkflowsMonitor");a(Bt,"buildArkRunInspectorSnapshot");a(ze,"formatArkRunInspectorSseEvent")});var vn={};At(vn,{listenArkRunInspector:()=>xo});function wo(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Ro(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Ao(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function P(t,e,n){if(!(t.writableEnded||t.destroyed))try{t.writeHead(e,wo()),t.end(JSON.stringify(n))}catch{}}function Io(t,e){let n=t.address();if(n===null||typeof n=="string")throw new b(e.host);if(!he(n.address))throw new b(n.address);return{host:e.host,port:n.port}}async function bo(t){if(typeof t.listInspectorOutbox=="function")return t.listInspectorOutbox();let e=t.outbox??t.eventBuffer;if(!e||typeof e.list!="function")return Q();let[n,r]=await Promise.all([e.list("pending"),e.list("failed")]);return Y([...n??[],...r??[]],{sampleLimit:A})}async function So(t){return typeof t.listInspectorWorkflows=="function"?t.listInspectorWorkflows():!t.workflowEngine||typeof t.workflowEngine.list!="function"?X():ee(await t.workflowEngine.list(),{sampleLimit:A})}async function xo(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,s=e.bind,c=a(()=>t.getInspectorSnapshot(s),"snapshot"),d=n.createServer((l,u)=>{let y=Ao(l.url),f=y.pathname;if(l.method==="GET"&&(f==="/"||f===je)){P(u,200,c());return}if(l.method==="GET"&&f===He){try{P(u,200,t.requestGraph(Tt({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof R){P(u,400,{error:g.message,option:g.option});return}throw g}return}if(l.method==="GET"&&f===Ve){bo(t).then(g=>P(u,200,g)).catch(g=>{P(u,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(l.method==="GET"&&f===Ue){So(t).then(g=>P(u,200,g)).catch(g=>{P(u,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(l.method==="GET"&&f===Fe){u.writeHead(200,Ro()),u.flushHeaders(),u.write(ze(c())),r.add(u);let g=i>0?setInterval(()=>{u.write(ze(c()))},i):void 0;g&&o.add(g);let h=a(()=>{r.delete(u),g&&(clearInterval(g),o.delete(g))},"drop");l.on("close",h),u.on("close",h);return}P(u,404,{error:"not found"})});try{await new Promise((l,u)=>{let y=a(f=>u(f),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{s=Io(d,e.bind),l()}catch(f){u(f instanceof Error?f:new b(e.bind.host))}})})}catch(l){throw await new Promise(u=>{d.close(()=>u())}),l}return{host:s.host,port:s.port,url:C(s.host,s.port,"/"),snapshotUrl:C(s.host,s.port,je),eventsUrl:C(s.host,s.port,Fe),graphUrl:C(s.host,s.port,He),outboxUrl:C(s.host,s.port,Ve),workflowsUrl:C(s.host,s.port,Ue),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,u)=>{d.close(y=>{y?u(y):l()})})}}}var Cn=H(()=>{"use strict";Ke();we();a(wo,"jsonHeaders");a(Ro,"sseHeaders");a(Ao,"requestUrl");a(P,"writeJson");a(Io,"boundAddress");a(bo,"resolveOutboxMonitor");a(So,"resolveWorkflowsMonitor");a(xo,"listenArkRunInspector")});var No={};At(No,{ARK_KERNEL:()=>j,ArkModule:()=>x,InjectArk:()=>Oo});module.exports=Vn(No);var Oe=require("@nestjs/common");Ke();we();U();me();var jt=0;function Lr(){return jt+=1,`audit-${Date.now()}-${jt}`}a(Lr,"createAuditId");function _r(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)}a(_r,"matchesQuery");var Re=class{constructor(e){this.maxRecords=e}maxRecords;static{a(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=>_r(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},Ae=class{constructor(e){this.store=e}store;static{a(this,"AuditTrailImpl")}async record(e){let n={id:Lr(),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 Je(t={}){return new Ae(t.store??new Re(t.maxRecords))}a(Je,"createAuditTrail");var O=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
- `);super(`Hard policy violation(s) detected:
7
- ${n}`),this.name="PolicyViolationError",this.violations=e}};var $=class{static{a(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 s=i.check(e);if(s!==!0){if(s===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(s))for(let c of s)n.push({policyName:i.name,severity:i.severity,message:c.message,details:c.details});else n.push({policyName:i.name,severity:i.severity,message:s.message,details:s.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 O(n.hardViolations);return n}clear(){this.policies.length=0}};function Ie(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}}a(Ie,"definePolicy");function $r(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}a($r,"defaultLayerOf");function Ft(t,e){return e.resolveLayer?.(t)??$r(t)}a(Ft,"resolveLayer");function Kr(t,e,n){return t===n.from&&e===n.to}a(Kr,"matchesRule");function Ht(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Ie({name:e,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(s=>s.kind==="declared"||s.kind==="produces").map(s=>({from:s.from,to:s.to})),...(r.relationships??[]).filter(s=>s.kind==="dependsOn").map(s=>({from:s.from,to:s.to}))],i=[];for(let s of o){let c=Ft(s.from,t),d=Ft(s.to,t);for(let l of t.rules)!l.allowed&&Kr(c,d,l)&&i.push({policyName:e,severity:n,message:l.message??`Layer violation: ${s.from} (${c}) must not relate to ${s.to} (${d})`})}return i.length>0?i:!0},"check")})}a(Ht,"defineLayerPolicy");function Qe(t){return t.tags?.includes("layer")??!1}a(Qe,"isLayerPolicy");function Xe(t,e={}){return Ht({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}a(Xe,"defineArchitectureProfilePolicy");function Ze(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}a(Ze,"buildPublishPolicyContext");var te=class extends Error{static{a(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}},ne=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},re=class extends Error{static{a(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"}},oe=class extends Error{static{a(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}},K=class extends Error{static{a(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}},N=class extends Error{static{a(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}},ie=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}};var Vt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ye(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Vt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Vt.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}a(Ye,"validateIntentName");function se(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ye(t);if(!n.valid)throw new ne(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new te(t)}}a(se,"assertIntentAllowed");function Ut(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new K(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new K(t.intent,t.metadata.source)}}a(Ut,"assertSourceAllowed");function ae(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new oe(t.intent,n.issues)}a(ae,"assertContractAllowed");function G(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}a(G,"isPlainRecord");function B(t){return Array.isArray(t)?t.map(B):G(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,B(n)])):t}a(B,"clonePatchValue");function et(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let s=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=B(i);continue}if(G(r[o])&&G(i)){r[o]=et(r[o],i,s);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=tt(r[o],i,s);continue}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}return r}a(et,"mergeRecordPatch");function tt(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let s=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=B(o);return}if(G(r[i])&&G(o)){r[i]=et(r[i],o,s);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=tt(r[i],o,s);return}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}),r}a(tt,"mergeArrayPatch");function Wt(t,e){if(Array.isArray(e)){if(t===void 0)return B(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return tt(t,e)}if(t===void 0)return B(e);if(!G(t))throw new Error("Object interceptor patch requires an object payload.");return et(t,e)}a(Wt,"applyPayloadPatch");async function qt(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:a(d=>{i.push(d)},"intercept")})),i.length===0)continue;let s=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:s}]}};for(let d of i)c={...c,payload:Wt(c.payload,d),metadata:{...c.metadata}};ae(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=s,e.appendTrace({type:"event.intercepted",timestamp:s,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(s){await Gr(o,r,s,e)}}return r}a(qt,"applyInterceptors");async function Gr(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})}a(Gr,"recordInterceptorError");var zt=new Map;function Jt(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}a(Jt,"escapeLiteral");function tn(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}a(tn,"normalizeGlobSeparators");function Br(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}a(Br,"bracesBalanced");function Qt(t){let e=zt.get(t);if(e)return e;let n=tn(t),r=Br(n),o="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(o+=Jt(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":d==="?"?o+="[^/]":d==="{"&&r?(o+="(?:",i+=1):d==="}"&&r&&i>0?(o+=")",i-=1):d===","&&r&&i>0?o+="|":o+=Jt(d)}let s=new RegExp(`^${o}$`);return zt.set(t,s),s}a(Qt,"globToRegExp");function Xt(t,e,n){if(!e?.length)return;let r=n==="stars"?"stars":"path",o=String(t).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let i=new Set;for(let s of e)if(!(typeof s!="string"||s.length===0)){if(jr(s)){let c=Fr(o,s,r);if(c)return c;continue}!s.includes("/")&&!s.includes("\\")&&!s.includes("*")&&i.add(s.toLowerCase())}return Vr(o,i)}a(Xt,"sliceIdForPath");function jr(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}a(jr,"isAnchoredSliceEntry");function Fr(t,e,n){let r=e.split(/[/\\]/).filter(i=>i.length>0).map(i=>i.toLowerCase()),o=rn(t,r[0]??"");for(let i of o){let s=Hr(t,r,i,n);if(s)return s}}a(Fr,"anchoredSliceId");function Hr(t,e,n,r="path"){let o=[],i=-1,s=n;for(let c=0;c<e.length;c+=1){let d=e[c];if(d==="*"){if(s>=t.length-1){for(let l=c;l<e.length;l+=1)if(e[l]!=="*")return;break}o.push(t[s].toLowerCase()),s+=1;continue}if(d==="**"||s>=t.length||t[s].toLowerCase()!==d)return;o.push(t[s].toLowerCase()),i=o.length-1,s+=1}if(o.length!==0)return r==="stars"?i<0?void 0:o.slice(i).join("/"):o.join("/")}a(Hr,"bindAnchoredSlice");function Vr(t,e){if(e.size!==0){for(let n=0;n<t.length-1;n+=1)if(e.has(t[n].toLowerCase())&&!(n+1>=t.length-1))return`${t[n].toLowerCase()}/${t[n+1].toLowerCase()}`}}a(Vr,"bareSliceId");function Ur(t){let e=new Set;for(let n of t??[]){let o=tn(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let s=o[i];if((s==="**"||s==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}a(Ur,"inferSliceFoldersFromPatterns");function Wr(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 Ur(r?.patterns)}a(Wr,"resolveSliceFolders");function Zt(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}a(Zt,"normalizeSegments");function nn(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(nn,"trimTrailingSlashes");var qr=["src","app"];function rn(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return qr.includes(n)&&r!==n?[0,1]:[0]}a(rn,"anchorOffsets");function zr(t){let e=nn(t.replace(/^[./]+/,""));return e==="*"||e==="**"}a(zr,"isBlanketRoot");function Yt(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Zt(n);for(let i of e){if(typeof i!="string"||i.length===0||zr(i))continue;if(i.includes("*")){let d=nn(i.toLowerCase());if(Qt(d).test(r)||Qt(`${d}/**`).test(r))return!0;continue}let s=Zt(i);if(s.length===0)continue;let c=rn(o,s[0]??"");for(let d of c){if(d+s.length>o.length)continue;let l=!0;for(let u=0;u<s.length;u+=1)if(o[d+u]!==s[u]){l=!1;break}if(l)return!0}}return!1}a(Yt,"pathUnderSharedRoot");function en(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(en,"sliceMatchesDeclaration");function Jr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&en(r.from,e)&&en(r.to,n))}a(Jr,"crossSliceEdgeAllowed");function Qr(t){if(!t.fromPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0;if(!t.toPath)return e?t.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:t.sharedImportsSlice==="deny"&&t.fromShared===!0&&t.toSlice&&!t.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Qr,"peerIsolationDecision");function on(t,e,n,r){return Xr(t,e,n,r)?.rule}a(on,"findDeniedEdgeRule");function Xr(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,s=r?.toPath,c=Wr(o,e,r?.layers),d=i?Xt(i,c,o.sliceIdentity):void 0,l=s?Xt(s,c,o.sliceIdentity):void 0,u=Qr({fromPath:i,toPath:s,folderCount:c.length,fromSlice:d,toSlice:l,fromShared:!d&&Yt(i,o.sharedRoots),toShared:!l&&Yt(s,o.sharedRoots),crossSliceAllowed:Jr(o.allowedCrossSlice,d,l),sharedImportsSlice:o.sharedImportsSlice});if(u.denied)return{rule:o,peerIsolationReason:u.reason,fromSlice:d,toSlice:l};continue}if(e!==n)return{rule:o}}}a(Xr,"findDeniedEdgeDecision");async function sn(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 s=on(r.rules,o,i);if(!s)return;let c=e.mode,d=s.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:s};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 ie(n,t.intent,o,i,d)}a(sn,"assertObservedLayerFlowAllowed");async function an(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof O&&(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))}a(an,"enforcePublishPolicy");function Zr(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}a(Zr,"appendHistory");function ce(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{}}a(ce,"appendTrace");async function be(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){ce(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)}})}}a(be,"recordAudit");async function cn(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."};ce(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 be(t,"event.rawPublish",e,n)}a(cn,"recordRawPublishDiagnostic");async function dn(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return Zr(t,o),await t.eventBuffer?.enqueue(e,r),ce(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 be(t,"event.published",e,{subscribersNotified:n}),o}a(dn,"recordSuccessfulPublish");function nt(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}}a(nt,"enrichMetadata");var ln=0;function Yr(){return ln+=1,`interceptor-${Date.now()}-${ln}`}a(Yr,"nextInterceptorRegistrationId");var de=class{static{a(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 $(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Qe)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new re;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ze({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,s=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,d,l=typeof e!="function";if(l){let f=e,g=r??n??{};d={...f,metadata:nt(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,h=r??{},p=f(g);d={...p,metadata:nt(p.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await cn(this.recording,d),se(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ut(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ae(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await qt(d,{interceptorsForIntent:a(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),ae(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await sn(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let u=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await an(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((f,g,h)=>this.safeHook(f,g,h),"safeHook")}),await dn(this.recording,d,i?u.length:0,o.tx);let y=(async()=>{i&&await Promise.all(u.map(f=>this.invokeHandler(f,d))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(d),"onPublish",d)})();return s?await y:y.then(void 0,()=>{}),d}createPublisher(e){let n=typeof e=="string"?e:e.name;return se(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,i={},s)=>{if(i.source&&i.source!==n)throw new N(n,i.source);await this.publish(r,o,{...i,source:n},s)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;se(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 s=this.subscriptions.indexOf(o);s>=0&&this.subscriptions.splice(s,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;se(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Yr(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let s=this.interceptorsByIntent.get(o)??[];return s.push(i),this.interceptorsByIntent.set(o,s),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){ce(this.recording,e)}async recordAudit(e,n,r){await be(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 eo(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}a(eo,"formatStandardSchemaPath");function to(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"}a(to,"actualType");function no(t,e){return t?`${t}.${e}`:e}a(no,"formatPath");function un(t,e,n,r,o){let i=to(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(s=>Object.is(s,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}pn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((s,c)=>{un(s,e.items,`${n}[${c}]`,r,o)})}a(un,"validateSchemaField");function pn(t,e,n,r,o){for(let[i,s]of Object.entries(e)){let c=no(o,i),d=t[i];if(d===void 0){s.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}un(d,s,c,n,r)}}a(pn,"validateObjectSchema");var Se=class{static{a(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(pn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let s of Object.keys(i))r.schema[s]||o.push({intent:e.intent,version:r.version,field:s,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let s=r.standardSchema["~standard"].validate(e.payload);if(s instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(s.issues)for(let c of s.issues)o.push({intent:e.intent,version:r.version,field:eo(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 rt(){return new Se}a(rt,"createEventContractRegistry");var xe=class{static{a(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
- `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
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
- `);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let s=e.resolveLayer(i)??"Unclassified",c=n.get(s)??[];c.push(i),n.set(s,c)}let r=`flowchart TD
11
- `;for(let i of e.layers){let s=n.get(i.name)??[];if(s.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
12
- `;for(let c of s)r+=` ${this.safeId(c)}[${c}]
13
- `;r+=` end
14
- `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
15
- `;for(let i of o)r+=` ${this.safeId(i)}[${i}]
16
- `;r+=` end
17
- `}for(let i of this.edges){let s=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${s} ${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=a(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),u=o.slice(l).concat(d);n.push(u)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let s=new Set(n.map(c=>c.join("->")));return Array.from(s).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function ot(){return new xe}a(ot,"createDependencyGraph");function it(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"))}a(it,"syncRegistryToGraph");var le=class{static{a(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=a(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 Rs=new le;function st(){return new le}a(st,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...D,default:[]},kernelRoots:{...D},managedLayers:{...D,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},gn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...D,default:[]},managedLayers:{...D,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...D,default:[]},appliesTo:{...D,default:[]}}};var mn="1.3",ro=["public","auth","admin","internal"];var yn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",hn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],oo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function io(){let t=[];for(let e of hn)for(let n of hn)e===n||oo.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}a(io,"createDefaultRules");var at=io();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},js={$schema:"https://json-schema.org/draft/2020-12/schema",$id:yn,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:yn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:mn,default:mn},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:at,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...w,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...ro]},owners:{...w,minItems:1},forbiddenGlobals:w,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:{...w,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...w,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...w,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...w,minItems:1}}},arkRun:fn,arkOrder:gn}};function so(t){return t.endsWith(".")?t:`${t}.`}a(so,"normalizePrefix");function ao(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}a(ao,"byLongestPrefix");function kn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(so)})),n=[...e].sort(ao),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(s=>o.startsWith(s)))?.name}}}a(kn,"createArchitectureProfile");var co=[{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}],ct=kn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:co,rules:at.map(t=>({...t}))});var wn="4.8.22";function uo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(uo,"policyId");var dt=class{constructor(e){this.data=e}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function lt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,s=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],u=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:uo(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),p=s?s.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:s.getCheckpoint(m.name)})):[],F={schemaVersion:"1.0",version:wn,exportedAt:new Date().toISOString(),intents:l,relationships:u,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new dt(F)}a(lt,"createArkManifest");var Ee=class{static{a(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 ut(){return new Ee}a(ut,"createMetadataRegistry");function pt(t){return`${t.from}->${t.to}`}a(pt,"flowKey");function An(t){let e=new Set,n=[];for(let r of t){let o=pt(r);e.has(o)||(e.add(o),n.push(r))}return n}a(An,"uniqueFlows");function In(t,e){let n=new Set(e.map(pt));return t.filter(r=>!n.has(pt(r)))}a(In,"difference");function ft(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})),s=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=s.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),d=An([...o,...i]),l=An([...s,...c]),u=l.filter(p=>!p.from||p.from==="unknown"),y=e?Array.from(new Set(l.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(l.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(l.flatMap(p=>[p.from,p.to])),h=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:In(d,l),observedButUndeclared:In(l.filter(p=>p.from!=="unknown"),d),unknownSources:u,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}a(ft,"createObservabilityReporter");var bn=0;function po(){return bn+=1,`outbox-${Date.now()}-${bn}`}a(po,"nextOutboxId");function Sn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}a(Sn,"cloneRecord");var ue=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:po(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Sn(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(Sn)}async clear(){this.records.clear()}};var Pe=class{static{a(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 fo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}a(fo,"initialState");var ve=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Pe,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)??fo(r),i=await r.project(e,o);await this.store.save(r.name,i);let s=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(s?.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 gt(t){return new ve(t)}a(gt,"createProjectionRegistry");var xn=0;function go(t){return xn+=1,`${t}-${Date.now()}-${xn}`}a(go,"createWorkflowId");function mt(t){return t instanceof Error?t.message:String(t)}a(mt,"errorMessage");function mo(t){return new Promise(e=>{setTimeout(e,t)})}a(mo,"sleep");async function yo(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((s,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)}}a(yo,"withTimeout");var Ce=class{static{a(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 s=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||s){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()}},yt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Ce}bus;options;static{a(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(),s={id:r.id??go(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(s,r.tx),await this.audit("workflow.started",s,{workflowName:e}),this.executeSnapshot(s,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=mt(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 s=1;s<=i;s+=1){e.attempts[n.name]=s,await this.store.save(e,r);let c;try{c=await yo(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(s<i){o.delayMs&&await mo(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:s,error:mt(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:s});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(s=>e.completedSteps.includes(s.name));for(let s=i.length-1;s>=0;s-=1){let c=i[s];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:mt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function ht(t,e){return new yt(t,e)}a(ht,"createWorkflowEngine");U();var ho=new Set(["singleton","transient"]);function En(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}a(En,"cloneComponent");function ko(t){if(t===void 0)return"singleton";if(typeof t=="string"&&ho.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(ko,"closedLifetime");function Pn(){let t=new Map,e=new Map,n=new Set;function r(s){let c=t.get(s);if(!c)throw new Error(`ArkRun component "${s}" is not registered.`);return c}a(r,"mustRecord");function o(s,c){if(!c.factory)throw new Error(`ArkRun component "${s}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(s))throw new Error(`ArkRun component "${s}" has a circular resolve.`);n.add(s);try{return c.factory()}finally{n.delete(s)}}a(o,"instantiate");function i(s,c){if(e.has(s))return e.get(s);let d=o(s,c);return e.set(s,d),d}return a(i,"singleton"),{register(s){let c=typeof s?.id=="string"?s.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=ko(s.lifetime),l=Le({id:c,lifetime:d,uses:s.uses,reactsTo:s.reactsTo,raises:s.raises,sends:s.sends,extendedInfo:s.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof s.factory=="function"?s.factory:void 0;return t.set(c,{component:l,factory:u}),En(l)},resolve(s){let c=r(s);return c.component.lifetime==="transient"?o(s,c):i(s,c)},resolveSingleton(s){let c=r(s);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${s}" is transient; resolveSingleton requires lifetime "singleton".`);return i(s,c)},snapshotComponents(){return[...t.values()].map(s=>En(s.component))}}}a(Pn,"createComponentRegistry");we();async function On(t,e={}){let n=We({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Cn(),vn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}a(On,"startArkRunInspector");me();function Eo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new N(t.source,e.source);return e.source=t.source,e}a(Eo,"stampMetadata");function Po(){}a(Po,"ignoreDetachedFailure");async function kt(t,e,n,r={}){let o=Lt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Eo(r),s=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(s));o.awaitHandoff?await c:c.then(void 0,Po)}return o}a(kt,"sendOnArkRunTransport");var vo=1e3,Nn=0;function Co(){return Nn+=1,`ark-kernel-${Date.now()}-${Nn}`}a(Co,"nextKernelInstanceId");function Dn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}a(Dn,"portConstructorId");function Tn(t={}){let e=t.strict??!0,n=t.instanceId??Co(),r=t.profile??ct,o=t.maxHistorySize??vo,i=st(),s=ot(),c=t.metadata??ut(),d=t.auditTrail===void 0,l=t.auditTrail??Je({maxRecords:o}),u=t.eventContracts??rt(),y=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new ue,g=t.projections??gt({auditTrail:l}),h=new $([Xe(r),...t.policies??[]]),p=a(()=>{it(i,s,{requireRegisteredTargets:!0})},"syncGraph"),F=t.ephemeral??!0,m=t.broker,T=new de({intentRegistry:i,dependencyGraph:s,policyEngine:h,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:u,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 g.apply(k)}}),wt=ht(T,{auditTrail:l}),Ne=ft({registry:i,eventBus:T,graph:s}),M=Pn(),Mn=typeof m?.send=="function",Ln=y?"InMemoryEventBuffer":Dn(f,"EventBufferStore"),_n=d?"InMemoryAuditStore":Dn(l,"AuditTrail"),$n=qe({stores:[Z(Ln,"outbox"),Z(_n,"audit"),Z("InMemoryWorkflowStore","workflow")]}),De={instanceId:n,profile:r,registry:i,graph:s,metadata:c,auditTrail:l,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:h,eventBus:T,workflowEngine:wt,observability:Ne,publisher(k){let L=T.createPublisher(k);return{source:L.source,publish:L.publish,send(S,Te,Kn={}){return kt({eventBus:T,broker:m,defaultEphemeral:F},S,Te,{...Kn,source:L.source})}}},send(k,L,S={}){return kt({eventBus:T,broker:m,defaultEphemeral:F},k,L,S)},register(k){return M.register(k)},resolve(k){return M.resolve(k)},resolveSingleton(k){return M.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:M.snapshotComponents()})},requestGraph(k){return Mt({kernelInstanceId:n,components:M.snapshotComponents()},k)},getInspectorSnapshot(k){return Bt({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:M.snapshotComponents()},observability:Ne.report(),ephemeralDefault:F,brokerBound:Mn,hardening:$n})},startInspector(k){return On({getInspectorSnapshot:a(S=>De.getInspectorSnapshot(S),"getInspectorSnapshot"),requestGraph:a(S=>De.requestGraph(S),"requestGraph"),async listInspectorOutbox(){let[S,Te]=await Promise.all([f.list("pending"),f.list("failed")]);return Y([...S,...Te],{sampleLimit:A})},async listInspectorWorkflows(){return ee(await wt.list(),{sampleLimit:A})}},k)},syncGraph:p,manifest(){return p(),lt({registry:i,policyEngine:h,metadata:c,graph:s,profile:r,projections:g,eventContracts:u,observability:Ne})}};return De}a(Tn,"createArkKernel");var j=Symbol("ARK_KERNEL"),Oo=a(()=>(0,Oe.Inject)(j),"InjectArk"),x=class{static forRoot(e){let n=e&&"registry"in e?e:Tn(e);return{module:x,global:!0,providers:[{provide:j,useValue:n}],exports:[j]}}static forRootAsync(e){return{module:x,global:!0,providers:[{provide:j,useFactory:e.useFactory,inject:e.inject??[]}],exports:[j]}}};a(x,"ArkModule"),x=bt([(0,Oe.Module)({})],x);0&&(module.exports={ARK_KERNEL,ArkModule,InjectArk});
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkRNQHRDCQcjs = require('../chunk-RNQHRDCQ.cjs');var _chunkA5EIY3HIcjs = require('../chunk-A5EIY3HI.cjs');var _common = require('@nestjs/common');var t=Symbol("ARK_KERNEL"),y= exports.InjectArk =_chunkA5EIY3HIcjs.a.call(void 0, ()=>_common.Inject.call(void 0, t),"InjectArk"),e= exports.ArkModule =class{static forRoot(r){let i=r&&"registry"in r?r:_chunkRNQHRDCQcjs.va.call(void 0, r);return{module:e,global:!0,providers:[{provide:t,useValue:i}],exports:[t]}}static forRootAsync(r){return{module:e,global:!0,providers:[{provide:t,useFactory:r.useFactory,inject:_nullishCoalesce(r.inject, () => ([]))}],exports:[t]}}};_chunkA5EIY3HIcjs.a.call(void 0, e,"ArkModule"),e= exports.ArkModule =_chunkA5EIY3HIcjs.b.call(void 0, [_common.Module.call(void 0, {})],e);exports.ARK_KERNEL = t; exports.ArkModule = e; exports.InjectArk = y;
@@ -0,0 +1,22 @@
1
+ import { DynamicModule, InjectionToken, OptionalFactoryDependency } from '@nestjs/common';
2
+ import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-DRinG-vT.cjs';
3
+
4
+ /** Injection token for the Ark kernel instance. */
5
+ declare const ARK_KERNEL: unique symbol;
6
+ /** Constructor-parameter decorator that injects the Ark kernel. */
7
+ declare const InjectArk: () => ParameterDecorator;
8
+ interface ArkModuleAsyncOptions {
9
+ /** Factory that builds (or resolves) the kernel; supports Nest DI via `inject`. */
10
+ useFactory: (...deps: never[]) => ArkKernel | Promise<ArkKernel>;
11
+ inject?: Array<InjectionToken | OptionalFactoryDependency>;
12
+ }
13
+ declare class ArkModule {
14
+ /**
15
+ * Registers a global Ark kernel. Pass an existing kernel to share one across
16
+ * processes/tests, or options to create a fresh strict kernel.
17
+ */
18
+ static forRoot(kernelOrOptions?: ArkKernel | CreateArkKernelOptions): DynamicModule;
19
+ static forRootAsync(options: ArkModuleAsyncOptions): DynamicModule;
20
+ }
21
+
22
+ export { ARK_KERNEL, ArkKernel, ArkModule, type ArkModuleAsyncOptions, CreateArkKernelOptions, InjectArk };
@@ -1,7 +1,5 @@
1
1
  import { DynamicModule, InjectionToken, OptionalFactoryDependency } from '@nestjs/common';
2
- import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-yDNEQ603.js';
3
- import '../types-fQ9-KrBj.js';
4
- import '../configTypes-CTELo87-.js';
2
+ import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-DRinG-vT.js';
5
3
 
6
4
  /** Injection token for the Ark kernel instance. */
7
5
  declare const ARK_KERNEL: unique symbol;
@@ -1,18 +1 @@
1
- var De=Object.defineProperty;var Ln=Object.getOwnPropertyDescriptor;var a=(t,e)=>De(t,"name",{value:e,configurable:!0});var j=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var _n=(t,e)=>{for(var n in e)De(t,n,{get:e[n],enumerable:!0})};var wt=(t,e,n,r)=>{for(var o=r>1?void 0:r?Ln(e,n):e,i=t.length-1,s;i>=0;i--)(s=t[i])&&(o=(r?s(e,n,o):s(o))||o);return r&&o&&De(e,n,o),o};function Te(t,e){return t<e?-1:t>e?1:0}function Bn(t){return[...new Set(t)].sort(Te)}function F(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return Bn(e)}function jn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function Fn(t){return typeof t=="string"&&Gn.has(t)?t:"singleton"}function Rt(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Object.keys(t).sort(Te)){if(n.length===0)continue;let r=jn(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function Hn(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=F(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=Rt(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Me(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:Fn(e.lifetime),uses:F(e.uses),reactsTo:F(e.reactsTo),raises:F(e.raises),sends:F(e.sends)},o=Hn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function Un(t){return Rt(t)}function Wn(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!n)return;let r=e.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,i=typeof o.kind=="string"?o.kind.trim():"";if(!i)return;let s=e.residual;if(s===null||typeof s!="object"||Array.isArray(s))return;let c=s,d=typeof c.kind=="string"&&Vn.has(c.kind)?c.kind:void 0;if(!d)return;let l={kind:i},u=Un(o.payload);u&&(l.payload=u);let y={kind:d};return typeof c.reasonCode=="string"&&c.reasonCode.length>0&&(y.reasonCode=c.reasonCode),typeof c.eventId=="string"&&c.eventId.length>0&&(y.eventId=c.eventId),typeof c.target=="string"&&c.target.length>0&&(y.target=c.target),{xiHash:n,event:l,residual:y}}function qn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){let r=Wn(n);r&&e.push(r)}return e}function v(t){let e=typeof t.kernelInstanceId=="string"?t.kernelInstanceId:"",n=Array.isArray(t.components)?t.components:[],r=new Set,o=[];for(let s of n){let c=Me(s);!c||r.has(c.id)||(r.add(c.id),o.push(c))}o.sort((s,c)=>Te(s.id,c.id));let i=qn(t.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:o,...i.length>0?{decisionTape:i}:{}}}var $n,Kn,Gn,Vn,H=j(()=>{"use strict";$n=["singleton","transient"],Kn=["absorb","escalate_up","hold"],Gn=new Set($n);a(Te,"compare");a(Bn,"uniqueSorted");a(F,"nameList");a(jn,"jsonPrimitive");a(Fn,"closedLifetime");a(Rt,"sanitizeMetadata");a(Hn,"sanitizeArkRunExtendedInfo");a(Me,"sanitizeArkRunComponent");Vn=new Set(Kn);a(Un,"sanitizeTapePayload");a(Wn,"sanitizeDecisionTapeRecord");a(qn,"sanitizeDecisionTape");a(v,"buildDependencyInformationPackage")});function W(t,e){return t<e?-1:t>e?1:0}function Le(t){return[...new Set(t)].sort(W)}function At(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function _e(t){return t.tokens.length+t.ids.length+t.labels.length+t.tags.length+t.groups.length+t.architectureKinds.length>0}function I(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Le(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 Le(n)}function xt(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 V(t,e){return t?e.some(n=>xt(t,n)):!1}function Et(t){if(t==null||t==="")return Jn;if(typeof t=="string"&&Xn.has(t))return t;throw new R("slice")}function Pt(t){if(t==null||t==="")return null;if(typeof t=="string"&&/^(0|[1-9]\d*)$/.test(t))return Number(t);if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;throw new R("degreesOfSeparation")}function It(t,e){if(t==null||t==="")return At();if(typeof t=="string"||Array.isArray(t))return{...At(),tokens:I(t,e)};if(typeof t!="object")throw new R(e);let n=t;for(let r of Object.keys(n))if(!Yn.has(r))throw new R(e);return{tokens:[],ids:I(n.ids,e),labels:I(n.labels,e),tags:I(n.tags,e),groups:I(n.groups,e),architectureKinds:I(n.architectureKinds,e)}}function vt(t={}){if(t==null||t==="")return vt({});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(!Zn.has(n))throw new R("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Et(e.slice),nodeIds:I(e.nodeIds,"nodeIds"),degreesOfSeparation:Pt(e.degreesOfSeparation),include:It(e.include,"include"),exclude:It(e.exclude,"exclude")}}function Ct(t){let e={};t.slice&&(e.slice=Et(t.slice));let n=I(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=Pt(t.degreesOfSeparation??void 0);r!==null&&(e.degreesOfSeparation=r);let o=I(t.include??void 0,"include");o.length>0&&(e.include=o);let i=I(t.exclude??void 0,"exclude");return i.length>0&&(e.exclude=i),e}function er(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 bt(t,e){if(!_e(e))return!0;let n=er(t);return e.tokens.some(r=>n.some(o=>xt(o,r)))||V(t.id,e.ids)||V(t.label,e.labels)||t.tags?.some(r=>V(r,e.tags))||V(t.group,e.groups)?!0:V(t.architectureKind,e.architectureKinds)}function tr(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return v({kernelInstanceId:e.kernelInstanceId,components:e.components})}return v({})}function nr(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 ue(t){return{id:t,kind:"interaction"}}function U(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function pe(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 rr(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(U(n,nr(i)),e==="technical"){for(let s of i.uses)U(n,n.get(s)??ue(s)),pe(r,o,i.id,s,"uses");continue}for(let s of i.raises)U(n,n.get(s)??ue(s)),pe(r,o,i.id,s,"raises");for(let s of i.reactsTo)U(n,n.get(s)??ue(s)),pe(r,o,s,i.id,"reactsTo");for(let s of i.sends)U(n,n.get(s)??ue(s)),pe(r,o,i.id,s,"sends")}return{nodes:n,edges:r}}function or(t){let e=new Map,n=a((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 ir(t,e,n,r){let o=e.filter(c=>t.has(c));if(o.length===0)return new Set;let i=new Set,s=o.map(c=>({id:c,depth:0}));for(;s.length>0;){let c=s.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)&&s.push({id:d,depth:c.depth+1})}return i}function q(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function St(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function sr(t){let e=new Set,n=new Map;for(let r of t){let o=q(r),i=o,s=2;for(;e.has(i);)i=`${o}_${s}`,s+=1;e.add(i),n.set(r,i)}return n}function ar(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=sr(n),o=Le(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],s=a((c,d)=>{let l=r.get(c.id)??q(c.id),u=St(c.label??c.id);i.push(`${d}${l}["${u}"]`)},"emitNode");for(let c of o){let d=q(`group_${c}`);i.push(` subgraph ${d}["${St(c)}"]`);for(let l of t.nodes)l.group===c&&s(l," ");i.push(" end")}for(let c of t.nodes)c.group||s(c," ");for(let c of t.edges){let d=r.get(c.from)??q(c.from),l=r.get(c.to)??q(c.to);i.push(` ${d} -->|${c.kind}| ${l}`)}return i.join(`
2
- `)}function cr(t,e,n){let r=new Set(t.keys());if(_e(n.include)&&(r=new Set([...r].filter(c=>{let d=t.get(c);return d!==void 0&&bt(d,n.include)}))),_e(n.exclude))for(let c of[...r]){let d=t.get(c);d&&bt(d,n.exclude)&&r.delete(c)}let o=e.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=ir(r,n.nodeIds,n.degreesOfSeparation,or(o)));let i=[...r].sort(W).map(c=>t.get(c)).filter(c=>!!c),s=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,d)=>W(c.from,d.from)||W(c.kind,d.kind)||W(c.to,d.to));return{nodes:i,edges:s}}function Ot(t={},e={}){let n=tr(t),r=vt(e),o=rr(n.components,r.slice),i=cr(o.nodes,o.edges,r),s={schemaVersion:zn,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return s.mermaid=ar(s),s}var zn,Jn,Qn,R,Xn,Zn,Yn,$e=j(()=>{"use strict";H();zn="1.0",Jn="process",Qn=["process","technical"],R=class extends Error{static{a(this,"InvalidArkRunGraphQueryError")}option;constructor(e,n){super(n??(e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=e}},Xn=new Set(Qn),Zn=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Yn=new Set(["ids","labels","tags","groups","architectureKinds"]);a(W,"compare");a(Le,"uniqueSorted");a(At,"emptyMatch");a(_e,"matchHasCriteria");a(I,"nameList");a(xt,"globMatch");a(V,"anyGlob");a(Et,"closedSlice");a(Pt,"closedDegrees");a(It,"closedMatch");a(vt,"closeArkRunGraphQuery");a(Ct,"arkRunGraphQueryFromSearchParams");a(er,"nodeFields");a(bt,"nodeMatches");a(tr,"asPackage");a(nr,"componentNode");a(ue,"interactionNode");a(U,"addNode");a(pe,"addEdge");a(rr,"buildSlice");a(or,"adjacency");a(ir,"neighborhood");a(q,"mermaidSafeId");a(St,"mermaidLabel");a(sr,"uniqueMermaidIds");a(ar,"formatArkRunGraphMermaid");a(cr,"filterGraph");a(Ot,"requestArkRunGraph")});function lr(t){if(t===void 0)return"local";if(typeof t=="string"&&dr.has(t))return t;throw new fe("transport")}function ur(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new fe("ephemeral")}function Nt(t){let e=lr(t.transport),n=ur(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 Ke,dr,fe,ge=j(()=>{"use strict";Ke=["local","localBlocking","broker"],dr=new Set(Ke),fe=class extends Error{static{a(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}};a(lr,"closedArkRunTransportKind");a(ur,"closedArkRunEphemeral");a(Nt,"resolveArkRunSendPlan")});function Tt(t){return t==="production"}function kr(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 Mt(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function ye(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=Mt(e);if(n)return ye(n);let r=kr(e);return r!==void 0&&r[0]===127}function Lt(t){if(t===void 0)return Dt;if(typeof t!="string")throw new b(String(t));let e=t.trim();if(hr.has(e.toLowerCase())||!ye(e))throw new b(e);let n=e.toLowerCase();if(n==="localhost")return Dt;if(n==="[::1]")return"::1";let r=Mt(n);return r?Lt(r):n}function wr(t){if(t===void 0)return gr;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new b(`port:${String(t)}`);return t}function Ue(t={}){if(Tt(t.nodeEnv)||Tt(t.processNodeEnv))throw new me;return{host:Lt(t.host),port:wr(t.port)}}function C(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function Rr(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function Ar(t){return{kinds:[...Ke],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:yr}}function x(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ir(t){let e=x(t);if(!e||typeof e.id!="string")return;let n=e.status;if(n!=="pending"&&n!=="failed")return;let r=x(e.event),o=r&&typeof r.intent=="string"?r.intent:typeof e.intent=="string"?e.intent:void 0,i={id:e.id,status:n,attempts:typeof e.attempts=="number"&&Number.isFinite(e.attempts)?e.attempts:0};return o&&(i.intent=o),typeof e.error=="string"&&e.error.length>0&&(i.error=e.error),typeof e.updatedAt=="string"&&(i.updatedAt=e.updatedAt),i}function he(t){if(typeof t!="number"||!Number.isFinite(t))return A;let e=Math.trunc(t);return e<0?0:e>A?A:e}function Q(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():t&&typeof t=="object"&&"constructor"in t?String(t.constructor?.name??e):e,r=/^InMemory/i.test(n)?"memory":"durable";return{role:e,id:n,kind:r}}function We(t={}){let e=x(t),n=x(e?.durability)??e,r=Array.isArray(n?.stores)?n.stores:Array.isArray(e?.stores)?e.stores:[],o=[];for(let i of r){let s=x(i);if(!s)continue;let c=s.role;if(c!=="outbox"&&c!=="audit"&&c!=="workflow")continue;let d=typeof s.id=="string"?s.id:typeof s.name=="string"?s.name:void 0;if(!d)continue;let l=s.kind==="memory"||s.kind==="durable"?s.kind:Q(d,c).kind;o.push({role:c,id:d,kind:l})}return{durability:{stores:o}}}function X(t=[],e={}){let n=he(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=[];for(let s of r){let c=Ir(s);c&&(c.status==="pending"?o.push(c):i.push(c))}return{available:!0,pendingCount:o.length,failedCount:i.length,pending:o.slice(0,n),failed:i.slice(0,n),sampleLimit:n}}function z(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:A}}function br(t){let e=x(t);if(!e||typeof e.id!="string")return;let n=typeof e.workflowName=="string"?e.workflowName:typeof e.name=="string"?e.name:void 0;if(!n)return;let r={id:e.id,name:n,status:typeof e.status=="string"?e.status:"unknown"};return typeof e.currentStep=="string"&&(r.currentStep=e.currentStep),typeof e.error=="string"&&e.error.length>0&&(r.error=e.error),r}function Sr(t){return t==="idle"||t==="waiting"}function Z(t=[],e={}){let n=he(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=0,s=0,c=0,d=0;for(let l of r){let u=br(l);u&&(o.push(u),u.status==="running"?i+=1:u.status==="compensating"?s+=1:u.status==="failed"?c+=1:Sr(u.status)&&(d+=1))}return{available:!0,total:o.length,runningCount:i,compensatingCount:s,failedCount:c,pendingCount:d,workflows:o.slice(0,n),sampleLimit:n}}function J(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:A}}function xr(t){if(t===void 0)return;let e=x(t);if(!e||e.available===!1)return z();let n=he(e.sampleLimit);if(Array.isArray(e.pending)||Array.isArray(e.failed)||Array.isArray(e.records)){let r=[...Array.isArray(e.pending)?e.pending:[],...Array.isArray(e.failed)?e.failed:[],...Array.isArray(e.records)?e.records:[]],o=X(r,{sampleLimit:n}),i=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):o.pendingCount,s=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):o.failedCount;return{...o,pendingCount:i,failedCount:s,sampleLimit:n}}return z()}function Er(t){if(t===void 0)return;let e=x(t);if(!e||e.available===!1)return J();let n=he(e.sampleLimit);if(Array.isArray(e.workflows)){let r=Z(e.workflows,{sampleLimit:n}),o=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):r.total,i=typeof e.runningCount=="number"&&Number.isFinite(e.runningCount)?Math.max(0,Math.trunc(e.runningCount)):r.runningCount,s=typeof e.compensatingCount=="number"&&Number.isFinite(e.compensatingCount)?Math.max(0,Math.trunc(e.compensatingCount)):r.compensatingCount,c=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):r.failedCount,d=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:i,compensatingCount:s,failedCount:c,pendingCount:d,sampleLimit:n}}return J()}function _t(t={}){let e=Ue({host:t.host,port:t.port}),n=v({kernelInstanceId:t.kernelInstanceId,components:t.package&&typeof t.package=="object"&&!Array.isArray(t.package)&&Array.isArray(t.package.components)?t.package.components:[]}),r=xr(t.outbox),o=Er(t.workflows),i={schemaVersion:fr,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:Ar(t),observability:Rr(t.observability)??{},hardening:We(t.hardening)};return r&&(i.outbox=r),o&&(i.workflows=o),i}function qe(t){return`event: ${mr}
3
- data: ${JSON.stringify(t)}
4
-
5
- `}var fr,Dt,gr,Be,je,Fe,He,Ve,mr,yr,A,me,b,hr,ke=j(()=>{"use strict";H();ge();fr="1.0",Dt="127.0.0.1",gr=0,Be="/snapshot",je="/events",Fe="/graph",He="/outbox",Ve="/workflows",mr="snapshot",yr="in-process-local",A=32,me=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},b=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},hr=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(Tt,"isArkRunInspectorProductionEnv");a(kr,"ipv4Octets");a(Mt,"unwrapIpv4Mapped");a(ye,"isArkRunInspectorLoopbackHost");a(Lt,"closedHost");a(wr,"closedPort");a(Ue,"resolveArkRunInspectorBind");a(C,"arkRunInspectorUrl");a(Rr,"jsonClone");a(Ar,"closedTransportFacts");a(x,"asRecord");a(Ir,"closedOutboxSummary");a(he,"closedSampleLimit");a(Q,"classifyArkRunInspectorStoreDurability");a(We,"buildArkRunInspectorHardening");a(X,"buildArkRunInspectorOutboxMonitor");a(z,"unavailableArkRunInspectorOutboxMonitor");a(br,"closedWorkflowSummary");a(Sr,"isPendingWorkflowStatus");a(Z,"buildArkRunInspectorWorkflowsMonitor");a(J,"unavailableArkRunInspectorWorkflowsMonitor");a(xr,"closedOutboxMonitor");a(Er,"closedWorkflowsMonitor");a(_t,"buildArkRunInspectorSnapshot");a(qe,"formatArkRunInspectorSseEvent")});var Sn={};_n(Sn,{listenArkRunInspector:()=>ho});function uo(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function po(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function fo(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function E(t,e,n){if(!(t.writableEnded||t.destroyed))try{t.writeHead(e,uo()),t.end(JSON.stringify(n))}catch{}}function go(t,e){let n=t.address();if(n===null||typeof n=="string")throw new b(e.host);if(!ye(n.address))throw new b(n.address);return{host:e.host,port:n.port}}async function mo(t){if(typeof t.listInspectorOutbox=="function")return t.listInspectorOutbox();let e=t.outbox??t.eventBuffer;if(!e||typeof e.list!="function")return z();let[n,r]=await Promise.all([e.list("pending"),e.list("failed")]);return X([...n??[],...r??[]],{sampleLimit:A})}async function yo(t){return typeof t.listInspectorWorkflows=="function"?t.listInspectorWorkflows():!t.workflowEngine||typeof t.workflowEngine.list!="function"?J():Z(await t.workflowEngine.list(),{sampleLimit:A})}async function ho(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,s=e.bind,c=a(()=>t.getInspectorSnapshot(s),"snapshot"),d=n.createServer((l,u)=>{let y=fo(l.url),f=y.pathname;if(l.method==="GET"&&(f==="/"||f===Be)){E(u,200,c());return}if(l.method==="GET"&&f===Fe){try{E(u,200,t.requestGraph(Ct({slice:y.searchParams.get("slice"),nodeIds:y.searchParams.get("nodeIds"),degreesOfSeparation:y.searchParams.get("degreesOfSeparation"),include:y.searchParams.get("include"),exclude:y.searchParams.get("exclude")})))}catch(g){if(g instanceof R){E(u,400,{error:g.message,option:g.option});return}throw g}return}if(l.method==="GET"&&f===He){mo(t).then(g=>E(u,200,g)).catch(g=>{E(u,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(l.method==="GET"&&f===Ve){yo(t).then(g=>E(u,200,g)).catch(g=>{E(u,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(l.method==="GET"&&f===je){u.writeHead(200,po()),u.flushHeaders(),u.write(qe(c())),r.add(u);let g=i>0?setInterval(()=>{u.write(qe(c()))},i):void 0;g&&o.add(g);let h=a(()=>{r.delete(u),g&&(clearInterval(g),o.delete(g))},"drop");l.on("close",h),u.on("close",h);return}E(u,404,{error:"not found"})});try{await new Promise((l,u)=>{let y=a(f=>u(f),"onError");d.once("error",y),d.listen({host:e.bind.host,port:e.bind.port},()=>{d.off("error",y);try{s=go(d,e.bind),l()}catch(f){u(f instanceof Error?f:new b(e.bind.host))}})})}catch(l){throw await new Promise(u=>{d.close(()=>u())}),l}return{host:s.host,port:s.port,url:C(s.host,s.port,"/"),snapshotUrl:C(s.host,s.port,Be),eventsUrl:C(s.host,s.port,je),graphUrl:C(s.host,s.port,Fe),outboxUrl:C(s.host,s.port,He),workflowsUrl:C(s.host,s.port,Ve),close(){for(let l of o)clearInterval(l);o.clear();for(let l of r)l.end();return r.clear(),new Promise((l,u)=>{d.close(y=>{y?u(y):l()})})}}}var xn=j(()=>{"use strict";$e();ke();a(uo,"jsonHeaders");a(po,"sseHeaders");a(fo,"requestUrl");a(E,"writeJson");a(go,"boundAddress");a(mo,"resolveOutboxMonitor");a(yo,"resolveWorkflowsMonitor");a(ho,"listenArkRunInspector")});import{Inject as Io,Module as bo}from"@nestjs/common";$e();ke();H();ge();var $t=0;function Pr(){return $t+=1,`audit-${Date.now()}-${$t}`}a(Pr,"createAuditId");function vr(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)}a(vr,"matchesQuery");var we=class{constructor(e){this.maxRecords=e}maxRecords;static{a(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=>vr(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},Re=class{constructor(e){this.store=e}store;static{a(this,"AuditTrailImpl")}async record(e){let n={id:Pr(),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 ze(t={}){return new Re(t.store??new we(t.maxRecords))}a(ze,"createAuditTrail");var O=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
6
- `);super(`Hard policy violation(s) detected:
7
- ${n}`),this.name="PolicyViolationError",this.violations=e}};var _=class{static{a(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 s=i.check(e);if(s!==!0){if(s===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(s))for(let c of s)n.push({policyName:i.name,severity:i.severity,message:c.message,details:c.details});else n.push({policyName:i.name,severity:i.severity,message:s.message,details:s.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 O(n.hardViolations);return n}clear(){this.policies.length=0}};function Ae(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}}a(Ae,"definePolicy");function Cr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}a(Cr,"defaultLayerOf");function Kt(t,e){return e.resolveLayer?.(t)??Cr(t)}a(Kt,"resolveLayer");function Or(t,e,n){return t===n.from&&e===n.to}a(Or,"matchesRule");function Gt(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Ae({name:e,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(s=>s.kind==="declared"||s.kind==="produces").map(s=>({from:s.from,to:s.to})),...(r.relationships??[]).filter(s=>s.kind==="dependsOn").map(s=>({from:s.from,to:s.to}))],i=[];for(let s of o){let c=Kt(s.from,t),d=Kt(s.to,t);for(let l of t.rules)!l.allowed&&Or(c,d,l)&&i.push({policyName:e,severity:n,message:l.message??`Layer violation: ${s.from} (${c}) must not relate to ${s.to} (${d})`})}return i.length>0?i:!0},"check")})}a(Gt,"defineLayerPolicy");function Je(t){return t.tags?.includes("layer")??!1}a(Je,"isLayerPolicy");function Qe(t,e={}){return Gt({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}a(Qe,"defineArchitectureProfilePolicy");function Xe(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}a(Xe,"buildPublishPolicyContext");var Y=class extends Error{static{a(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}},ee=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},te=class extends Error{static{a(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"}},ne=class extends Error{static{a(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}},$=class extends Error{static{a(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}},N=class extends Error{static{a(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}},re=class extends Error{static{a(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 Bt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ze(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Bt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Bt.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}}a(Ze,"validateIntentName");function oe(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ze(t);if(!n.valid)throw new ee(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new Y(t)}}a(oe,"assertIntentAllowed");function jt(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new $(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new $(t.intent,t.metadata.source)}}a(jt,"assertSourceAllowed");function ie(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new ne(t.intent,n.issues)}a(ie,"assertContractAllowed");function K(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}a(K,"isPlainRecord");function G(t){return Array.isArray(t)?t.map(G):K(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,G(n)])):t}a(G,"clonePatchValue");function Ye(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let s=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=G(i);continue}if(K(r[o])&&K(i)){r[o]=Ye(r[o],i,s);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=et(r[o],i,s);continue}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}return r}a(Ye,"mergeRecordPatch");function et(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let s=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=G(o);return}if(K(r[i])&&K(o)){r[i]=Ye(r[i],o,s);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=et(r[i],o,s);return}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}),r}a(et,"mergeArrayPatch");function Ft(t,e){if(Array.isArray(e)){if(t===void 0)return G(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return et(t,e)}if(t===void 0)return G(e);if(!K(t))throw new Error("Object interceptor patch requires an object payload.");return Ye(t,e)}a(Ft,"applyPayloadPatch");async function Ht(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:a(d=>{i.push(d)},"intercept")})),i.length===0)continue;let s=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:s}]}};for(let d of i)c={...c,payload:Ft(c.payload,d),metadata:{...c.metadata}};ie(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=s,e.appendTrace({type:"event.intercepted",timestamp:s,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(s){await Nr(o,r,s,e)}}return r}a(Ht,"applyInterceptors");async function Nr(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})}a(Nr,"recordInterceptorError");var Vt=new Map;function Ut(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}a(Ut,"escapeLiteral");function Xt(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}a(Xt,"normalizeGlobSeparators");function Dr(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}a(Dr,"bracesBalanced");function Wt(t){let e=Vt.get(t);if(e)return e;let n=Xt(t),r=Dr(n),o="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(o+=Ut(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":d==="?"?o+="[^/]":d==="{"&&r?(o+="(?:",i+=1):d==="}"&&r&&i>0?(o+=")",i-=1):d===","&&r&&i>0?o+="|":o+=Ut(d)}let s=new RegExp(`^${o}$`);return Vt.set(t,s),s}a(Wt,"globToRegExp");function qt(t,e,n){if(!e?.length)return;let r=n==="stars"?"stars":"path",o=String(t).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let i=new Set;for(let s of e)if(!(typeof s!="string"||s.length===0)){if(Tr(s)){let c=Mr(o,s,r);if(c)return c;continue}!s.includes("/")&&!s.includes("\\")&&!s.includes("*")&&i.add(s.toLowerCase())}return _r(o,i)}a(qt,"sliceIdForPath");function Tr(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}a(Tr,"isAnchoredSliceEntry");function Mr(t,e,n){let r=e.split(/[/\\]/).filter(i=>i.length>0).map(i=>i.toLowerCase()),o=Yt(t,r[0]??"");for(let i of o){let s=Lr(t,r,i,n);if(s)return s}}a(Mr,"anchoredSliceId");function Lr(t,e,n,r="path"){let o=[],i=-1,s=n;for(let c=0;c<e.length;c+=1){let d=e[c];if(d==="*"){if(s>=t.length-1){for(let l=c;l<e.length;l+=1)if(e[l]!=="*")return;break}o.push(t[s].toLowerCase()),s+=1;continue}if(d==="**"||s>=t.length||t[s].toLowerCase()!==d)return;o.push(t[s].toLowerCase()),i=o.length-1,s+=1}if(o.length!==0)return r==="stars"?i<0?void 0:o.slice(i).join("/"):o.join("/")}a(Lr,"bindAnchoredSlice");function _r(t,e){if(e.size!==0){for(let n=0;n<t.length-1;n+=1)if(e.has(t[n].toLowerCase())&&!(n+1>=t.length-1))return`${t[n].toLowerCase()}/${t[n+1].toLowerCase()}`}}a(_r,"bareSliceId");function $r(t){let e=new Set;for(let n of t??[]){let o=Xt(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let s=o[i];if((s==="**"||s==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}a($r,"inferSliceFoldersFromPatterns");function Kr(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 $r(r?.patterns)}a(Kr,"resolveSliceFolders");function zt(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}a(zt,"normalizeSegments");function Zt(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(Zt,"trimTrailingSlashes");var Gr=["src","app"];function Yt(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return Gr.includes(n)&&r!==n?[0,1]:[0]}a(Yt,"anchorOffsets");function Br(t){let e=Zt(t.replace(/^[./]+/,""));return e==="*"||e==="**"}a(Br,"isBlanketRoot");function Jt(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=zt(n);for(let i of e){if(typeof i!="string"||i.length===0||Br(i))continue;if(i.includes("*")){let d=Zt(i.toLowerCase());if(Wt(d).test(r)||Wt(`${d}/**`).test(r))return!0;continue}let s=zt(i);if(s.length===0)continue;let c=Yt(o,s[0]??"");for(let d of c){if(d+s.length>o.length)continue;let l=!0;for(let u=0;u<s.length;u+=1)if(o[d+u]!==s[u]){l=!1;break}if(l)return!0}}return!1}a(Jt,"pathUnderSharedRoot");function Qt(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(Qt,"sliceMatchesDeclaration");function jr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Qt(r.from,e)&&Qt(r.to,n))}a(jr,"crossSliceEdgeAllowed");function Fr(t){if(!t.fromPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0;if(!t.toPath)return e?t.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:t.sharedImportsSlice==="deny"&&t.fromShared===!0&&t.toSlice&&!t.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Fr,"peerIsolationDecision");function en(t,e,n,r){return Hr(t,e,n,r)?.rule}a(en,"findDeniedEdgeRule");function Hr(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,s=r?.toPath,c=Kr(o,e,r?.layers),d=i?qt(i,c,o.sliceIdentity):void 0,l=s?qt(s,c,o.sliceIdentity):void 0,u=Fr({fromPath:i,toPath:s,folderCount:c.length,fromSlice:d,toSlice:l,fromShared:!d&&Jt(i,o.sharedRoots),toShared:!l&&Jt(s,o.sharedRoots),crossSliceAllowed:jr(o.allowedCrossSlice,d,l),sharedImportsSlice:o.sharedImportsSlice});if(u.denied)return{rule:o,peerIsolationReason:u.reason,fromSlice:d,toSlice:l};continue}if(e!==n)return{rule:o}}}a(Hr,"findDeniedEdgeDecision");async function tn(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 s=en(r.rules,o,i);if(!s)return;let c=e.mode,d=s.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:s};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 re(n,t.intent,o,i,d)}a(tn,"assertObservedLayerFlowAllowed");async function nn(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof O&&(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))}a(nn,"enforcePublishPolicy");function Vr(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}a(Vr,"appendHistory");function se(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{}}a(se,"appendTrace");async function Ie(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){se(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)}})}}a(Ie,"recordAudit");async function rn(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."};se(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 Ie(t,"event.rawPublish",e,n)}a(rn,"recordRawPublishDiagnostic");async function on(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return Vr(t,o),await t.eventBuffer?.enqueue(e,r),se(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 Ie(t,"event.published",e,{subscribersNotified:n}),o}a(on,"recordSuccessfulPublish");function tt(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}}a(tt,"enrichMetadata");var sn=0;function Ur(){return sn+=1,`interceptor-${Date.now()}-${sn}`}a(Ur,"nextInterceptorRegistrationId");var ae=class{static{a(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 _(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Je)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new te;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Xe({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,s=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,d,l=typeof e!="function";if(l){let f=e,g=r??n??{};d={...f,metadata:tt(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,h=r??{},p=f(g);d={...p,metadata:tt(p.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await rn(this.recording,d),oe(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),jt(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ie(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await Ht(d,{interceptorsForIntent:a(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),ie(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await tn(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let u=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await nn(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((f,g,h)=>this.safeHook(f,g,h),"safeHook")}),await on(this.recording,d,i?u.length:0,o.tx);let y=(async()=>{i&&await Promise.all(u.map(f=>this.invokeHandler(f,d))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(d),"onPublish",d)})();return s?await y:y.then(void 0,()=>{}),d}createPublisher(e){let n=typeof e=="string"?e:e.name;return oe(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,i={},s)=>{if(i.source&&i.source!==n)throw new N(n,i.source);await this.publish(r,o,{...i,source:n},s)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;oe(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 s=this.subscriptions.indexOf(o);s>=0&&this.subscriptions.splice(s,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;oe(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Ur(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let s=this.interceptorsByIntent.get(o)??[];return s.push(i),this.interceptorsByIntent.set(o,s),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){se(this.recording,e)}async recordAudit(e,n,r){await Ie(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 Wr(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}a(Wr,"formatStandardSchemaPath");function qr(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"}a(qr,"actualType");function zr(t,e){return t?`${t}.${e}`:e}a(zr,"formatPath");function an(t,e,n,r,o){let i=qr(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(s=>Object.is(s,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}cn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((s,c)=>{an(s,e.items,`${n}[${c}]`,r,o)})}a(an,"validateSchemaField");function cn(t,e,n,r,o){for(let[i,s]of Object.entries(e)){let c=zr(o,i),d=t[i];if(d===void 0){s.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}an(d,s,c,n,r)}}a(cn,"validateObjectSchema");var be=class{static{a(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(cn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let s of Object.keys(i))r.schema[s]||o.push({intent:e.intent,version:r.version,field:s,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let s=r.standardSchema["~standard"].validate(e.payload);if(s instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(s.issues)for(let c of s.issues)o.push({intent:e.intent,version:r.version,field:Wr(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 nt(){return new be}a(nt,"createEventContractRegistry");var Se=class{static{a(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
- `;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
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
- `);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let s=e.resolveLayer(i)??"Unclassified",c=n.get(s)??[];c.push(i),n.set(s,c)}let r=`flowchart TD
11
- `;for(let i of e.layers){let s=n.get(i.name)??[];if(s.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
12
- `;for(let c of s)r+=` ${this.safeId(c)}[${c}]
13
- `;r+=` end
14
- `}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
15
- `;for(let i of o)r+=` ${this.safeId(i)}[${i}]
16
- `;r+=` end
17
- `}for(let i of this.edges){let s=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${s} ${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=a(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),u=o.slice(l).concat(d);n.push(u)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let s=new Set(n.map(c=>c.join("->")));return Array.from(s).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function rt(){return new Se}a(rt,"createDependencyGraph");function ot(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"))}a(ot,"syncRegistryToGraph");var ce=class{static{a(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=a(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 ps=new ce;function it(){return new ce}a(it,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},dn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...D,default:[]},kernelRoots:{...D},managedLayers:{...D,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},ln={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...D,default:[]},managedLayers:{...D,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...D,default:[]},appliesTo:{...D,default:[]}}};var un="1.3",Jr=["public","auth","admin","internal"];var pn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",fn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Qr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Xr(){let t=[];for(let e of fn)for(let n of fn)e===n||Qr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}a(Xr,"createDefaultRules");var st=Xr();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ts={$schema:"https://json-schema.org/draft/2020-12/schema",$id:pn,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:pn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:un,default:un},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:st,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...w,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Jr]},owners:{...w,minItems:1},forbiddenGlobals:w,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:{...w,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...w,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...w,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...w,minItems:1}}},arkRun:dn,arkOrder:ln}};function Zr(t){return t.endsWith(".")?t:`${t}.`}a(Zr,"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}a(Yr,"byLongestPrefix");function gn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Zr)})),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(s=>o.startsWith(s)))?.name}}}a(gn,"createArchitectureProfile");var eo=[{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}],at=gn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:eo,rules:st.map(t=>({...t}))});var mn="4.8.22";function no(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(no,"policyId");var ct=class{constructor(e){this.data=e}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function dt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,s=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],u=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:no(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),p=s?s.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:s.getCheckpoint(m.name)})):[],B={schemaVersion:"1.0",version:mn,exportedAt:new Date().toISOString(),intents:l,relationships:u,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new ct(B)}a(dt,"createArkManifest");var xe=class{static{a(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 lt(){return new xe}a(lt,"createMetadataRegistry");function ut(t){return`${t.from}->${t.to}`}a(ut,"flowKey");function hn(t){let e=new Set,n=[];for(let r of t){let o=ut(r);e.has(o)||(e.add(o),n.push(r))}return n}a(hn,"uniqueFlows");function kn(t,e){let n=new Set(e.map(ut));return t.filter(r=>!n.has(ut(r)))}a(kn,"difference");function pt(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})),s=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=s.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),d=hn([...o,...i]),l=hn([...s,...c]),u=l.filter(p=>!p.from||p.from==="unknown"),y=e?Array.from(new Set(l.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(l.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(l.flatMap(p=>[p.from,p.to])),h=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:kn(d,l),observedButUndeclared:kn(l.filter(p=>p.from!=="unknown"),d),unknownSources:u,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}a(pt,"createObservabilityReporter");var wn=0;function ro(){return wn+=1,`outbox-${Date.now()}-${wn}`}a(ro,"nextOutboxId");function Rn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}a(Rn,"cloneRecord");var de=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:ro(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Rn(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(Rn)}async clear(){this.records.clear()}};var Ee=class{static{a(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 oo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}a(oo,"initialState");var Pe=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Ee,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)??oo(r),i=await r.project(e,o);await this.store.save(r.name,i);let s=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(s?.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 ft(t){return new Pe(t)}a(ft,"createProjectionRegistry");var An=0;function io(t){return An+=1,`${t}-${Date.now()}-${An}`}a(io,"createWorkflowId");function gt(t){return t instanceof Error?t.message:String(t)}a(gt,"errorMessage");function so(t){return new Promise(e=>{setTimeout(e,t)})}a(so,"sleep");async function ao(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((s,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)}}a(ao,"withTimeout");var ve=class{static{a(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 s=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||s){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()}},mt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new ve}bus;options;static{a(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(),s={id:r.id??io(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(s,r.tx),await this.audit("workflow.started",s,{workflowName:e}),this.executeSnapshot(s,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=gt(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 s=1;s<=i;s+=1){e.attempts[n.name]=s,await this.store.save(e,r);let c;try{c=await ao(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(s<i){o.delayMs&&await so(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:s,error:gt(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:s});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(s=>e.completedSteps.includes(s.name));for(let s=i.length-1;s>=0;s-=1){let c=i[s];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:gt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function yt(t,e){return new mt(t,e)}a(yt,"createWorkflowEngine");H();var co=new Set(["singleton","transient"]);function In(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}a(In,"cloneComponent");function lo(t){if(t===void 0)return"singleton";if(typeof t=="string"&&co.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(lo,"closedLifetime");function bn(){let t=new Map,e=new Map,n=new Set;function r(s){let c=t.get(s);if(!c)throw new Error(`ArkRun component "${s}" is not registered.`);return c}a(r,"mustRecord");function o(s,c){if(!c.factory)throw new Error(`ArkRun component "${s}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(s))throw new Error(`ArkRun component "${s}" has a circular resolve.`);n.add(s);try{return c.factory()}finally{n.delete(s)}}a(o,"instantiate");function i(s,c){if(e.has(s))return e.get(s);let d=o(s,c);return e.set(s,d),d}return a(i,"singleton"),{register(s){let c=typeof s?.id=="string"?s.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=lo(s.lifetime),l=Me({id:c,lifetime:d,uses:s.uses,reactsTo:s.reactsTo,raises:s.raises,sends:s.sends,extendedInfo:s.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof s.factory=="function"?s.factory:void 0;return t.set(c,{component:l,factory:u}),In(l)},resolve(s){let c=r(s);return c.component.lifetime==="transient"?o(s,c):i(s,c)},resolveSingleton(s){let c=r(s);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${s}" is transient; resolveSingleton requires lifetime "singleton".`);return i(s,c)},snapshotComponents(){return[...t.values()].map(s=>In(s.component))}}}a(bn,"createComponentRegistry");ke();async function En(t,e={}){let n=Ue({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(xn(),Sn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}a(En,"startArkRunInspector");ge();function ko(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new N(t.source,e.source);return e.source=t.source,e}a(ko,"stampMetadata");function wo(){}a(wo,"ignoreDetachedFailure");async function ht(t,e,n,r={}){let o=Nt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=ko(r),s=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(s));o.awaitHandoff?await c:c.then(void 0,wo)}return o}a(ht,"sendOnArkRunTransport");var Ro=1e3,Pn=0;function Ao(){return Pn+=1,`ark-kernel-${Date.now()}-${Pn}`}a(Ao,"nextKernelInstanceId");function vn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}a(vn,"portConstructorId");function Cn(t={}){let e=t.strict??!0,n=t.instanceId??Ao(),r=t.profile??at,o=t.maxHistorySize??Ro,i=it(),s=rt(),c=t.metadata??lt(),d=t.auditTrail===void 0,l=t.auditTrail??ze({maxRecords:o}),u=t.eventContracts??nt(),y=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new de,g=t.projections??ft({auditTrail:l}),h=new _([Qe(r),...t.policies??[]]),p=a(()=>{ot(i,s,{requireRegisteredTargets:!0})},"syncGraph"),B=t.ephemeral??!0,m=t.broker,T=new ae({intentRegistry:i,dependencyGraph:s,policyEngine:h,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:u,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 g.apply(k)}}),kt=yt(T,{auditTrail:l}),Ce=pt({registry:i,eventBus:T,graph:s}),M=bn(),On=typeof m?.send=="function",Nn=y?"InMemoryEventBuffer":vn(f,"EventBufferStore"),Dn=d?"InMemoryAuditStore":vn(l,"AuditTrail"),Tn=We({stores:[Q(Nn,"outbox"),Q(Dn,"audit"),Q("InMemoryWorkflowStore","workflow")]}),Oe={instanceId:n,profile:r,registry:i,graph:s,metadata:c,auditTrail:l,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:h,eventBus:T,workflowEngine:kt,observability:Ce,publisher(k){let L=T.createPublisher(k);return{source:L.source,publish:L.publish,send(S,Ne,Mn={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},S,Ne,{...Mn,source:L.source})}}},send(k,L,S={}){return ht({eventBus:T,broker:m,defaultEphemeral:B},k,L,S)},register(k){return M.register(k)},resolve(k){return M.resolve(k)},resolveSingleton(k){return M.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:M.snapshotComponents()})},requestGraph(k){return Ot({kernelInstanceId:n,components:M.snapshotComponents()},k)},getInspectorSnapshot(k){return _t({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:M.snapshotComponents()},observability:Ce.report(),ephemeralDefault:B,brokerBound:On,hardening:Tn})},startInspector(k){return En({getInspectorSnapshot:a(S=>Oe.getInspectorSnapshot(S),"getInspectorSnapshot"),requestGraph:a(S=>Oe.requestGraph(S),"requestGraph"),async listInspectorOutbox(){let[S,Ne]=await Promise.all([f.list("pending"),f.list("failed")]);return X([...S,...Ne],{sampleLimit:A})},async listInspectorWorkflows(){return Z(await kt.list(),{sampleLimit:A})}},k)},syncGraph:p,manifest(){return p(),dt({registry:i,policyEngine:h,metadata:c,graph:s,profile:r,projections:g,eventContracts:u,observability:Ce})}};return Oe}a(Cn,"createArkKernel");var le=Symbol("ARK_KERNEL"),dc=a(()=>Io(le),"InjectArk"),P=class{static forRoot(e){let n=e&&"registry"in e?e:Cn(e);return{module:P,global:!0,providers:[{provide:le,useValue:n}],exports:[le]}}static forRootAsync(e){return{module:P,global:!0,providers:[{provide:le,useFactory:e.useFactory,inject:e.inject??[]}],exports:[le]}}};a(P,"ArkModule"),P=wt([bo({})],P);export{le as ARK_KERNEL,P as ArkModule,dc as InjectArk};
1
+ import{va as c}from"../chunk-MBXCFLO4.js";import{a as o,b as n}from"../chunk-SVSQVGFJ.js";import{Inject as p,Module as s}from"@nestjs/common";var t=Symbol("ARK_KERNEL"),y=o(()=>p(t),"InjectArk"),e=class{static forRoot(r){let i=r&&"registry"in r?r:c(r);return{module:e,global:!0,providers:[{provide:t,useValue:i}],exports:[t]}}static forRootAsync(r){return{module:e,global:!0,providers:[{provide:t,useFactory:r.useFactory,inject:r.inject??[]}],exports:[t]}}};o(e,"ArkModule"),e=n([s({})],e);export{t as ARK_KERNEL,e as ArkModule,y as InjectArk};