arkgate 4.8.21 → 4.8.23
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.
- package/CHANGELOG.md +71 -0
- package/README.md +2 -2
- package/bin/ark-check-runtime.mjs +4 -2
- package/bin/ark-layer-match.mjs +606 -11
- package/bin/lib/analysis-engine.mjs +11 -11
- package/bin/lib/config-contract.mjs +492 -1
- package/bin/lib/diagnostic-catalog.mjs +32 -0
- package/bin/lib/doctor-advisories.mjs +60 -1
- package/bin/lib/doctor-plan.mjs +2 -2
- package/bin/lib/enforcement-honesty.mjs +22 -0
- package/bin/lib/flat-parent-pilot.mjs +252 -0
- package/bin/lib/html-report-advisories.mjs +2 -0
- package/bin/lib/html-report-depth.mjs +3 -1
- package/bin/lib/invariant-coverage.mjs +27 -3
- package/bin/lib/physical-cohesion.mjs +16 -18
- package/bin/lib/pilot-loop.mjs +21 -8
- package/bin/lib/team-parliament-io.mjs +4 -2
- package/dist/{configTypes-CTELo87-.d.ts → configTypes-Bbf_MFGe.d.ts} +36 -2
- package/dist/{diagnosticCatalog-B7BXlet6.d.ts → diagnosticCatalog-35mrwAHe.d.ts} +20 -5
- package/dist/eslint/index.cjs +4 -4
- package/dist/eslint/index.d.ts +51 -5
- package/dist/eslint/index.js +4 -4
- package/dist/index.cjs +36 -36
- package/dist/index.d.ts +104 -5
- package/dist/index.js +36 -36
- package/dist/nestjs/index.cjs +9 -9
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +9 -9
- package/dist/runtime/index.cjs +19 -19
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +19 -19
- package/dist/{types-yDNEQ603.d.ts → types-Bdj32QwA.d.ts} +1 -1
- package/dist/{types-fQ9-KrBj.d.ts → types-Ik_OakcI.d.ts} +1 -1
- package/docs/README.md +3 -1
- package/docs/agent-guide.md +9 -1
- package/docs/configuration.md +92 -1
- package/docs/diagnostics.md +32 -0
- package/docs/product-voice.md +1 -1
- package/package.json +2 -1
- package/schemas/ark.config.schema.json +124 -2
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
package/dist/nestjs/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}function
|
|
1
|
+
var Le=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var s=(t,e)=>Le(t,"name",{value:e,configurable:!0});var B=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var jn=(t,e)=>{for(var n in e)Le(t,n,{get:e[n],enumerable:!0})};var St=(t,e,n,r)=>{for(var o=r>1?void 0:r?Bn(e,n):e,i=t.length-1,a;i>=0;i--)(a=t[i])&&(o=(r?a(e,n,o):a(o))||o);return r&&o&&Le(e,n,o),o};function Te(t,e){return t<e?-1:t>e?1:0}function Wn(t){return[...new Set(t)].sort(Te)}function j(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return Wn(e)}function qn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function zn(t){return typeof t=="string"&&Vn.has(t)?t:"singleton"}function bt(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=qn(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function Jn(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=j(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=bt(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function _e(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:zn(e.lifetime),uses:j(e.uses),reactsTo:j(e.reactsTo),raises:j(e.raises),sends:j(e.sends)},o=Jn(e.extendedInfo);return o&&(r.extendedInfo=o),r}function Xn(t){return bt(t)}function Zn(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.xiHash=="string"?e.xiHash.trim():"";if(!n)return;let r=e.event;if(r===null||typeof r!="object"||Array.isArray(r))return;let o=r,i=typeof o.kind=="string"?o.kind.trim():"";if(!i)return;let a=e.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let c=a,l=typeof c.kind=="string"&&Qn.has(c.kind)?c.kind:void 0;if(!l)return;let d={kind:i},u=Xn(o.payload);u&&(d.payload=u);let m={kind:l};return typeof c.reasonCode=="string"&&c.reasonCode.length>0&&(m.reasonCode=c.reasonCode),typeof c.eventId=="string"&&c.eventId.length>0&&(m.eventId=c.eventId),typeof c.target=="string"&&c.target.length>0&&(m.target=c.target),{xiHash:n,event:d,residual:m}}function Yn(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){let r=Zn(n);r&&e.push(r)}return e}function P(t){let e=typeof t.kernelInstanceId=="string"?t.kernelInstanceId:"",n=Array.isArray(t.components)?t.components:[],r=new Set,o=[];for(let a of n){let c=_e(a);!c||r.has(c.id)||(r.add(c.id),o.push(c))}o.sort((a,c)=>Te(a.id,c.id));let i=Yn(t.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:o,...i.length>0?{decisionTape:i}:{}}}var Hn,Un,Vn,Qn,H=B(()=>{"use strict";Hn=["singleton","transient"],Un=["absorb","escalate_up","hold"],Vn=new Set(Hn);s(Te,"compare");s(Wn,"uniqueSorted");s(j,"nameList");s(qn,"jsonPrimitive");s(zn,"closedLifetime");s(bt,"sanitizeMetadata");s(Jn,"sanitizeArkRunExtendedInfo");s(_e,"sanitizeArkRunComponent");Qn=new Set(Un);s(Xn,"sanitizeTapePayload");s(Zn,"sanitizeDecisionTapeRecord");s(Yn,"sanitizeDecisionTape");s(P,"buildDependencyInformationPackage")});function W(t,e){return t<e?-1:t>e?1:0}function Me(t){return[...new Set(t)].sort(W)}function Et(){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 R(t,e){if(t==null||t==="")return[];if(typeof t=="string")return Me(t.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(t))throw new A(e);let n=[];for(let r of t){if(typeof r!="string")throw new A(e);let o=r.trim();o.length>0&&n.push(o)}return Me(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 U(t,e){return t?e.some(n=>Ct(t,n)):!1}function Ot(t){if(t==null||t==="")return tr;if(typeof t=="string"&&rr.has(t))return t;throw new A("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 A("degreesOfSeparation")}function vt(t,e){if(t==null||t==="")return Et();if(typeof t=="string"||Array.isArray(t))return{...Et(),tokens:R(t,e)};if(typeof t!="object")throw new A(e);let n=t;for(let r of Object.keys(n))if(!ir.has(r))throw new A(e);return{tokens:[],ids:R(n.ids,e),labels:R(n.labels,e),tags:R(n.tags,e),groups:R(n.groups,e),architectureKinds:R(n.architectureKinds,e)}}function Dt(t={}){if(t==null||t==="")return Dt({});if(typeof t!="object"||Array.isArray(t))throw new A("slice","ArkRun graph query must be an object.");let e=t;for(let n of Object.keys(e))if(!or.has(n))throw new A("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Ot(e.slice),nodeIds:R(e.nodeIds,"nodeIds"),degreesOfSeparation:Nt(e.degreesOfSeparation),include:vt(e.include,"include"),exclude:vt(e.exclude,"exclude")}}function Lt(t){let e={};t.slice&&(e.slice=Ot(t.slice));let n=R(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=R(t.include??void 0,"include");o.length>0&&(e.include=o);let i=R(t.exclude??void 0,"exclude");return i.length>0&&(e.exclude=i),e}function sr(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 xt(t,e){if(!$e(e))return!0;let n=sr(t);return e.tokens.some(r=>n.some(o=>Ct(o,r)))||U(t.id,e.ids)||U(t.label,e.labels)||t.tags?.some(r=>U(r,e.tags))||U(t.group,e.groups)?!0:U(t.architectureKind,e.architectureKinds)}function ar(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return P({kernelInstanceId:e.kernelInstanceId,components:e.components})}return P({})}function cr(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 fe(t){return{id:t,kind:"interaction"}}function V(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 lr(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(V(n,cr(i)),e==="technical"){for(let a of i.uses)V(n,n.get(a)??fe(a)),pe(r,o,i.id,a,"uses");continue}for(let a of i.raises)V(n,n.get(a)??fe(a)),pe(r,o,i.id,a,"raises");for(let a of i.reactsTo)V(n,n.get(a)??fe(a)),pe(r,o,a,i.id,"reactsTo");for(let a of i.sends)V(n,n.get(a)??fe(a)),pe(r,o,i.id,a,"sends")}return{nodes:n,edges:r}}function dr(t){let e=new Map,n=s((r,o)=>{let i=e.get(r);i?i.push(o):e.set(r,[o])},"push");for(let r of t)n(r.from,r.to),n(r.to,r.from);return e}function ur(t,e,n,r){let o=e.filter(c=>t.has(c));if(o.length===0)return new Set;let i=new Set,a=o.map(c=>({id:c,depth:0}));for(;a.length>0;){let c=a.shift();if(!(!c||i.has(c.id))&&(i.add(c.id),!(n!==null&&c.depth>=n)))for(let l of r.get(c.id)??[])!i.has(l)&&t.has(l)&&a.push({id:l,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 Pt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function fr(t){let e=new Set,n=new Map;for(let r of t){let o=q(r),i=o,a=2;for(;e.has(i);)i=`${o}_${a}`,a+=1;e.add(i),n.set(r,i)}return n}function pr(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=fr(n),o=Me(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,l)=>{let d=r.get(c.id)??q(c.id),u=Pt(c.label??c.id);i.push(`${l}${d}["${u}"]`)},"emitNode");for(let c of o){let l=q(`group_${c}`);i.push(` subgraph ${l}["${Pt(c)}"]`);for(let d of t.nodes)d.group===c&&a(d," ");i.push(" end")}for(let c of t.nodes)c.group||a(c," ");for(let c of t.edges){let l=r.get(c.from)??q(c.from),d=r.get(c.to)??q(c.to);i.push(` ${l} -->|${c.kind}| ${d}`)}return i.join(`
|
|
2
|
+
`)}function gr(t,e,n){let r=new Set(t.keys());if($e(n.include)&&(r=new Set([...r].filter(c=>{let l=t.get(c);return l!==void 0&&xt(l,n.include)}))),$e(n.exclude))for(let c of[...r]){let l=t.get(c);l&&xt(l,n.exclude)&&r.delete(c)}let o=e.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=ur(r,n.nodeIds,n.degreesOfSeparation,dr(o)));let i=[...r].sort(W).map(c=>t.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,l)=>W(c.from,l.from)||W(c.kind,l.kind)||W(c.to,l.to));return{nodes:i,edges:a}}function Tt(t={},e={}){let n=ar(t),r=Dt(e),o=lr(n.components,r.slice),i=gr(o.nodes,o.edges,r),a={schemaVersion:er,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=pr(a),a}var er,tr,nr,A,rr,or,ir,Ge=B(()=>{"use strict";H();er="1.0",tr="process",nr=["process","technical"],A=class extends Error{static{s(this,"InvalidArkRunGraphQueryError")}option;constructor(e,n){super(n??(e==="slice"?'ArkRun graph slice must be "process" or "technical".':e==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${e} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=e}},rr=new Set(nr),or=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),ir=new Set(["ids","labels","tags","groups","architectureKinds"]);s(W,"compare");s(Me,"uniqueSorted");s(Et,"emptyMatch");s($e,"matchHasCriteria");s(R,"nameList");s(Ct,"globMatch");s(U,"anyGlob");s(Ot,"closedSlice");s(Nt,"closedDegrees");s(vt,"closedMatch");s(Dt,"closeArkRunGraphQuery");s(Lt,"arkRunGraphQueryFromSearchParams");s(sr,"nodeFields");s(xt,"nodeMatches");s(ar,"asPackage");s(cr,"componentNode");s(fe,"interactionNode");s(V,"addNode");s(pe,"addEdge");s(lr,"buildSlice");s(dr,"adjacency");s(ur,"neighborhood");s(q,"mermaidSafeId");s(Pt,"mermaidLabel");s(fr,"uniqueMermaidIds");s(pr,"formatArkRunGraphMermaid");s(gr,"filterGraph");s(Tt,"requestArkRunGraph")});function hr(t){if(t===void 0)return"local";if(typeof t=="string"&&mr.has(t))return t;throw new ge("transport")}function yr(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new ge("ephemeral")}function _t(t){let e=hr(t.transport),n=yr(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,mr,ge,me=B(()=>{"use strict";Ke=["local","localBlocking","broker"],mr=new Set(Ke),ge=class extends Error{static{s(this,"InvalidArkRunSendOptionError")}option;constructor(e){super(e==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=e}};s(hr,"closedArkRunTransportKind");s(yr,"closedArkRunEphemeral");s(_t,"resolveArkRunSendPlan")});function $t(t){return t==="production"}function br(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 Gt(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=Gt(e);if(n)return ye(n);let r=br(e);return r!==void 0&&r[0]===127}function Kt(t){if(t===void 0)return Mt;if(typeof t!="string")throw new S(String(t));let e=t.trim();if(Sr.has(e.toLowerCase())||!ye(e))throw new S(e);let n=e.toLowerCase();if(n==="localhost")return Mt;if(n==="[::1]")return"::1";let r=Gt(n);return r?Kt(r):n}function Er(t){if(t===void 0)return Ar;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new S(`port:${String(t)}`);return t}function We(t={}){if($t(t.nodeEnv)||$t(t.processNodeEnv))throw new he;return{host:Kt(t.host),port:Er(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 xr(t){return{kinds:[...Ke],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:Rr}}function E(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Pr(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 I;let e=Math.trunc(t);return e<0?0:e>I?I: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 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 a=E(i);if(!a)continue;let c=a.role;if(c!=="outbox"&&c!=="audit"&&c!=="workflow")continue;let l=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!l)continue;let d=a.kind==="memory"||a.kind==="durable"?a.kind:Q(l,c).kind;o.push({role:c,id:l,kind:d})}return{durability:{stores:o}}}function X(t=[],e={}){let n=ke(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=[];for(let a of r){let c=Pr(a);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:I}}function Cr(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 Or(t){return t==="idle"||t==="waiting"}function Z(t=[],e={}){let n=ke(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=0,a=0,c=0,l=0;for(let d of r){let u=Cr(d);u&&(o.push(u),u.status==="running"?i+=1:u.status==="compensating"?a+=1:u.status==="failed"?c+=1:Or(u.status)&&(l+=1))}return{available:!0,total:o.length,runningCount:i,compensatingCount:a,failedCount:c,pendingCount:l,workflows:o.slice(0,n),sampleLimit:n}}function J(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:I}}function Nr(t){if(t===void 0)return;let e=E(t);if(!e||e.available===!1)return z();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=X(r,{sampleLimit:n}),i=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):o.pendingCount,a=typeof e.failedCount=="number"&&Number.isFinite(e.failedCount)?Math.max(0,Math.trunc(e.failedCount)):o.failedCount;return{...o,pendingCount:i,failedCount:a,sampleLimit:n}}return z()}function Dr(t){if(t===void 0)return;let e=E(t);if(!e||e.available===!1)return J();let n=ke(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,a=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,l=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:i,compensatingCount:a,failedCount:c,pendingCount:l,sampleLimit:n}}return J()}function Ft(t={}){let e=We({host:t.host,port:t.port}),n=P({kernelInstanceId:t.kernelInstanceId,components:t.package&&typeof t.package=="object"&&!Array.isArray(t.package)&&Array.isArray(t.package.components)?t.package.components:[]}),r=Nr(t.outbox),o=Dr(t.workflows),i={schemaVersion:wr,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:xr(t),observability:vr(t.observability)??{},hardening:qe(t.hardening)};return r&&(i.outbox=r),o&&(i.workflows=o),i}function ze(t){return`event: ${Ir}
|
|
3
3
|
data: ${JSON.stringify(t)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var wr,Mt,Ar,Be,je,He,Ue,Ve,Ir,Rr,I,he,S,Sr,we=B(()=>{"use strict";H();me();wr="1.0",Mt="127.0.0.1",Ar=0,Be="/snapshot",je="/events",He="/graph",Ue="/outbox",Ve="/workflows",Ir="snapshot",Rr="in-process-local",I=32,he=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},S=class extends Error{static{s(this,"ArkRunInspectorBindError")}constructor(e){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${e}" is rejected.`),this.name="ArkRunInspectorBindError"}},Sr=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s($t,"isArkRunInspectorProductionEnv");s(br,"ipv4Octets");s(Gt,"unwrapIpv4Mapped");s(ye,"isArkRunInspectorLoopbackHost");s(Kt,"closedHost");s(Er,"closedPort");s(We,"resolveArkRunInspectorBind");s(C,"arkRunInspectorUrl");s(vr,"jsonClone");s(xr,"closedTransportFacts");s(E,"asRecord");s(Pr,"closedOutboxSummary");s(ke,"closedSampleLimit");s(Q,"classifyArkRunInspectorStoreDurability");s(qe,"buildArkRunInspectorHardening");s(X,"buildArkRunInspectorOutboxMonitor");s(z,"unavailableArkRunInspectorOutboxMonitor");s(Cr,"closedWorkflowSummary");s(Or,"isPendingWorkflowStatus");s(Z,"buildArkRunInspectorWorkflowsMonitor");s(J,"unavailableArkRunInspectorWorkflowsMonitor");s(Nr,"closedOutboxMonitor");s(Dr,"closedWorkflowsMonitor");s(Ft,"buildArkRunInspectorSnapshot");s(ze,"formatArkRunInspectorSseEvent")});var On={};jn(On,{listenArkRunInspector:()=>Go});function Do(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Lo(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function To(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function v(t,e,n){if(!(t.writableEnded||t.destroyed))try{t.writeHead(e,Do()),t.end(JSON.stringify(n))}catch{}}function _o(t,e){let n=t.address();if(n===null||typeof n=="string")throw new S(e.host);if(!ye(n.address))throw new S(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:I})}async function $o(t){return typeof t.listInspectorWorkflows=="function"?t.listInspectorWorkflows():!t.workflowEngine||typeof t.workflowEngine.list!="function"?J():Z(await t.workflowEngine.list(),{sampleLimit:I})}async function Go(t,e){let n=await import("http"),r=new Set,o=new Set,i=typeof e.sseIntervalMs=="number"&&Number.isFinite(e.sseIntervalMs)?Math.max(0,e.sseIntervalMs):1e3,a=e.bind,c=s(()=>t.getInspectorSnapshot(a),"snapshot"),l=n.createServer((d,u)=>{let m=To(d.url),f=m.pathname;if(d.method==="GET"&&(f==="/"||f===Be)){v(u,200,c());return}if(d.method==="GET"&&f===He){try{v(u,200,t.requestGraph(Lt({slice:m.searchParams.get("slice"),nodeIds:m.searchParams.get("nodeIds"),degreesOfSeparation:m.searchParams.get("degreesOfSeparation"),include:m.searchParams.get("include"),exclude:m.searchParams.get("exclude")})))}catch(g){if(g instanceof A){v(u,400,{error:g.message,option:g.option});return}throw g}return}if(d.method==="GET"&&f===Ue){Mo(t).then(g=>v(u,200,g)).catch(g=>{v(u,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(d.method==="GET"&&f===Ve){$o(t).then(g=>v(u,200,g)).catch(g=>{v(u,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(d.method==="GET"&&f===je){u.writeHead(200,Lo()),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 y=s(()=>{r.delete(u),g&&(clearInterval(g),o.delete(g))},"drop");d.on("close",y),u.on("close",y);return}v(u,404,{error:"not found"})});try{await new Promise((d,u)=>{let m=s(f=>u(f),"onError");l.once("error",m),l.listen({host:e.bind.host,port:e.bind.port},()=>{l.off("error",m);try{a=_o(l,e.bind),d()}catch(f){u(f instanceof Error?f:new S(e.bind.host))}})})}catch(d){throw await new Promise(u=>{l.close(()=>u())}),d}return{host:a.host,port:a.port,url:C(a.host,a.port,"/"),snapshotUrl:C(a.host,a.port,Be),eventsUrl:C(a.host,a.port,je),graphUrl:C(a.host,a.port,He),outboxUrl:C(a.host,a.port,Ue),workflowsUrl:C(a.host,a.port,Ve),close(){for(let d of o)clearInterval(d);o.clear();for(let d of r)d.end();return r.clear(),new Promise((d,u)=>{l.close(m=>{m?u(m):d()})})}}}var Nn=B(()=>{"use strict";Ge();we();s(Do,"jsonHeaders");s(Lo,"sseHeaders");s(To,"requestUrl");s(v,"writeJson");s(_o,"boundAddress");s(Mo,"resolveOutboxMonitor");s($o,"resolveWorkflowsMonitor");s(Go,"listenArkRunInspector")});import{Inject as Ho,Module as Uo}from"@nestjs/common";Ge();we();H();me();var Bt=0;function Lr(){return Bt+=1,`audit-${Date.now()}-${Bt}`}s(Lr,"createAuditId");function Tr(t,e){return!(e.type&&t.type!==e.type||e.intent&&t.intent!==e.intent||e.correlationId&&t.correlationId!==e.correlationId||e.subject&&t.subject!==e.subject||e.since&&t.timestamp<e.since||e.until&&t.timestamp>e.until)}s(Tr,"matchesQuery");var Ae=class{constructor(e){this.maxRecords=e}maxRecords;static{s(this,"InMemoryAuditStore")}records=[];append(e){this.records.push(e),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(e={}){let n=this.records.filter(r=>Tr(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},Ie=class{constructor(e){this.store=e}store;static{s(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 Ie(t.store??new Ae(t.maxRecords))}s(Je,"createAuditTrail");var O=class extends Error{static{s(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
6
6
|
`);super(`Hard policy violation(s) detected:
|
|
7
|
-
${n}`),this.name="PolicyViolationError",this.violations=e}};var _=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
|
|
7
|
+
${n}`),this.name="PolicyViolationError",this.violations=e}};var M=class{static{s(this,"PolicyEngine")}policies=[];constructor(e=[]){for(let n of e)this.add(n)}add(e){if(this.policies.some(n=>n.name===e.name))throw new Error(`Policy "${e.name}" is already registered in this engine.`);this.policies.push(e)}getPolicies(){return[...this.policies]}evaluate(e){let n=[];for(let i of this.policies){let a=i.check(e);if(a!==!0){if(a===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(a))for(let c of a)n.push({policyName:i.name,severity:i.severity,message:c.message,details:c.details});else n.push({policyName:i.name,severity:i.severity,message:a.message,details:a.details})}}let r=n.filter(i=>i.severity==="hard"),o=n.filter(i=>i.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(e){let n=this.evaluate(e);if(n.hardViolations.length>0)throw new O(n.hardViolations);return n}clear(){this.policies.length=0}};function Re(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}s(Re,"definePolicy");function _r(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(_r,"defaultLayerOf");function jt(t,e){return e.resolveLayer?.(t)??_r(t)}s(jt,"resolveLayer");function Mr(t,e,n){return t===n.from&&e===n.to}s(Mr,"matchesRule");function Ht(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Re({name:e,severity:n,tags:["layer"],check:s(r=>{let o=[...(r.edges??[]).filter(a=>a.kind==="declared"||a.kind==="produces").map(a=>({from:a.from,to:a.to})),...(r.relationships??[]).filter(a=>a.kind==="dependsOn").map(a=>({from:a.from,to:a.to}))],i=[];for(let a of o){let c=jt(a.from,t),l=jt(a.to,t);for(let d of t.rules)!d.allowed&&Mr(c,l,d)&&i.push({policyName:e,severity:n,message:d.message??`Layer violation: ${a.from} (${c}) must not relate to ${a.to} (${l})`})}return i.length>0?i:!0},"check")})}s(Ht,"defineLayerPolicy");function Qe(t){return t.tags?.includes("layer")??!1}s(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})}s(Xe,"defineArchitectureProfilePolicy");function Ze(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Ze,"buildPublishPolicyContext");var Y=class extends Error{static{s(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},ee=class extends Error{static{s(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},te=class extends Error{static{s(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},ne=class extends Error{static{s(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},$=class extends Error{static{s(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},N=class extends Error{static{s(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},re=class extends Error{static{s(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}};var Ut=["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(!Ut.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Ut.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}s(Ye,"validateIntentName");function oe(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ye(t);if(!n.valid)throw new ee(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new Y(t)}}s(oe,"assertIntentAllowed");function Vt(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)}}s(Vt,"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)}s(ie,"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}s(G,"isPlainRecord");function K(t){return Array.isArray(t)?t.map(K):G(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,K(n)])):t}s(K,"clonePatchValue");function et(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=K(i);continue}if(G(r[o])&&G(i)){r[o]=et(r[o],i,a);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=tt(r[o],i,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}s(et,"mergeRecordPatch");function tt(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let a=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=K(o);return}if(G(r[i])&&G(o)){r[i]=et(r[i],o,a);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=tt(r[i],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}s(tt,"mergeArrayPatch");function Wt(t,e){if(Array.isArray(e)){if(t===void 0)return K(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return tt(t,e)}if(t===void 0)return K(e);if(!G(t))throw new Error("Object interceptor patch requires an object payload.");return et(t,e)}s(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:s(l=>{i.push(l)},"intercept")})),i.length===0)continue;let a=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let l of i)c={...c,payload:Wt(c.payload,l),metadata:{...c.metadata}};ie(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=a,e.appendTrace({type:"event.intercepted",timestamp:a,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(a){await $r(o,r,a,e)}}return r}s(qt,"applyInterceptors");async function $r(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}s($r,"recordInterceptorError");var zt=new Map;function Jt(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}s(Jt,"escapeLiteral");function nn(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}s(nn,"normalizeGlobSeparators");function Gr(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}s(Gr,"bracesBalanced");function nt(t){let e=zt.get(t);if(e)return e;let n=nn(t),r=Gr(n),o="",i=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=Jt(n[c+1]),c+=1):l==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":l==="?"?o+="[^/]":l==="{"&&r?(o+="(?:",i+=1):l==="}"&&r&&i>0?(o+=")",i-=1):l===","&&r&&i>0?o+="|":o+=Jt(l)}let a=new RegExp(`^${o}$`);return zt.set(t,a),a}s(nt,"globToRegExp");function rn(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 a of e)if(!(typeof a!="string"||a.length===0)){if(Kr(a)){let c=Fr(o,a,r);if(c)return c;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&i.add(a.toLowerCase())}return jr(o,i)}s(rn,"sliceIdForPath");function Kr(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}s(Kr,"isAnchoredSliceEntry");function Fr(t,e,n){let r=e.split(/[/\\]/).filter(i=>i.length>0).map(i=>i.toLowerCase()),o=on(t,r[0]??"");for(let i of o){let a=Br(t,r,i,n);if(a)return a}}s(Fr,"anchoredSliceId");function Br(t,e,n,r="path"){let o=[],i=-1,a=n;for(let c=0;c<e.length;c+=1){let l=e[c];if(l==="*"){if(a>=t.length-1){for(let d=c;d<e.length;d+=1)if(e[d]!=="*")return;break}o.push(t[a].toLowerCase()),a+=1;continue}if(l==="**"||a>=t.length||t[a].toLowerCase()!==l)return;o.push(t[a].toLowerCase()),i=o.length-1,a+=1}if(o.length!==0)return r==="stars"?i<0?void 0:o.slice(i).join("/"):o.join("/")}s(Br,"bindAnchoredSlice");function jr(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()}`}}s(jr,"bareSliceId");function Hr(t){let e=new Set;for(let n of t??[]){let o=nn(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let a=o[i];if((a==="**"||a==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}s(Hr,"inferSliceFoldersFromPatterns");function Ur(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return Hr(r?.patterns)}s(Ur,"resolveSliceFolders");function Qt(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}s(Qt,"normalizeSegments");function se(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}s(se,"trimTrailingSlashes");var Vr=["src","app"];function on(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return Vr.includes(n)&&r!==n?[0,1]:[0]}s(on,"anchorOffsets");function Wr(t){let e=se(t.replace(/^[./]+/,""));return e==="*"||e==="**"}s(Wr,"isBlanketRoot");function Xt(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Qt(n);for(let i of e){if(typeof i!="string"||i.length===0||Wr(i))continue;if(i.includes("*")){let l=se(i.toLowerCase());if(nt(l).test(r)||nt(`${l}/**`).test(r))return!0;continue}let a=Qt(i);if(a.length===0)continue;let c=on(o,a[0]??"");for(let l of c){if(l+a.length>o.length)continue;let d=!0;for(let u=0;u<a.length;u+=1)if(o[l+u]!==a[u]){d=!1;break}if(d)return!0}}return!1}s(Xt,"pathUnderSharedRoot");function Zt(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}s(Zt,"sliceMatchesDeclaration");function qr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Zt(r.from,e)&&Zt(r.to,n))}s(qr,"crossSliceEdgeAllowed");function zr(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"}}s(zr,"peerIsolationDecision");function sn(t){return se(t.trim().replace(/\\/g,"/")).toLowerCase()}s(sn,"aliasGlobPattern");function Jr(t,e){let n=sn(t);if(!n||n==="*"||n==="**")return!1;let r=String(e).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=ot(r),i=nt(n);return i.test(r)||o!==r&&i.test(o)}s(Jr,"aliasGlobMatches");function Qr(t){let e=sn(t).split("/").filter(Boolean);return e.length<2||e.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:e.slice(0,-1).join("/"),childId:e.join("/")}}s(Qr,"splitAliasTarget");function Xr(t,e){for(let n of e.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&Jr(n.from,t))return Qr(n.to);return null}s(Xr,"firstSliceAlias");function Yt(t,e,n){if(!t)return{};let r=n??e.sliceFolders,o=rn(t,r?[...r]:void 0,e.sliceIdentity),i=rt(t,o,e.childSlices);if(o||i.childId||i.mismatched)return i.childId?{universeId:o,childId:i.childId}:{universeId:o};let a=Xr(t,e);return a?{universeId:a.universeId,childId:a.childId}:{}}s(Yt,"resolveGovernedSlice");function Zr(t,e){switch(t){case"cross-slice":return`cross-slice edge ${e.fromSlice??"?"} \u2192 ${e.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${e.toSlice??"?"} (${e.fromPath??"?"} \u2192 ${e.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[e.fromSlice?void 0:e.fromPath,e.toSlice?void 0:e.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}s(Zr,"peerIsolationDenyExplanation");function Yr(t,e){return`cross-parent slice ${t??"?"} \u2192 ${e??"?"}. The child wall cannot allow another universe.`}s(Yr,"crossParentExplanation");function eo(t,e,n){return`cross-sibling slice ${t} \u2192 ${e} inside ${n}.`}s(eo,"crossSiblingExplanation");function to(t){return`universe common imports child ${t}. parentMayImportChild is off.`}s(to,"parentImportsChildExplanation");function no(t){return String(t).split(/[/\\]/).filter(Boolean).slice(0,-1)}s(no,"directorySegments");function ro(t,e){if(!e?.length)return!1;let n=new Set;for(let r of e)typeof r=="string"&&r.length>0&&n.add(r.toLowerCase());return n.size===0?!1:no(t).some(r=>n.has(r.toLowerCase()))}s(ro,"pathHasCommonFolder");function rt(t,e,n){if(!t||!n?.sliceFolders?.length)return{};if(ro(t,n.commonFolders))return{};let r=rn(t,n.sliceFolders,n.sliceIdentity);if(!r||!e)return{};let o=r.toLowerCase(),i=e.toLowerCase();return o===i?{}:o.startsWith(`${i}/`)?{childId:r}:{mismatched:{childId:r,universeId:e}}}s(rt,"resolveChildSliceId");function oo(t){return se(t.trim().replace(/\\/g,"/")).toLowerCase()}s(oo,"siblingEntryKey");function ot(t){return t.replace(/^(?:src|app)\//,"")}s(ot,"stripSrcOrApp");function io(t,e){let n=t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=ot(e);if(!r)return!1;let o=ot(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}s(io,"pathUnderSubtree");function so(t,e,n){if(!e||!n?.length)return!1;let r=e.toLowerCase();for(let o of n){if(typeof o!="string")continue;let i=oo(o);if(!(!i||i.includes("*"))&&(r===i||t&&io(t,i)))return!0}return!1}s(so,"importerInEnforcedSubtree");function ao(t,e,n){return t==null||t==="deny"?!1:t==="advisory"?!0:t.default==="deny"?!1:!so(e,n,t.enforce)}s(ao,"siblingCrossingAdvisory");function en(t){if(typeof t!="string")return null;let e=se(t.trim().replace(/\\/g,"/")).toLowerCase();if(!e.includes("/"))return null;let n=e.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}s(en,"childSlicePatternSegments");function tn(t,e){let n=en(t),r=en(e);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!=="*"&&i!==r[o])return!1}return!0}s(tn,"childSlicePatternMatches");function co(t,e,n){if(!t?.length)return!1;for(let r of t)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&tn(r.from,e)&&tn(r.to,n))return!0;return!1}s(co,"childCrossSliceAllowed");function lo(t){let e=zr({fromPath:t.fromPath,toPath:t.toPath,folderCount:t.folderCount,fromSlice:t.fromSlice,toSlice:t.toSlice,fromShared:t.fromShared,toShared:t.toShared,crossSliceAllowed:t.crossSliceAllowed,sharedImportsSlice:t.rule.sharedImportsSlice});if(e.denied){let a=!!t.rule.childSlices&&e.reason==="cross-slice";return{crossing:e.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...a?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:a?Yr(t.fromSlice,t.toSlice):Zr(e.reason??"missing-path",{fromPath:t.fromPath,toPath:t.toPath,fromSlice:t.fromSlice,toSlice:t.toSlice}),peerIsolationReason:e.reason,fromUniverse:t.fromSlice,toUniverse:t.toSlice}}let n=t.rule.childSlices;if(!n||!t.fromSlice||!t.toSlice||t.fromSlice!==t.toSlice||!t.toPath)return{crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};let r=t.fromChild??rt(t.fromPath,t.fromSlice,n).childId,o=t.toChild??rt(t.toPath,t.toSlice,n).childId,i={crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};return r&&o&&r!==o?co(n.allowedCrossSlice,r,o)?i:{crossing:"cross-sibling",decision:ao(n.siblings,t.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:eo(r,o,t.fromSlice),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:to(o),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:i}s(lo,"evaluateNestedSliceWall");function an(t,e,n,r){return uo(t,e,n,r)?.rule}s(an,"findDeniedEdgeRule");function uo(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,a=r?.toPath,c=Ur(o,e,r?.layers),l=Yt(i,o,c),d=Yt(a,o,c),u=l.universeId,m=d.universeId,f=lo({rule:o,fromPath:i,toPath:a,folderCount:c.length,fromSlice:u,toSlice:m,fromChild:l.childId,toChild:d.childId,fromShared:!u&&Xt(i,o.sharedRoots),toShared:!m&&Xt(a,o.sharedRoots),crossSliceAllowed:qr(o.allowedCrossSlice,u,m)});if(f.decision!=="allow")return{rule:o,peerIsolationReason:f.peerIsolationReason,fromSlice:u,toSlice:m,sliceVerdict:f};continue}if(e!==n)return{rule:o}}}s(uo,"findDeniedEdgeDecision");async function cn(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let a=an(r.rules,o,i);if(!a)return;let c=e.mode,l=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,d={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:c,message:l,rule:a};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:d}),await e.recordAudit("layer.observedViolation",t,d),c==="hard")throw new re(n,t.intent,o,i,l)}s(cn,"assertObservedLayerFlowAllowed");async function ln(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))}s(ln,"enforcePublishPolicy");function fo(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}s(fo,"appendHistory");function ae(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}s(ae,"appendTrace");async function Se(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){ae(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}s(Se,"recordAudit");async function dn(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."};ae(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 Se(t,"event.rawPublish",e,n)}s(dn,"recordRawPublishDiagnostic");async function un(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return fo(t,o),await t.eventBuffer?.enqueue(e,r),ae(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 Se(t,"event.published",e,{subscribersNotified:n}),o}s(un,"recordSuccessfulPublish");function it(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}s(it,"enrichMetadata");var fn=0;function po(){return fn+=1,`interceptor-${Date.now()}-${fn}`}s(po,"nextInterceptorRegistrationId");var ce=class{static{s(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new M(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Qe)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new te;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,a=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,l,d=typeof e!="function";if(d){let f=e,g=r??n??{};l={...f,metadata:it(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,y=r??{},p=f(g);l={...p,metadata:it(p.metadata,y,this.recording.instanceId)}}d&&this.strictRegistry&&await dn(this.recording,l),oe(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Vt(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ie(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await qt(l,{interceptorsForIntent:s(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,y)=>this.recordAudit(f,g,y),"recordAudit")}),ie(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await cn(l,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,y)=>this.recordAudit(f,g,y),"recordAudit")}),this.dependencyGraph?.registerEventFlow(l.metadata.source,l.intent);let u=[...this.subscriptionsByIntent.get(l.intent)??[]];this.policyEngine&&await ln(l,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(f=>this.appendTrace(f),"appendTrace"),recordAudit:s((f,g,y)=>this.recordAudit(f,g,y),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((f,g,y)=>this.safeHook(f,g,y),"safeHook")}),await un(this.recording,l,i?u.length:0,o.tx);let m=(async()=>{i&&await Promise.all(u.map(f=>this.invokeHandler(f,l))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(l),"onPublish",l)})();return a?await m:m.then(void 0,()=>{}),l}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:s(async(r,o,i={},a)=>{if(i.source&&i.source!==n)throw new N(n,i.source);await this.publish(r,o,{...i,source:n},a)},"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 a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let l=c.indexOf(o);l>=0&&c.splice(l,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:po(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let a=this.interceptorsByIntent.get(o)??[];return a.push(i),this.interceptorsByIntent.set(o,a),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){ae(this.recording,e)}async recordAudit(e,n,r){await Se(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 go(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}s(go,"formatStandardSchemaPath");function mo(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}s(mo,"actualType");function ho(t,e){return t?`${t}.${e}`:e}s(ho,"formatPath");function pn(t,e,n,r,o){let i=mo(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(a=>Object.is(a,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}gn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{pn(a,e.items,`${n}[${c}]`,r,o)})}s(pn,"validateSchemaField");function gn(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=ho(o,i),l=t[i];if(l===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}pn(l,a,c,n,r)}}s(gn,"validateObjectSchema");var be=class{static{s(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(gn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(i))r.schema[a]||o.push({intent:e.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(e.payload);if(a instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let c of a.issues)o.push({intent:e.intent,version:r.version,field:go(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 st(){return new be}s(st,"createEventContractRegistry");var Ee=class{static{s(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
|
|
8
8
|
`;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
|
|
9
9
|
`}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(e+=` ${this.safeId(r)}
|
|
10
|
-
`);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let
|
|
11
|
-
`;for(let i of e.layers){let
|
|
12
|
-
`;for(let c of
|
|
10
|
+
`);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let a=e.resolveLayer(i)??"Unclassified",c=n.get(a)??[];c.push(i),n.set(a,c)}let r=`flowchart TD
|
|
11
|
+
`;for(let i of e.layers){let a=n.get(i.name)??[];if(a.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
|
|
12
|
+
`;for(let c of a)r+=` ${this.safeId(c)}[${c}]
|
|
13
13
|
`;r+=` end
|
|
14
14
|
`}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
|
|
15
15
|
`;for(let i of o)r+=` ${this.safeId(i)}[${i}]
|
|
16
16
|
`;r+=` end
|
|
17
|
-
`}for(let i of this.edges){let
|
|
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.21";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};
|
|
17
|
+
`}for(let i of this.edges){let a=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${a} ${this.safeId(i.to)}
|
|
18
|
+
`}return r.trim()}detectViolations(e=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of e)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(e){this.nodes.has(e)||this.nodes.set(e,{id:e})}addEdge(e){this.edges.some(r=>r.from===e.from&&r.to===e.to&&r.kind===e.kind)||this.edges.push(e)}findSimpleCycles(){let e=new Map;for(let c of this.edges)e.has(c.from)||e.set(c.from,[]),e.get(c.from).push(c.to);let n=[],r=new Set,o=[],i=s(c=>{r.add(c),o.push(c);for(let l of e.get(c)||[])if(!r.has(l))i(l);else if(o.includes(l)){let d=o.indexOf(l),u=o.slice(d).concat(l);n.push(u)}o.pop()},"dfs");for(let c of e.keys())r.has(c)||i(c);let a=new Set(n.map(c=>c.join("->")));return Array.from(a).map(c=>c.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function at(){return new Ee}s(at,"createDependencyGraph");function ct(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}s(ct,"syncRegistryToGraph");var le=class{static{s(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=s(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Ls=new le;function lt(){return new le}s(lt,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},mn={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}}},hn={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 yn="1.3",yo=["public","auth","admin","internal"];var kn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",wn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],ko=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function wo(){let t=[];for(let e of wn)for(let n of wn)e===n||ko.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(wo,"createDefaultRules");var dt=wo();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ea={$schema:"https://json-schema.org/draft/2020-12/schema",$id:kn,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:kn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:yn,default:yn},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:dt,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:[...yo]},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","deny-cross-parent"],description:"deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. arkgate 4.8.22 and older reject deny-cross-parent."},childSlices:{type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Absent keeps today's universe wall. sliceFolders names children. commonFolders and flat files are universe common. siblings is "deny" (default), "advisory", or { default, enforce }. parentMayImportChild defaults to false. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...w,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...w,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce } so listed subtrees are errors while the default stays advisory. A string-enum build rejects the object at config load (must be one of deny, advisory).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...w}}}]},parentMayImportChild:{type:"boolean"},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A bare name, a universe id alone, an unknown universe, and a wildcard in to are rejected. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each alias as an owed move. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget 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:mn,arkOrder:hn}};function Ao(t){return t.endsWith(".")?t:`${t}.`}s(Ao,"normalizePrefix");function Io(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}s(Io,"byLongestPrefix");function An(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Ao)})),n=[...e].sort(Io),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(a=>o.startsWith(a)))?.name}}}s(An,"createArchitectureProfile");var Ro=[{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}],ut=An({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ro,rules:dt.map(t=>({...t}))});var In="4.8.23";function bo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(bo,"policyId");var ft=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function pt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,a=t.projections,c=t.eventContracts,l=t.observability,d=e?e.list().map(h=>({name:h.name,dependencies:e.getDependencies(h.name),productions:e.getProductions(h.name)})):[],u=e?e.getAllRelationships():[],m=n?n.getPolicies().map(h=>({id:bo(h.name),name:h.name,severity:h.severity,tags:h.tags?[...h.tags]:void 0,owner:h.owner,version:h.version,rationale:h.rationale,enforcementMode:h.enforcementMode,deprecated:h.deprecated,replacedBy:h.replacedBy,description:h.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},y=f.filter(h=>(h.emits?.length??0)>0||(h.consumes?.length??0)>0).map(h=>({entity:h.name,emits:h.emits,consumes:h.consumes})),p=a?a.list().map(h=>({name:h.name,sourceIntents:h.sourceIntents,checkpoint:a.getCheckpoint(h.name)})):[],F={schemaVersion:"1.0",version:In,exportedAt:new Date().toISOString(),intents:d,relationships:u,policies:m,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:l?.report(),links:{entityIntents:y}};return new ft(F)}s(pt,"createArkManifest");var ve=class{static{s(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function gt(){return new ve}s(gt,"createMetadataRegistry");function mt(t){return`${t.from}->${t.to}`}s(mt,"flowKey");function Sn(t){let e=new Set,n=[];for(let r of t){let o=mt(r);e.has(o)||(e.add(o),n.push(r))}return n}s(Sn,"uniqueFlows");function bn(t,e){let n=new Set(e.map(mt));return t.filter(r=>!n.has(mt(r)))}s(bn,"difference");function ht(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})),a=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=a.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),l=Sn([...o,...i]),d=Sn([...a,...c]),u=d.filter(p=>!p.from||p.from==="unknown"),m=e?Array.from(new Set(d.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(d.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(d.flatMap(p=>[p.from,p.to])),y=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:l,observedProductions:d,declaredButUnobserved:bn(l,d),observedButUndeclared:bn(d.filter(p=>p.from!=="unknown"),l),unknownSources:u,unregisteredObservedSources:m,unregisteredObservedIntents:f,registeredButNeverObserved:y}}}}s(ht,"createObservabilityReporter");var En=0;function Eo(){return En+=1,`outbox-${Date.now()}-${En}`}s(Eo,"nextOutboxId");function vn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(vn,"cloneRecord");var de=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Eo(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),vn(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(vn)}async clear(){this.records.clear()}};var xe=class{static{s(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function vo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(vo,"initialState");var Pe=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new xe,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)??vo(r),i=await r.project(e,o);await this.store.save(r.name,i);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function yt(t){return new Pe(t)}s(yt,"createProjectionRegistry");var xn=0;function xo(t){return xn+=1,`${t}-${Date.now()}-${xn}`}s(xo,"createWorkflowId");function kt(t){return t instanceof Error?t.message:String(t)}s(kt,"errorMessage");function Po(t){return new Promise(e=>{setTimeout(e,t)})}s(Po,"sleep");async function Co(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((a,c)=>{o=setTimeout(()=>{let l=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(l),c(l)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}s(Co,"withTimeout");var Ce=class{static{s(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let a=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||a){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},wt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Ce}bus;options;static{s(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),a={id:r.id??xo(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:e}),this.executeSnapshot(a,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=kt(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let a=1;a<=i;a+=1){e.attempts[n.name]=a,await this.store.save(e,r);let c;try{c=await Co(l=>Promise.resolve(n.execute(e.context,this.bus,l)),n.timeoutMs,n.name)}catch(l){if(a<i){o.delayMs&&await Po(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:a,error:kt(l)}),l}c&&Object.assign(e.context,c),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(a=>e.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let c=i[a];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(l){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:kt(l)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function At(t,e){return new wt(t,e)}s(At,"createWorkflowEngine");H();var Oo=new Set(["singleton","transient"]);function Pn(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}s(Pn,"cloneComponent");function No(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Oo.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(No,"closedLifetime");function Cn(){let t=new Map,e=new Map,n=new Set;function r(a){let c=t.get(a);if(!c)throw new Error(`ArkRun component "${a}" is not registered.`);return c}s(r,"mustRecord");function o(a,c){if(!c.factory)throw new Error(`ArkRun component "${a}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(a))throw new Error(`ArkRun component "${a}" has a circular resolve.`);n.add(a);try{return c.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,c){if(e.has(a))return e.get(a);let l=o(a,c);return e.set(a,l),l}return s(i,"singleton"),{register(a){let c=typeof a?.id=="string"?a.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let l=No(a.lifetime),d=_e({id:c,lifetime:l,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!d)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof a.factory=="function"?a.factory:void 0;return t.set(c,{component:d,factory:u}),Pn(d)},resolve(a){let c=r(a);return c.component.lifetime==="transient"?o(a,c):i(a,c)},resolveSingleton(a){let c=r(a);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,c)},snapshotComponents(){return[...t.values()].map(a=>Pn(a.component))}}}s(Cn,"createComponentRegistry");we();async function Dn(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(()=>(Nn(),On));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(Dn,"startArkRunInspector");me();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}s(Ko,"stampMetadata");function Fo(){}s(Fo,"ignoreDetachedFailure");async function It(t,e,n,r={}){let o=_t({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Ko(r),a=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(a));o.awaitHandoff?await c:c.then(void 0,Fo)}return o}s(It,"sendOnArkRunTransport");var Bo=1e3,Ln=0;function jo(){return Ln+=1,`ark-kernel-${Date.now()}-${Ln}`}s(jo,"nextKernelInstanceId");function Tn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}s(Tn,"portConstructorId");function _n(t={}){let e=t.strict??!0,n=t.instanceId??jo(),r=t.profile??ut,o=t.maxHistorySize??Bo,i=lt(),a=at(),c=t.metadata??gt(),l=t.auditTrail===void 0,d=t.auditTrail??Je({maxRecords:o}),u=t.eventContracts??st(),m=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new de,g=t.projections??yt({auditTrail:d}),y=new M([Xe(r),...t.policies??[]]),p=s(()=>{ct(i,a,{requireRegisteredTargets:!0})},"syncGraph"),F=t.ephemeral??!0,h=t.broker,L=new ce({intentRegistry:i,dependencyGraph:a,policyEngine:y,strictRegistry:!0,validateIntentNaming:!0,auditTrail:d,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)}}),Rt=At(L,{auditTrail:d}),Oe=ht({registry:i,eventBus:L,graph:a}),T=Cn(),Mn=typeof h?.send=="function",$n=m?"InMemoryEventBuffer":Tn(f,"EventBufferStore"),Gn=l?"InMemoryAuditStore":Tn(d,"AuditTrail"),Kn=qe({stores:[Q($n,"outbox"),Q(Gn,"audit"),Q("InMemoryWorkflowStore","workflow")]}),Ne={instanceId:n,profile:r,registry:i,graph:a,metadata:c,auditTrail:d,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:y,eventBus:L,workflowEngine:Rt,observability:Oe,publisher(k){let _=L.createPublisher(k);return{source:_.source,publish:_.publish,send(b,De,Fn={}){return It({eventBus:L,broker:h,defaultEphemeral:F},b,De,{...Fn,source:_.source})}}},send(k,_,b={}){return It({eventBus:L,broker:h,defaultEphemeral:F},k,_,b)},register(k){return T.register(k)},resolve(k){return T.resolve(k)},resolveSingleton(k){return T.resolveSingleton(k)},getDependencyInformationPackage(){return P({kernelInstanceId:n,components:T.snapshotComponents()})},requestGraph(k){return Tt({kernelInstanceId:n,components:T.snapshotComponents()},k)},getInspectorSnapshot(k){return Ft({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:T.snapshotComponents()},observability:Oe.report(),ephemeralDefault:F,brokerBound:Mn,hardening:Kn})},startInspector(k){return Dn({getInspectorSnapshot:s(b=>Ne.getInspectorSnapshot(b),"getInspectorSnapshot"),requestGraph:s(b=>Ne.requestGraph(b),"requestGraph"),async listInspectorOutbox(){let[b,De]=await Promise.all([f.list("pending"),f.list("failed")]);return X([...b,...De],{sampleLimit:I})},async listInspectorWorkflows(){return Z(await Rt.list(),{sampleLimit:I})}},k)},syncGraph:p,manifest(){return p(),pt({registry:i,policyEngine:y,metadata:c,graph:a,profile:r,projections:g,eventContracts:u,observability:Oe})}};return Ne}s(_n,"createArkKernel");var ue=Symbol("ARK_KERNEL"),Oc=s(()=>Ho(ue),"InjectArk"),x=class{static forRoot(e){let n=e&&"registry"in e?e:_n(e);return{module:x,global:!0,providers:[{provide:ue,useValue:n}],exports:[ue]}}static forRootAsync(e){return{module:x,global:!0,providers:[{provide:ue,useFactory:e.useFactory,inject:e.inject??[]}],exports:[ue]}}};s(x,"ArkModule"),x=St([Uo({})],x);export{ue as ARK_KERNEL,x as ArkModule,Oc as InjectArk};
|