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.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}function
|
|
1
|
+
"use strict";var Vn=Object.create;var M=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var qn=Object.getPrototypeOf,zn=Object.prototype.hasOwnProperty;var s=(t,e)=>M(t,"name",{value:e,configurable:!0});var H=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var Et=(t,e)=>{for(var n in e)M(t,n,{get:e[n],enumerable:!0})},vt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wn(e))!zn.call(t,o)&&o!==n&&M(t,o,{get:()=>e[o],enumerable:!(r=bt(e,o))||r.enumerable});return t};var Jn=(t,e,n)=>(n=t!=null?Vn(qn(t)):{},vt(e||!t||!t.__esModule?M(n,"default",{value:t,enumerable:!0}):n,t)),Qn=t=>vt(M({},"__esModule",{value:!0}),t),xt=(t,e,n,r)=>{for(var o=r>1?void 0:r?bt(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&&M(e,n,o),o};function _e(t,e){return t<e?-1:t>e?1:0}function er(t){return[...new Set(t)].sort(_e)}function U(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n=="string"&&n.length>0&&e.push(n);return er(e)}function tr(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t}function nr(t){return typeof t=="string"&&Yn.has(t)?t:"singleton"}function Pt(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of Object.keys(t).sort(_e)){if(n.length===0)continue;let r=tr(t[n]);r!==void 0&&(e[n]=r)}return Object.keys(e).length>0?e:void 0}function rr(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=U(e.tags);r.length>0&&(n.tags=r),typeof e.group=="string"&&e.group.length>0&&(n.group=e.group);let o=Pt(e.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Me(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.id=="string"?e.id.trim():"";if(!n)return;let r={id:n,lifetime:nr(e.lifetime),uses:U(e.uses),reactsTo:U(e.reactsTo),raises:U(e.raises),sends:U(e.sends)},o=rr(e.extendedInfo);return o&&(r.extendedInfo=o),r}function ir(t){return Pt(t)}function sr(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"&&or.has(c.kind)?c.kind:void 0;if(!l)return;let d={kind:i},u=ir(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 ar(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){let r=sr(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=Me(a);!c||r.has(c.id)||(r.add(c.id),o.push(c))}o.sort((a,c)=>_e(a.id,c.id));let i=ar(t.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:e,components:o,...i.length>0?{decisionTape:i}:{}}}var Xn,Zn,Yn,or,V=H(()=>{"use strict";Xn=["singleton","transient"],Zn=["absorb","escalate_up","hold"],Yn=new Set(Xn);s(_e,"compare");s(er,"uniqueSorted");s(U,"nameList");s(tr,"jsonPrimitive");s(nr,"closedLifetime");s(Pt,"sanitizeMetadata");s(rr,"sanitizeArkRunExtendedInfo");s(Me,"sanitizeArkRunComponent");or=new Set(Zn);s(ir,"sanitizeTapePayload");s(sr,"sanitizeDecisionTapeRecord");s(ar,"sanitizeDecisionTape");s(P,"buildDependencyInformationPackage")});function z(t,e){return t<e?-1:t>e?1:0}function $e(t){return[...new Set(t)].sort(z)}function Ct(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function Ge(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 $e(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 $e(n)}function Lt(t,e){if(e==="*")return t.length>0;if(!e.includes("*"))return t===e;let n="^";for(let r of e)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(t)}function W(t,e){return t?e.some(n=>Lt(t,n)):!1}function Tt(t){if(t==null||t==="")return lr;if(typeof t=="string"&&ur.has(t))return t;throw new A("slice")}function _t(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 Ot(t,e){if(t==null||t==="")return Ct();if(typeof t=="string"||Array.isArray(t))return{...Ct(),tokens:R(t,e)};if(typeof t!="object")throw new A(e);let n=t;for(let r of Object.keys(n))if(!pr.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 Mt(t={}){if(t==null||t==="")return Mt({});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(!fr.has(n))throw new A("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Tt(e.slice),nodeIds:R(e.nodeIds,"nodeIds"),degreesOfSeparation:_t(e.degreesOfSeparation),include:Ot(e.include,"include"),exclude:Ot(e.exclude,"exclude")}}function $t(t){let e={};t.slice&&(e.slice=Tt(t.slice));let n=R(t.nodeIds??void 0,"nodeIds");n.length>0&&(e.nodeIds=n);let r=_t(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 gr(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 Nt(t,e){if(!Ge(e))return!0;let n=gr(t);return e.tokens.some(r=>n.some(o=>Lt(o,r)))||W(t.id,e.ids)||W(t.label,e.labels)||t.tags?.some(r=>W(r,e.tags))||W(t.group,e.groups)?!0:W(t.architectureKind,e.architectureKinds)}function mr(t){if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;return P({kernelInstanceId:e.kernelInstanceId,components:e.components})}return P({})}function hr(t){let e={id:t.id,kind:"component",lifetime:t.lifetime},n=t.extendedInfo;return n?.label&&(e.label=n.label),n?.group&&(e.group=n.group),n?.architectureKind&&(e.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(e.tags=[...n.tags]),e}function pe(t){return{id:t,kind:"interaction"}}function q(t,e){let n=t.get(e.id);(!n||n.kind==="interaction"&&e.kind==="component")&&t.set(e.id,e)}function ge(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 yr(t,e){let n=new Map,r=[],o=new Set;for(let i of t){if(q(n,hr(i)),e==="technical"){for(let a of i.uses)q(n,n.get(a)??pe(a)),ge(r,o,i.id,a,"uses");continue}for(let a of i.raises)q(n,n.get(a)??pe(a)),ge(r,o,i.id,a,"raises");for(let a of i.reactsTo)q(n,n.get(a)??pe(a)),ge(r,o,a,i.id,"reactsTo");for(let a of i.sends)q(n,n.get(a)??pe(a)),ge(r,o,i.id,a,"sends")}return{nodes:n,edges:r}}function kr(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 wr(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 J(t){let e=t.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(e)?e:`n_${e}`}function Dt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Ar(t){let e=new Set,n=new Map;for(let r of t){let o=J(r),i=o,a=2;for(;e.has(i);)i=`${o}_${a}`,a+=1;e.add(i),n.set(r,i)}return n}function Ir(t){let e=t.slice==="technical"?"TD":"LR",n=t.nodes.map(c=>c.id),r=Ar(n),o=$e(t.nodes.map(c=>c.group).filter(c=>!!c)),i=[`flowchart ${e}`],a=s((c,l)=>{let d=r.get(c.id)??J(c.id),u=Dt(c.label??c.id);i.push(`${l}${d}["${u}"]`)},"emitNode");for(let c of o){let l=J(`group_${c}`);i.push(` subgraph ${l}["${Dt(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)??J(c.from),d=r.get(c.to)??J(c.to);i.push(` ${l} -->|${c.kind}| ${d}`)}return i.join(`
|
|
2
|
+
`)}function Rr(t,e,n){let r=new Set(t.keys());if(Ge(n.include)&&(r=new Set([...r].filter(c=>{let l=t.get(c);return l!==void 0&&Nt(l,n.include)}))),Ge(n.exclude))for(let c of[...r]){let l=t.get(c);l&&Nt(l,n.exclude)&&r.delete(c)}let o=e.filter(c=>r.has(c.from)&&r.has(c.to));n.nodeIds.length>0&&(r=wr(r,n.nodeIds,n.degreesOfSeparation,kr(o)));let i=[...r].sort(z).map(c=>t.get(c)).filter(c=>!!c),a=o.filter(c=>r.has(c.from)&&r.has(c.to)).sort((c,l)=>z(c.from,l.from)||z(c.kind,l.kind)||z(c.to,l.to));return{nodes:i,edges:a}}function Gt(t={},e={}){let n=mr(t),r=Mt(e),o=yr(n.components,r.slice),i=Rr(o.nodes,o.edges,r),a={schemaVersion:cr,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=Ir(a),a}var cr,lr,dr,A,ur,fr,pr,Ke=H(()=>{"use strict";V();cr="1.0",lr="process",dr=["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}},ur=new Set(dr),fr=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),pr=new Set(["ids","labels","tags","groups","architectureKinds"]);s(z,"compare");s($e,"uniqueSorted");s(Ct,"emptyMatch");s(Ge,"matchHasCriteria");s(R,"nameList");s(Lt,"globMatch");s(W,"anyGlob");s(Tt,"closedSlice");s(_t,"closedDegrees");s(Ot,"closedMatch");s(Mt,"closeArkRunGraphQuery");s($t,"arkRunGraphQueryFromSearchParams");s(gr,"nodeFields");s(Nt,"nodeMatches");s(mr,"asPackage");s(hr,"componentNode");s(pe,"interactionNode");s(q,"addNode");s(ge,"addEdge");s(yr,"buildSlice");s(kr,"adjacency");s(wr,"neighborhood");s(J,"mermaidSafeId");s(Dt,"mermaidLabel");s(Ar,"uniqueMermaidIds");s(Ir,"formatArkRunGraphMermaid");s(Rr,"filterGraph");s(Gt,"requestArkRunGraph")});function br(t){if(t===void 0)return"local";if(typeof t=="string"&&Sr.has(t))return t;throw new me("transport")}function Er(t){if(t===void 0)return!0;if(t===!0||t===!1)return t;throw new me("ephemeral")}function Kt(t){let e=br(t.transport),n=Er(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 Fe,Sr,me,he=H(()=>{"use strict";Fe=["local","localBlocking","broker"],Sr=new Set(Fe),me=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(br,"closedArkRunTransportKind");s(Er,"closedArkRunEphemeral");s(Kt,"resolveArkRunSendPlan")});function Bt(t){return t==="production"}function Dr(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 jt(t){if(t.startsWith("[::ffff:")&&t.endsWith("]"))return t.slice(8,-1);if(t.startsWith("::ffff:"))return t.slice(7)}function ke(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1"||e==="[::1]")return!0;let n=jt(e);if(n)return ke(n);let r=Dr(e);return r!==void 0&&r[0]===127}function Ht(t){if(t===void 0)return Ft;if(typeof t!="string")throw new S(String(t));let e=t.trim();if(Nr.has(e.toLowerCase())||!ke(e))throw new S(e);let n=e.toLowerCase();if(n==="localhost")return Ft;if(n==="[::1]")return"::1";let r=jt(n);return r?Ht(r):n}function Lr(t){if(t===void 0)return Pr;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>65535)throw new S(`port:${String(t)}`);return t}function qe(t={}){if(Bt(t.nodeEnv)||Bt(t.processNodeEnv))throw new ye;return{host:Ht(t.host),port:Lr(t.port)}}function C(t,e,n){return`http://${t.includes(":")?`[${t}]`:t}:${e}${n}`}function Tr(t){if(t!==void 0)try{return JSON.parse(JSON.stringify(t))}catch{return}}function _r(t){return{kinds:[...Fe],ephemeralDefault:t.ephemeralDefault===!1?!1:!0,brokerBound:t.brokerBound===!0,cloudSdksShipped:!1,fallback:Or}}function v(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Mr(t){let e=v(t);if(!e||typeof e.id!="string")return;let n=e.status;if(n!=="pending"&&n!=="failed")return;let r=v(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 we(t){if(typeof t!="number"||!Number.isFinite(t))return I;let e=Math.trunc(t);return e<0?0:e>I?I:e}function Z(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():t&&typeof t=="object"&&"constructor"in t?String(t.constructor?.name??e):e,r=/^InMemory/i.test(n)?"memory":"durable";return{role:e,id:n,kind:r}}function ze(t={}){let e=v(t),n=v(e?.durability)??e,r=Array.isArray(n?.stores)?n.stores:Array.isArray(e?.stores)?e.stores:[],o=[];for(let i of r){let a=v(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:Z(l,c).kind;o.push({role:c,id:l,kind:d})}return{durability:{stores:o}}}function Y(t=[],e={}){let n=we(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=[];for(let a of r){let c=Mr(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 Q(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:I}}function $r(t){let e=v(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 Gr(t){return t==="idle"||t==="waiting"}function ee(t=[],e={}){let n=we(e.sampleLimit),r=Array.isArray(t)?t:[],o=[],i=0,a=0,c=0,l=0;for(let d of r){let u=$r(d);u&&(o.push(u),u.status==="running"?i+=1:u.status==="compensating"?a+=1:u.status==="failed"?c+=1:Gr(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 X(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:I}}function Kr(t){if(t===void 0)return;let e=v(t);if(!e||e.available===!1)return Q();let n=we(e.sampleLimit);if(Array.isArray(e.pending)||Array.isArray(e.failed)||Array.isArray(e.records)){let r=[...Array.isArray(e.pending)?e.pending:[],...Array.isArray(e.failed)?e.failed:[],...Array.isArray(e.records)?e.records:[]],o=Y(r,{sampleLimit:n}),i=typeof e.pendingCount=="number"&&Number.isFinite(e.pendingCount)?Math.max(0,Math.trunc(e.pendingCount)):o.pendingCount,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 Q()}function Fr(t){if(t===void 0)return;let e=v(t);if(!e||e.available===!1)return X();let n=we(e.sampleLimit);if(Array.isArray(e.workflows)){let r=ee(e.workflows,{sampleLimit:n}),o=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(0,Math.trunc(e.total)):r.total,i=typeof e.runningCount=="number"&&Number.isFinite(e.runningCount)?Math.max(0,Math.trunc(e.runningCount)):r.runningCount,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 X()}function Ut(t={}){let e=qe({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=Kr(t.outbox),o=Fr(t.workflows),i={schemaVersion:xr,kernelInstanceId:typeof t.kernelInstanceId=="string"?t.kernelInstanceId:n.kernelInstanceId,bind:{host:e.host,port:e.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:_r(t),observability:Tr(t.observability)??{},hardening:ze(t.hardening)};return r&&(i.outbox=r),o&&(i.workflows=o),i}function Je(t){return`event: ${Cr}
|
|
3
3
|
data: ${JSON.stringify(t)}
|
|
4
4
|
|
|
5
|
-
`}var
|
|
5
|
+
`}var xr,Ft,Pr,je,He,Ue,Ve,We,Cr,Or,I,ye,S,Nr,Ae=H(()=>{"use strict";V();he();xr="1.0",Ft="127.0.0.1",Pr=0,je="/snapshot",He="/events",Ue="/graph",Ve="/outbox",We="/workflows",Cr="snapshot",Or="in-process-local",I=32,ye=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"}},Nr=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(Bt,"isArkRunInspectorProductionEnv");s(Dr,"ipv4Octets");s(jt,"unwrapIpv4Mapped");s(ke,"isArkRunInspectorLoopbackHost");s(Ht,"closedHost");s(Lr,"closedPort");s(qe,"resolveArkRunInspectorBind");s(C,"arkRunInspectorUrl");s(Tr,"jsonClone");s(_r,"closedTransportFacts");s(v,"asRecord");s(Mr,"closedOutboxSummary");s(we,"closedSampleLimit");s(Z,"classifyArkRunInspectorStoreDurability");s(ze,"buildArkRunInspectorHardening");s(Y,"buildArkRunInspectorOutboxMonitor");s(Q,"unavailableArkRunInspectorOutboxMonitor");s($r,"closedWorkflowSummary");s(Gr,"isPendingWorkflowStatus");s(ee,"buildArkRunInspectorWorkflowsMonitor");s(X,"unavailableArkRunInspectorWorkflowsMonitor");s(Kr,"closedOutboxMonitor");s(Fr,"closedWorkflowsMonitor");s(Ut,"buildArkRunInspectorSnapshot");s(Je,"formatArkRunInspectorSseEvent")});var Tn={};Et(Tn,{listenArkRunInspector:()=>Wo});function Fo(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Bo(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function jo(t){let e=t&&t.length>0?t:"/";return new URL(e,"http://127.0.0.1")}function x(t,e,n){if(!(t.writableEnded||t.destroyed))try{t.writeHead(e,Fo()),t.end(JSON.stringify(n))}catch{}}function Ho(t,e){let n=t.address();if(n===null||typeof n=="string")throw new S(e.host);if(!ke(n.address))throw new S(n.address);return{host:e.host,port:n.port}}async function Uo(t){if(typeof t.listInspectorOutbox=="function")return t.listInspectorOutbox();let e=t.outbox??t.eventBuffer;if(!e||typeof e.list!="function")return Q();let[n,r]=await Promise.all([e.list("pending"),e.list("failed")]);return Y([...n??[],...r??[]],{sampleLimit:I})}async function Vo(t){return typeof t.listInspectorWorkflows=="function"?t.listInspectorWorkflows():!t.workflowEngine||typeof t.workflowEngine.list!="function"?X():ee(await t.workflowEngine.list(),{sampleLimit:I})}async function Wo(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=jo(d.url),f=m.pathname;if(d.method==="GET"&&(f==="/"||f===je)){x(u,200,c());return}if(d.method==="GET"&&f===Ue){try{x(u,200,t.requestGraph($t({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){x(u,400,{error:g.message,option:g.option});return}throw g}return}if(d.method==="GET"&&f===Ve){Uo(t).then(g=>x(u,200,g)).catch(g=>{x(u,500,{error:g instanceof Error?g.message:"outbox monitor failed"})});return}if(d.method==="GET"&&f===We){Vo(t).then(g=>x(u,200,g)).catch(g=>{x(u,500,{error:g instanceof Error?g.message:"workflows monitor failed"})});return}if(d.method==="GET"&&f===He){u.writeHead(200,Bo()),u.flushHeaders(),u.write(Je(c())),r.add(u);let g=i>0?setInterval(()=>{u.write(Je(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}x(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=Ho(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,je),eventsUrl:C(a.host,a.port,He),graphUrl:C(a.host,a.port,Ue),outboxUrl:C(a.host,a.port,Ve),workflowsUrl:C(a.host,a.port,We),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 _n=H(()=>{"use strict";Ke();Ae();s(Fo,"jsonHeaders");s(Bo,"sseHeaders");s(jo,"requestUrl");s(x,"writeJson");s(Ho,"boundAddress");s(Uo,"resolveOutboxMonitor");s(Vo,"resolveWorkflowsMonitor");s(Wo,"listenArkRunInspector")});var Zo={};Et(Zo,{ARK_KERNEL:()=>B,ArkModule:()=>E,InjectArk:()=>Xo});module.exports=Qn(Zo);var Ne=require("@nestjs/common");Ke();Ae();V();he();var Vt=0;function Br(){return Vt+=1,`audit-${Date.now()}-${Vt}`}s(Br,"createAuditId");function jr(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(jr,"matchesQuery");var Ie=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=>jr(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},Re=class{constructor(e){this.store=e}store;static{s(this,"AuditTrailImpl")}async record(e){let n={id:Br(),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 Qe(t={}){return new Re(t.store??new Ie(t.maxRecords))}s(Qe,"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 Ie(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}a(Ie,"definePolicy");function $r(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}a($r,"defaultLayerOf");function Ft(t,e){return e.resolveLayer?.(t)??$r(t)}a(Ft,"resolveLayer");function Kr(t,e,n){return t===n.from&&e===n.to}a(Kr,"matchesRule");function Ht(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Ie({name:e,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(s=>s.kind==="declared"||s.kind==="produces").map(s=>({from:s.from,to:s.to})),...(r.relationships??[]).filter(s=>s.kind==="dependsOn").map(s=>({from:s.from,to:s.to}))],i=[];for(let s of o){let c=Ft(s.from,t),d=Ft(s.to,t);for(let l of t.rules)!l.allowed&&Kr(c,d,l)&&i.push({policyName:e,severity:n,message:l.message??`Layer violation: ${s.from} (${c}) must not relate to ${s.to} (${d})`})}return i.length>0?i:!0},"check")})}a(Ht,"defineLayerPolicy");function Qe(t){return t.tags?.includes("layer")??!1}a(Qe,"isLayerPolicy");function Xe(t,e={}){return Ht({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}a(Xe,"defineArchitectureProfilePolicy");function Ze(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}a(Ze,"buildPublishPolicyContext");var te=class extends Error{static{a(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},ne=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},re=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},oe=class extends Error{static{a(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},K=class extends Error{static{a(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},N=class extends Error{static{a(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},ie=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}};var Vt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Ye(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Vt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${Vt.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}a(Ye,"validateIntentName");function se(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Ye(t);if(!n.valid)throw new ne(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new te(t)}}a(se,"assertIntentAllowed");function Ut(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new K(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new K(t.intent,t.metadata.source)}}a(Ut,"assertSourceAllowed");function ae(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new oe(t.intent,n.issues)}a(ae,"assertContractAllowed");function G(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}a(G,"isPlainRecord");function B(t){return Array.isArray(t)?t.map(B):G(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,B(n)])):t}a(B,"clonePatchValue");function et(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let s=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=B(i);continue}if(G(r[o])&&G(i)){r[o]=et(r[o],i,s);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=tt(r[o],i,s);continue}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}return r}a(et,"mergeRecordPatch");function tt(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let s=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=B(o);return}if(G(r[i])&&G(o)){r[i]=et(r[i],o,s);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=tt(r[i],o,s);return}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}),r}a(tt,"mergeArrayPatch");function Wt(t,e){if(Array.isArray(e)){if(t===void 0)return B(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return tt(t,e)}if(t===void 0)return B(e);if(!G(t))throw new Error("Object interceptor patch requires an object payload.");return et(t,e)}a(Wt,"applyPayloadPatch");async function qt(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:a(d=>{i.push(d)},"intercept")})),i.length===0)continue;let s=new Date().toISOString(),c={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:s}]}};for(let d of i)c={...c,payload:Wt(c.payload,d),metadata:{...c.metadata}};ae(c,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=c,o.lastInterceptedAt=s,e.appendTrace({type:"event.intercepted",timestamp:s,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(s){await Gr(o,r,s,e)}}return r}a(qt,"applyInterceptors");async function Gr(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}a(Gr,"recordInterceptorError");var zt=new Map;function Jt(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}a(Jt,"escapeLiteral");function tn(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}a(tn,"normalizeGlobSeparators");function Br(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}a(Br,"bracesBalanced");function Qt(t){let e=zt.get(t);if(e)return e;let n=tn(t),r=Br(n),o="",i=0;for(let c=0;c<n.length;c+=1){let d=n[c];d==="\\"&&c+1<n.length?(o+=Jt(n[c+1]),c+=1):d==="*"?n[c+1]==="*"?n[c+2]==="/"?(o+="(?:.*/)?",c+=2):(o+=".*",c+=1):o+="[^/]*":d==="?"?o+="[^/]":d==="{"&&r?(o+="(?:",i+=1):d==="}"&&r&&i>0?(o+=")",i-=1):d===","&&r&&i>0?o+="|":o+=Jt(d)}let s=new RegExp(`^${o}$`);return zt.set(t,s),s}a(Qt,"globToRegExp");function Xt(t,e,n){if(!e?.length)return;let r=n==="stars"?"stars":"path",o=String(t).split(/[/\\]/).filter(Boolean);if(o.length===0)return;let i=new Set;for(let s of e)if(!(typeof s!="string"||s.length===0)){if(jr(s)){let c=Fr(o,s,r);if(c)return c;continue}!s.includes("/")&&!s.includes("\\")&&!s.includes("*")&&i.add(s.toLowerCase())}return Vr(o,i)}a(Xt,"sliceIdForPath");function jr(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}a(jr,"isAnchoredSliceEntry");function Fr(t,e,n){let r=e.split(/[/\\]/).filter(i=>i.length>0).map(i=>i.toLowerCase()),o=rn(t,r[0]??"");for(let i of o){let s=Hr(t,r,i,n);if(s)return s}}a(Fr,"anchoredSliceId");function Hr(t,e,n,r="path"){let o=[],i=-1,s=n;for(let c=0;c<e.length;c+=1){let d=e[c];if(d==="*"){if(s>=t.length-1){for(let l=c;l<e.length;l+=1)if(e[l]!=="*")return;break}o.push(t[s].toLowerCase()),s+=1;continue}if(d==="**"||s>=t.length||t[s].toLowerCase()!==d)return;o.push(t[s].toLowerCase()),i=o.length-1,s+=1}if(o.length!==0)return r==="stars"?i<0?void 0:o.slice(i).join("/"):o.join("/")}a(Hr,"bindAnchoredSlice");function Vr(t,e){if(e.size!==0){for(let n=0;n<t.length-1;n+=1)if(e.has(t[n].toLowerCase())&&!(n+1>=t.length-1))return`${t[n].toLowerCase()}/${t[n+1].toLowerCase()}`}}a(Vr,"bareSliceId");function Ur(t){let e=new Set;for(let n of t??[]){let o=tn(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let s=o[i];if((s==="**"||s==="*")&&i>0){let c=o[i-1];c&&!c.includes("*")&&!c.includes("{")&&!c.includes("}")&&e.add(c)}}}return[...e]}a(Ur,"inferSliceFoldersFromPatterns");function Wr(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return Ur(r?.patterns)}a(Wr,"resolveSliceFolders");function Zt(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}a(Zt,"normalizeSegments");function nn(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(nn,"trimTrailingSlashes");var qr=["src","app"];function rn(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return qr.includes(n)&&r!==n?[0,1]:[0]}a(rn,"anchorOffsets");function zr(t){let e=nn(t.replace(/^[./]+/,""));return e==="*"||e==="**"}a(zr,"isBlanketRoot");function Yt(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Zt(n);for(let i of e){if(typeof i!="string"||i.length===0||zr(i))continue;if(i.includes("*")){let d=nn(i.toLowerCase());if(Qt(d).test(r)||Qt(`${d}/**`).test(r))return!0;continue}let s=Zt(i);if(s.length===0)continue;let c=rn(o,s[0]??"");for(let d of c){if(d+s.length>o.length)continue;let l=!0;for(let u=0;u<s.length;u+=1)if(o[d+u]!==s[u]){l=!1;break}if(l)return!0}}return!1}a(Yt,"pathUnderSharedRoot");function en(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(en,"sliceMatchesDeclaration");function Jr(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&en(r.from,e)&&en(r.to,n))}a(Jr,"crossSliceEdgeAllowed");function Qr(t){if(!t.fromPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0;if(!t.toPath)return e?t.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:t.sharedImportsSlice==="deny"&&t.fromShared===!0&&t.toSlice&&!t.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(Qr,"peerIsolationDecision");function on(t,e,n,r){return Xr(t,e,n,r)?.rule}a(on,"findDeniedEdgeRule");function Xr(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,s=r?.toPath,c=Wr(o,e,r?.layers),d=i?Xt(i,c,o.sliceIdentity):void 0,l=s?Xt(s,c,o.sliceIdentity):void 0,u=Qr({fromPath:i,toPath:s,folderCount:c.length,fromSlice:d,toSlice:l,fromShared:!d&&Yt(i,o.sharedRoots),toShared:!l&&Yt(s,o.sharedRoots),crossSliceAllowed:Jr(o.allowedCrossSlice,d,l),sharedImportsSlice:o.sharedImportsSlice});if(u.denied)return{rule:o,peerIsolationReason:u.reason,fromSlice:d,toSlice:l};continue}if(e!==n)return{rule:o}}}a(Xr,"findDeniedEdgeDecision");async function sn(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let s=on(r.rules,o,i);if(!s)return;let c=e.mode,d=s.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,l={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:c,message:d,rule:s};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:l}),await e.recordAudit("layer.observedViolation",t,l),c==="hard")throw new ie(n,t.intent,o,i,d)}a(sn,"assertObservedLayerFlowAllowed");async function an(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof O&&(e.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:o.violations}}),await e.recordAudit("policy.hardViolation",t,{violations:o.violations})),o}r.softViolations.length>0&&(e.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:r.softViolations}}),await e.recordAudit("policy.softViolation",t,{violations:r.softViolations}),e.onSoftViolation&&await e.safeHook(()=>e.onSoftViolation(r,t),"onSoftViolation",t))}a(an,"enforcePublishPolicy");function Zr(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}a(Zr,"appendHistory");function ce(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}a(ce,"appendTrace");async function be(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){ce(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}a(be,"recordAudit");async function cn(t,e){let n={intent:e.intent,source:e.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};ce(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await be(t,"event.rawPublish",e,n)}a(cn,"recordRawPublishDiagnostic");async function dn(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return Zr(t,o),await t.eventBuffer?.enqueue(e,r),ce(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await be(t,"event.published",e,{subscribersNotified:n}),o}a(dn,"recordSuccessfulPublish");function nt(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}a(nt,"enrichMetadata");var ln=0;function Yr(){return ln+=1,`interceptor-${Date.now()}-${ln}`}a(Yr,"nextInterceptorRegistrationId");var de=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new $(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Qe)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new re;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ze({intentRegistry:e.intentRegistry,dependencyGraph:e.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(e,n,r,o){await this.dispatch(e,n,r,o)}async dispatch(e,n,r,o={}){let i=o.notifySubscribers!==!1,s=o.awaitHandlers!==!1,c=o.runOnPublish!==!1,d,l=typeof e!="function";if(l){let f=e,g=r??n??{};d={...f,metadata:nt(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,h=r??{},p=f(g);d={...p,metadata:nt(p.metadata,h,this.recording.instanceId)}}l&&this.strictRegistry&&await cn(this.recording,d),se(d.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ut(d,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ae(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),d=await qt(d,{interceptorsForIntent:a(f=>this.interceptorsByIntent.get(f)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),ae(d,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await sn(d,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit")}),this.dependencyGraph?.registerEventFlow(d.metadata.source,d.intent);let u=[...this.subscriptionsByIntent.get(d.intent)??[]];this.policyEngine&&await an(d,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(f=>this.appendTrace(f),"appendTrace"),recordAudit:a((f,g,h)=>this.recordAudit(f,g,h),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((f,g,h)=>this.safeHook(f,g,h),"safeHook")}),await dn(this.recording,d,i?u.length:0,o.tx);let y=(async()=>{i&&await Promise.all(u.map(f=>this.invokeHandler(f,d))),c&&this.onPublish&&await this.safeHook(()=>this.onPublish(d),"onPublish",d)})();return s?await y:y.then(void 0,()=>{}),d}createPublisher(e){let n=typeof e=="string"?e:e.name;return se(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,i={},s)=>{if(i.source&&i.source!==n)throw new N(n,i.source);await this.publish(r,o,{...i,source:n},s)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;se(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let s=this.subscriptions.indexOf(o);s>=0&&this.subscriptions.splice(s,1);let c=this.subscriptionsByIntent.get(r);if(!c)return;let d=c.indexOf(o);d>=0&&c.splice(d,1),c.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(e,n,r){let o=typeof e=="string"?e:e.name;se(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Yr(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let s=this.interceptorsByIntent.get(o)??[];return s.push(i),this.interceptorsByIntent.set(o,s),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){ce(this.recording,e)}async recordAudit(e,n,r){await be(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function eo(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}a(eo,"formatStandardSchemaPath");function to(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}a(to,"actualType");function no(t,e){return t?`${t}.${e}`:e}a(no,"formatPath");function un(t,e,n,r,o){let i=to(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(s=>Object.is(s,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}pn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((s,c)=>{un(s,e.items,`${n}[${c}]`,r,o)})}a(un,"validateSchemaField");function pn(t,e,n,r,o){for(let[i,s]of Object.entries(e)){let c=no(o,i),d=t[i];if(d===void 0){s.required&&r.push({intent:n.intent,version:n.version,field:c,message:"Required field is missing."});continue}un(d,s,c,n,r)}}a(pn,"validateObjectSchema");var Se=class{static{a(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(pn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let s of Object.keys(i))r.schema[s]||o.push({intent:e.intent,version:r.version,field:s,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let s=r.standardSchema["~standard"].validate(e.payload);if(s instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(s.issues)for(let c of s.issues)o.push({intent:e.intent,version:r.version,field:eo(c.path),message:c.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(e,n){return`${e}@${n}`}};function rt(){return new Se}a(rt,"createEventContractRegistry");var xe=class{static{a(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
|
|
7
|
+
${n}`),this.name="PolicyViolationError",this.violations=e}};var $=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 Se(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(Se,"definePolicy");function Hr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}s(Hr,"defaultLayerOf");function Wt(t,e){return e.resolveLayer?.(t)??Hr(t)}s(Wt,"resolveLayer");function Ur(t,e,n){return t===n.from&&e===n.to}s(Ur,"matchesRule");function qt(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Se({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=Wt(a.from,t),l=Wt(a.to,t);for(let d of t.rules)!d.allowed&&Ur(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(qt,"defineLayerPolicy");function Xe(t){return t.tags?.includes("layer")??!1}s(Xe,"isLayerPolicy");function Ze(t,e={}){return qt({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}s(Ze,"defineArchitectureProfilePolicy");function Ye(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}s(Ye,"buildPublishPolicyContext");var te=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}},ne=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}},re=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"}},oe=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}},G=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}},ie=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 zt=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function et(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!zt.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${zt.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(et,"validateIntentName");function se(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=et(t);if(!n.valid)throw new ne(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new te(t)}}s(se,"assertIntentAllowed");function Jt(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new G(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new G(t.intent,t.metadata.source)}}s(Jt,"assertSourceAllowed");function ae(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new oe(t.intent,n.issues)}s(ae,"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}s(K,"isPlainRecord");function F(t){return Array.isArray(t)?t.map(F):K(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,F(n)])):t}s(F,"clonePatchValue");function tt(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]=F(i);continue}if(K(r[o])&&K(i)){r[o]=tt(r[o],i,a);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=nt(r[o],i,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}s(tt,"mergeRecordPatch");function nt(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]=F(o);return}if(K(r[i])&&K(o)){r[i]=tt(r[i],o,a);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=nt(r[i],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}s(nt,"mergeArrayPatch");function Qt(t,e){if(Array.isArray(e)){if(t===void 0)return F(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return nt(t,e)}if(t===void 0)return F(e);if(!K(t))throw new Error("Object interceptor patch requires an object payload.");return tt(t,e)}s(Qt,"applyPayloadPatch");async function Xt(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:s(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:Qt(c.payload,l),metadata:{...c.metadata}};ae(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 Vr(o,r,a,e)}}return r}s(Xt,"applyInterceptors");async function Vr(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(Vr,"recordInterceptorError");var Zt=new Map;function Yt(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}s(Yt,"escapeLiteral");function an(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(an,"normalizeGlobSeparators");function Wr(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(Wr,"bracesBalanced");function rt(t){let e=Zt.get(t);if(e)return e;let n=an(t),r=Wr(n),o="",i=0;for(let c=0;c<n.length;c+=1){let l=n[c];l==="\\"&&c+1<n.length?(o+=Yt(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+=Yt(l)}let a=new RegExp(`^${o}$`);return Zt.set(t,a),a}s(rt,"globToRegExp");function cn(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(qr(a)){let c=zr(o,a,r);if(c)return c;continue}!a.includes("/")&&!a.includes("\\")&&!a.includes("*")&&i.add(a.toLowerCase())}return Qr(o,i)}s(cn,"sliceIdForPath");function qr(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}s(qr,"isAnchoredSliceEntry");function zr(t,e,n){let r=e.split(/[/\\]/).filter(i=>i.length>0).map(i=>i.toLowerCase()),o=ln(t,r[0]??"");for(let i of o){let a=Jr(t,r,i,n);if(a)return a}}s(zr,"anchoredSliceId");function Jr(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(Jr,"bindAnchoredSlice");function Qr(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(Qr,"bareSliceId");function Xr(t){let e=new Set;for(let n of t??[]){let o=an(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(Xr,"inferSliceFoldersFromPatterns");function Zr(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 Xr(r?.patterns)}s(Zr,"resolveSliceFolders");function en(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}s(en,"normalizeSegments");function ce(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}s(ce,"trimTrailingSlashes");var Yr=["src","app"];function ln(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return Yr.includes(n)&&r!==n?[0,1]:[0]}s(ln,"anchorOffsets");function eo(t){let e=ce(t.replace(/^[./]+/,""));return e==="*"||e==="**"}s(eo,"isBlanketRoot");function tn(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=en(n);for(let i of e){if(typeof i!="string"||i.length===0||eo(i))continue;if(i.includes("*")){let l=ce(i.toLowerCase());if(rt(l).test(r)||rt(`${l}/**`).test(r))return!0;continue}let a=en(i);if(a.length===0)continue;let c=ln(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(tn,"pathUnderSharedRoot");function nn(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(nn,"sliceMatchesDeclaration");function to(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&nn(r.from,e)&&nn(r.to,n))}s(to,"crossSliceEdgeAllowed");function no(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(no,"peerIsolationDecision");function dn(t){return ce(t.trim().replace(/\\/g,"/")).toLowerCase()}s(dn,"aliasGlobPattern");function ro(t,e){let n=dn(t);if(!n||n==="*"||n==="**")return!1;let r=String(e).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=it(r),i=rt(n);return i.test(r)||o!==r&&i.test(o)}s(ro,"aliasGlobMatches");function oo(t){let e=dn(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(oo,"splitAliasTarget");function io(t,e){for(let n of e.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&ro(n.from,t))return oo(n.to);return null}s(io,"firstSliceAlias");function rn(t,e,n){if(!t)return{};let r=n??e.sliceFolders,o=cn(t,r?[...r]:void 0,e.sliceIdentity),i=ot(t,o,e.childSlices);if(o||i.childId||i.mismatched)return i.childId?{universeId:o,childId:i.childId}:{universeId:o};let a=io(t,e);return a?{universeId:a.universeId,childId:a.childId}:{}}s(rn,"resolveGovernedSlice");function so(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(so,"peerIsolationDenyExplanation");function ao(t,e){return`cross-parent slice ${t??"?"} \u2192 ${e??"?"}. The child wall cannot allow another universe.`}s(ao,"crossParentExplanation");function co(t,e,n){return`cross-sibling slice ${t} \u2192 ${e} inside ${n}.`}s(co,"crossSiblingExplanation");function lo(t){return`universe common imports child ${t}. parentMayImportChild is off.`}s(lo,"parentImportsChildExplanation");function uo(t){return String(t).split(/[/\\]/).filter(Boolean).slice(0,-1)}s(uo,"directorySegments");function fo(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:uo(t).some(r=>n.has(r.toLowerCase()))}s(fo,"pathHasCommonFolder");function ot(t,e,n){if(!t||!n?.sliceFolders?.length)return{};if(fo(t,n.commonFolders))return{};let r=cn(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(ot,"resolveChildSliceId");function po(t){return ce(t.trim().replace(/\\/g,"/")).toLowerCase()}s(po,"siblingEntryKey");function it(t){return t.replace(/^(?:src|app)\//,"")}s(it,"stripSrcOrApp");function go(t,e){let n=t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=it(e);if(!r)return!1;let o=it(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}s(go,"pathUnderSubtree");function mo(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=po(o);if(!(!i||i.includes("*"))&&(r===i||t&&go(t,i)))return!0}return!1}s(mo,"importerInEnforcedSubtree");function ho(t,e,n){return t==null||t==="deny"?!1:t==="advisory"?!0:t.default==="deny"?!1:!mo(e,n,t.enforce)}s(ho,"siblingCrossingAdvisory");function on(t){if(typeof t!="string")return null;let e=ce(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(on,"childSlicePatternSegments");function sn(t,e){let n=on(t),r=on(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(sn,"childSlicePatternMatches");function yo(t,e,n){if(!t?.length)return!1;for(let r of t)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&sn(r.from,e)&&sn(r.to,n))return!0;return!1}s(yo,"childCrossSliceAllowed");function ko(t){let e=no({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?ao(t.fromSlice,t.toSlice):so(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??ot(t.fromPath,t.fromSlice,n).childId,o=t.toChild??ot(t.toPath,t.toSlice,n).childId,i={crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};return r&&o&&r!==o?yo(n.allowedCrossSlice,r,o)?i:{crossing:"cross-sibling",decision:ho(n.siblings,t.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:co(r,o,t.fromSlice),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:lo(o),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:i}s(ko,"evaluateNestedSliceWall");function un(t,e,n,r){return wo(t,e,n,r)?.rule}s(un,"findDeniedEdgeRule");function wo(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=Zr(o,e,r?.layers),l=rn(i,o,c),d=rn(a,o,c),u=l.universeId,m=d.universeId,f=ko({rule:o,fromPath:i,toPath:a,folderCount:c.length,fromSlice:u,toSlice:m,fromChild:l.childId,toChild:d.childId,fromShared:!u&&tn(i,o.sharedRoots),toShared:!m&&tn(a,o.sharedRoots),crossSliceAllowed:to(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(wo,"findDeniedEdgeDecision");async function fn(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=un(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 ie(n,t.intent,o,i,l)}s(fn,"assertObservedLayerFlowAllowed");async function pn(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(pn,"enforcePublishPolicy");function Ao(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(Ao,"appendHistory");function le(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(le,"appendTrace");async function be(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){le(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(be,"recordAudit");async function gn(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."};le(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await be(t,"event.rawPublish",e,n)}s(gn,"recordRawPublishDiagnostic");async function mn(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};return Ao(t,o),await t.eventBuffer?.enqueue(e,r),le(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await be(t,"event.published",e,{subscribersNotified:n}),o}s(mn,"recordSuccessfulPublish");function st(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(st,"enrichMetadata");var hn=0;function Io(){return hn+=1,`interceptor-${Date.now()}-${hn}`}s(Io,"nextInterceptorRegistrationId");var de=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 $(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Xe)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new re;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ye({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:st(f.metadata,g,this.recording.instanceId)}}else{let f=e,g=n,y=r??{},p=f(g);l={...p,metadata:st(p.metadata,y,this.recording.instanceId)}}d&&this.strictRegistry&&await gn(this.recording,l),se(l.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Jt(l,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ae(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),l=await Xt(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")}),ae(l,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await fn(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 pn(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 mn(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 se(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;se(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let 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;se(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Io(),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){le(this.recording,e)}async recordAudit(e,n,r){await be(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function Ro(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(Ro,"formatStandardSchemaPath");function So(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(So,"actualType");function bo(t,e){return t?`${t}.${e}`:e}s(bo,"formatPath");function yn(t,e,n,r,o){let i=So(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}kn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((a,c)=>{yn(a,e.items,`${n}[${c}]`,r,o)})}s(yn,"validateSchemaField");function kn(t,e,n,r,o){for(let[i,a]of Object.entries(e)){let c=bo(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}yn(l,a,c,n,r)}}s(kn,"validateObjectSchema");var Ee=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(kn(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:Ro(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 at(){return new Ee}s(at,"createEventContractRegistry");var ve=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 ot(){return new xe}a(ot,"createDependencyGraph");function it(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}a(it,"syncRegistryToGraph");var le=class{static{a(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=a(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var Rs=new le;function st(){return new le}a(st,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},fn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...D,default:[]},kernelRoots:{...D},managedLayers:{...D,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},gn={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...D,default:[]},managedLayers:{...D,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...D,default:[]},appliesTo:{...D,default:[]}}};var mn="1.3",ro=["public","auth","admin","internal"];var yn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",hn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],oo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function io(){let t=[];for(let e of hn)for(let n of hn)e===n||oo.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}a(io,"createDefaultRules");var at=io();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},js={$schema:"https://json-schema.org/draft/2020-12/schema",$id:yn,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:yn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:mn,default:mn},name:{type:"string",minLength:1},include:{...w,minItems:1,default:["src"]},exclude:{...w,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:at,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...w,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{type:"string",minLength:1},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...w,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...w,minItems:1},exclude:w,intentPrefixes:w,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...ro]},owners:{...w,minItems:1},forbiddenGlobals:w,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...w,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus the star bindings, so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...w,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:{type:"string",enum:["deny"]}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...w,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...w,minItems:1}}},arkRun:fn,arkOrder:gn}};function so(t){return t.endsWith(".")?t:`${t}.`}a(so,"normalizePrefix");function ao(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}a(ao,"byLongestPrefix");function kn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(so)})),n=[...e].sort(ao),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(s=>o.startsWith(s)))?.name}}}a(kn,"createArchitectureProfile");var co=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],ct=kn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:co,rules:at.map(t=>({...t}))});var wn="4.8.21";function uo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(uo,"policyId");var dt=class{constructor(e){this.data=e}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function lt(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,s=t.projections,c=t.eventContracts,d=t.observability,l=e?e.list().map(m=>({name:m.name,dependencies:e.getDependencies(m.name),productions:e.getProductions(m.name)})):[],u=e?e.getAllRelationships():[],y=n?n.getPolicies().map(m=>({id:uo(m.name),name:m.name,severity:m.severity,tags:m.tags?[...m.tags]:void 0,owner:m.owner,version:m.version,rationale:m.rationale,enforcementMode:m.enforcementMode,deprecated:m.deprecated,replacedBy:m.replacedBy,description:m.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],f=r?r.toJSON():[],g=o?o.toJSON():{nodes:[],edges:[]},h=f.filter(m=>(m.emits?.length??0)>0||(m.consumes?.length??0)>0).map(m=>({entity:m.name,emits:m.emits,consumes:m.consumes})),p=s?s.list().map(m=>({name:m.name,sourceIntents:m.sourceIntents,checkpoint:s.getCheckpoint(m.name)})):[],F={schemaVersion:"1.0",version:wn,exportedAt:new Date().toISOString(),intents:l,relationships:u,policies:y,entities:f,graph:g,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:p,eventContracts:c?.list()??[],observability:d?.report(),links:{entityIntents:h}};return new dt(F)}a(lt,"createArkManifest");var Ee=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function ut(){return new Ee}a(ut,"createMetadataRegistry");function pt(t){return`${t.from}->${t.to}`}a(pt,"flowKey");function An(t){let e=new Set,n=[];for(let r of t){let o=pt(r);e.has(o)||(e.add(o),n.push(r))}return n}a(An,"uniqueFlows");function In(t,e){let n=new Set(e.map(pt));return t.filter(r=>!n.has(pt(r)))}a(In,"difference");function ft(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="produces").map(p=>({from:p.from,to:p.to})),s=n?.getHistory().map(p=>({from:p.event.metadata.source,to:p.event.intent}))??[],c=s.length>0||!r?[]:r.getEdges().filter(p=>p.kind==="observed").map(p=>({from:p.from,to:p.to})),d=An([...o,...i]),l=An([...s,...c]),u=l.filter(p=>!p.from||p.from==="unknown"),y=e?Array.from(new Set(l.map(p=>p.from).filter(p=>p&&p!=="unknown"&&!e.has(p)))):[],f=e?Array.from(new Set(l.map(p=>p.to).filter(p=>!e.has(p)))):[],g=new Set(l.flatMap(p=>[p.from,p.to])),h=e?e.list().map(p=>p.name).filter(p=>!g.has(p)):[];return{generatedAt:new Date().toISOString(),declaredProductions:d,observedProductions:l,declaredButUnobserved:In(d,l),observedButUndeclared:In(l.filter(p=>p.from!=="unknown"),d),unknownSources:u,unregisteredObservedSources:y,unregisteredObservedIntents:f,registeredButNeverObserved:h}}}}a(ft,"createObservabilityReporter");var bn=0;function po(){return bn+=1,`outbox-${Date.now()}-${bn}`}a(po,"nextOutboxId");function Sn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}a(Sn,"cloneRecord");var ue=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:po(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Sn(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(Sn)}async clear(){this.records.clear()}};var Pe=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function fo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}a(fo,"initialState");var ve=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Pe,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??fo(r),i=await r.project(e,o);await this.store.save(r.name,i);let s=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(s?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function gt(t){return new ve(t)}a(gt,"createProjectionRegistry");var xn=0;function go(t){return xn+=1,`${t}-${Date.now()}-${xn}`}a(go,"createWorkflowId");function mt(t){return t instanceof Error?t.message:String(t)}a(mt,"errorMessage");function mo(t){return new Promise(e=>{setTimeout(e,t)})}a(mo,"sleep");async function yo(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((s,c)=>{o=setTimeout(()=>{let d=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(d),c(d)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}a(yo,"withTimeout");var Ce=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let s=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||s){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let c=(i.version??0)+1;return i.version=c,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},yt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Ce}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),s={id:r.id??go(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(s,r.tx),await this.audit("workflow.started",s,{workflowName:e}),this.executeSnapshot(s,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=mt(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let s=1;s<=i;s+=1){e.attempts[n.name]=s,await this.store.save(e,r);let c;try{c=await yo(d=>Promise.resolve(n.execute(e.context,this.bus,d)),n.timeoutMs,n.name)}catch(d){if(s<i){o.delayMs&&await mo(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:s,error:mt(d)}),d}c&&Object.assign(e.context,c),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:s});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(s=>e.completedSteps.includes(s.name));for(let s=i.length-1;s>=0;s-=1){let c=i[s];if(c.compensate)try{await Promise.resolve(c.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:c.name})}catch(d){await this.audit("workflow.step.failed",e,{step:c.name,compensation:!0,error:mt(d)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function ht(t,e){return new yt(t,e)}a(ht,"createWorkflowEngine");U();var ho=new Set(["singleton","transient"]);function En(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}a(En,"cloneComponent");function ko(t){if(t===void 0)return"singleton";if(typeof t=="string"&&ho.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(ko,"closedLifetime");function Pn(){let t=new Map,e=new Map,n=new Set;function r(s){let c=t.get(s);if(!c)throw new Error(`ArkRun component "${s}" is not registered.`);return c}a(r,"mustRecord");function o(s,c){if(!c.factory)throw new Error(`ArkRun component "${s}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(s))throw new Error(`ArkRun component "${s}" has a circular resolve.`);n.add(s);try{return c.factory()}finally{n.delete(s)}}a(o,"instantiate");function i(s,c){if(e.has(s))return e.get(s);let d=o(s,c);return e.set(s,d),d}return a(i,"singleton"),{register(s){let c=typeof s?.id=="string"?s.id.trim():"";if(!c)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(c))throw new Error(`ArkRun component "${c}" is already registered.`);let d=ko(s.lifetime),l=Le({id:c,lifetime:d,uses:s.uses,reactsTo:s.reactsTo,raises:s.raises,sends:s.sends,extendedInfo:s.extendedInfo});if(!l)throw new Error("ArkRun component id must be a non-empty string.");let u=typeof s.factory=="function"?s.factory:void 0;return t.set(c,{component:l,factory:u}),En(l)},resolve(s){let c=r(s);return c.component.lifetime==="transient"?o(s,c):i(s,c)},resolveSingleton(s){let c=r(s);if(c.component.lifetime==="transient")throw new Error(`ArkRun component "${s}" is transient; resolveSingleton requires lifetime "singleton".`);return i(s,c)},snapshotComponents(){return[...t.values()].map(s=>En(s.component))}}}a(Pn,"createComponentRegistry");we();async function On(t,e={}){let n=We({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Cn(),vn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}a(On,"startArkRunInspector");me();function Eo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new N(t.source,e.source);return e.source=t.source,e}a(Eo,"stampMetadata");function Po(){}a(Po,"ignoreDetachedFailure");async function kt(t,e,n,r={}){let o=Lt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Eo(r),s=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&t.broker){let c=Promise.resolve(t.broker.send(s));o.awaitHandoff?await c:c.then(void 0,Po)}return o}a(kt,"sendOnArkRunTransport");var vo=1e3,Nn=0;function Co(){return Nn+=1,`ark-kernel-${Date.now()}-${Nn}`}a(Co,"nextKernelInstanceId");function Dn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}a(Dn,"portConstructorId");function Tn(t={}){let e=t.strict??!0,n=t.instanceId??Co(),r=t.profile??ct,o=t.maxHistorySize??vo,i=st(),s=ot(),c=t.metadata??ut(),d=t.auditTrail===void 0,l=t.auditTrail??Je({maxRecords:o}),u=t.eventContracts??rt(),y=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new ue,g=t.projections??gt({auditTrail:l}),h=new $([Xe(r),...t.policies??[]]),p=a(()=>{it(i,s,{requireRegisteredTargets:!0})},"syncGraph"),F=t.ephemeral??!0,m=t.broker,T=new de({intentRegistry:i,dependencyGraph:s,policyEngine:h,strictRegistry:!0,validateIntentNaming:!0,auditTrail:l,eventContracts:u,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:f,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async k=>{await g.apply(k)}}),wt=ht(T,{auditTrail:l}),Ne=ft({registry:i,eventBus:T,graph:s}),M=Pn(),Mn=typeof m?.send=="function",Ln=y?"InMemoryEventBuffer":Dn(f,"EventBufferStore"),_n=d?"InMemoryAuditStore":Dn(l,"AuditTrail"),$n=qe({stores:[Z(Ln,"outbox"),Z(_n,"audit"),Z("InMemoryWorkflowStore","workflow")]}),De={instanceId:n,profile:r,registry:i,graph:s,metadata:c,auditTrail:l,eventContracts:u,eventBuffer:f,outbox:f,projections:g,policyEngine:h,eventBus:T,workflowEngine:wt,observability:Ne,publisher(k){let L=T.createPublisher(k);return{source:L.source,publish:L.publish,send(S,Te,Kn={}){return kt({eventBus:T,broker:m,defaultEphemeral:F},S,Te,{...Kn,source:L.source})}}},send(k,L,S={}){return kt({eventBus:T,broker:m,defaultEphemeral:F},k,L,S)},register(k){return M.register(k)},resolve(k){return M.resolve(k)},resolveSingleton(k){return M.resolveSingleton(k)},getDependencyInformationPackage(){return v({kernelInstanceId:n,components:M.snapshotComponents()})},requestGraph(k){return Mt({kernelInstanceId:n,components:M.snapshotComponents()},k)},getInspectorSnapshot(k){return Bt({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:M.snapshotComponents()},observability:Ne.report(),ephemeralDefault:F,brokerBound:Mn,hardening:$n})},startInspector(k){return On({getInspectorSnapshot:a(S=>De.getInspectorSnapshot(S),"getInspectorSnapshot"),requestGraph:a(S=>De.requestGraph(S),"requestGraph"),async listInspectorOutbox(){let[S,Te]=await Promise.all([f.list("pending"),f.list("failed")]);return Y([...S,...Te],{sampleLimit:A})},async listInspectorWorkflows(){return ee(await wt.list(),{sampleLimit:A})}},k)},syncGraph:p,manifest(){return p(),lt({registry:i,policyEngine:h,metadata:c,graph:s,profile:r,projections:g,eventContracts:u,observability:Ne})}};return De}a(Tn,"createArkKernel");var j=Symbol("ARK_KERNEL"),Oo=a(()=>(0,Oe.Inject)(j),"InjectArk"),x=class{static forRoot(e){let n=e&&"registry"in e?e:Tn(e);return{module:x,global:!0,providers:[{provide:j,useValue:n}],exports:[j]}}static forRootAsync(e){return{module:x,global:!0,providers:[{provide:j,useFactory:e.useFactory,inject:e.inject??[]}],exports:[j]}}};a(x,"ArkModule"),x=bt([(0,Oe.Module)({})],x);0&&(module.exports={ARK_KERNEL,ArkModule,InjectArk});
|
|
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 ct(){return new ve}s(ct,"createDependencyGraph");function lt(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(lt,"syncRegistryToGraph");var ue=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 Bs=new ue;function dt(){return new ue}s(dt,"createIntentRegistry");var D={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},wn={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}}},An={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 In="1.3",Eo=["public","auth","admin","internal"];var Rn="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Sn=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],vo=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function xo(){let t=[];for(let e of Sn)for(let n of Sn)e===n||vo.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}s(xo,"createDefaultRules");var ut=xo();var w={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ca={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Rn,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:Rn,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:In,default:In},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:ut,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:[...Eo]},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:wn,arkOrder:An}};function Po(t){return t.endsWith(".")?t:`${t}.`}s(Po,"normalizePrefix");function Co(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(Co,"byLongestPrefix");function bn(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Po)})),n=[...e].sort(Co),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(bn,"createArchitectureProfile");var Oo=[{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}],ft=bn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Oo,rules:ut.map(t=>({...t}))});var En="4.8.23";function Do(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Do,"policyId");var pt=class{constructor(e){this.data=e}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function gt(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:Do(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)})):[],j={schemaVersion:"1.0",version:En,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 pt(j)}s(gt,"createArkManifest");var xe=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 mt(){return new xe}s(mt,"createMetadataRegistry");function ht(t){return`${t.from}->${t.to}`}s(ht,"flowKey");function xn(t){let e=new Set,n=[];for(let r of t){let o=ht(r);e.has(o)||(e.add(o),n.push(r))}return n}s(xn,"uniqueFlows");function Pn(t,e){let n=new Set(e.map(ht));return t.filter(r=>!n.has(ht(r)))}s(Pn,"difference");function yt(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=xn([...o,...i]),d=xn([...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:Pn(l,d),observedButUndeclared:Pn(d.filter(p=>p.from!=="unknown"),l),unknownSources:u,unregisteredObservedSources:m,unregisteredObservedIntents:f,registeredButNeverObserved:y}}}}s(yt,"createObservabilityReporter");var Cn=0;function Lo(){return Cn+=1,`outbox-${Date.now()}-${Cn}`}s(Lo,"nextOutboxId");function On(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}s(On,"cloneRecord");var fe=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(e){let n=new Date().toISOString(),r={id:Lo(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),On(r)}async markDispatched(e){let n=this.records.get(e);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(e,n){let r=this.records.get(e);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(On)}async clear(){this.records.clear()}};var Pe=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 To(t){return typeof t.initialState=="function"?t.initialState():t.initialState}s(To,"initialState");var Ce=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new Pe,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??To(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 kt(t){return new Ce(t)}s(kt,"createProjectionRegistry");var Nn=0;function _o(t){return Nn+=1,`${t}-${Date.now()}-${Nn}`}s(_o,"createWorkflowId");function wt(t){return t instanceof Error?t.message:String(t)}s(wt,"errorMessage");function Mo(t){return new Promise(e=>{setTimeout(e,t)})}s(Mo,"sleep");async function $o(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($o,"withTimeout");var Oe=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()}},At=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Oe}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??_o(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=wt(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 $o(l=>Promise.resolve(n.execute(e.context,this.bus,l)),n.timeoutMs,n.name)}catch(l){if(a<i){o.delayMs&&await Mo(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:a,error:wt(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:wt(l)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function It(t,e){return new At(t,e)}s(It,"createWorkflowEngine");V();var Go=new Set(["singleton","transient"]);function Dn(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(Dn,"cloneComponent");function Ko(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Go.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(Ko,"closedLifetime");function Ln(){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=Ko(a.lifetime),d=Me({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}),Dn(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=>Dn(a.component))}}}s(Ln,"createComponentRegistry");Ae();async function Mn(t,e={}){let n=qe({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(_n(),Tn));return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}s(Mn,"startArkRunInspector");he();function qo(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(qo,"stampMetadata");function zo(){}s(zo,"ignoreDetachedFailure");async function Rt(t,e,n,r={}){let o=Kt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=qo(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,zo)}return o}s(Rt,"sendOnArkRunTransport");var Jo=1e3,$n=0;function Qo(){return $n+=1,`ark-kernel-${Date.now()}-${$n}`}s(Qo,"nextKernelInstanceId");function Gn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}s(Gn,"portConstructorId");function Kn(t={}){let e=t.strict??!0,n=t.instanceId??Qo(),r=t.profile??ft,o=t.maxHistorySize??Jo,i=dt(),a=ct(),c=t.metadata??mt(),l=t.auditTrail===void 0,d=t.auditTrail??Qe({maxRecords:o}),u=t.eventContracts??at(),m=t.eventBuffer===void 0&&t.outbox===void 0,f=t.eventBuffer??t.outbox??new fe,g=t.projections??kt({auditTrail:d}),y=new $([Ze(r),...t.policies??[]]),p=s(()=>{lt(i,a,{requireRegisteredTargets:!0})},"syncGraph"),j=t.ephemeral??!0,h=t.broker,L=new de({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)}}),St=It(L,{auditTrail:d}),De=yt({registry:i,eventBus:L,graph:a}),T=Ln(),Fn=typeof h?.send=="function",Bn=m?"InMemoryEventBuffer":Gn(f,"EventBufferStore"),jn=l?"InMemoryAuditStore":Gn(d,"AuditTrail"),Hn=ze({stores:[Z(Bn,"outbox"),Z(jn,"audit"),Z("InMemoryWorkflowStore","workflow")]}),Le={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:St,observability:De,publisher(k){let _=L.createPublisher(k);return{source:_.source,publish:_.publish,send(b,Te,Un={}){return Rt({eventBus:L,broker:h,defaultEphemeral:j},b,Te,{...Un,source:_.source})}}},send(k,_,b={}){return Rt({eventBus:L,broker:h,defaultEphemeral:j},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 Gt({kernelInstanceId:n,components:T.snapshotComponents()},k)},getInspectorSnapshot(k){return Ut({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:T.snapshotComponents()},observability:De.report(),ephemeralDefault:j,brokerBound:Fn,hardening:Hn})},startInspector(k){return Mn({getInspectorSnapshot:s(b=>Le.getInspectorSnapshot(b),"getInspectorSnapshot"),requestGraph:s(b=>Le.requestGraph(b),"requestGraph"),async listInspectorOutbox(){let[b,Te]=await Promise.all([f.list("pending"),f.list("failed")]);return Y([...b,...Te],{sampleLimit:I})},async listInspectorWorkflows(){return ee(await St.list(),{sampleLimit:I})}},k)},syncGraph:p,manifest(){return p(),gt({registry:i,policyEngine:y,metadata:c,graph:a,profile:r,projections:g,eventContracts:u,observability:De})}};return Le}s(Kn,"createArkKernel");var B=Symbol("ARK_KERNEL"),Xo=s(()=>(0,Ne.Inject)(B),"InjectArk"),E=class{static forRoot(e){let n=e&&"registry"in e?e:Kn(e);return{module:E,global:!0,providers:[{provide:B,useValue:n}],exports:[B]}}static forRootAsync(e){return{module:E,global:!0,providers:[{provide:B,useFactory:e.useFactory,inject:e.inject??[]}],exports:[B]}}};s(E,"ArkModule"),E=xt([(0,Ne.Module)({})],E);0&&(module.exports={ARK_KERNEL,ArkModule,InjectArk});
|
package/dist/nestjs/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DynamicModule, InjectionToken, OptionalFactoryDependency } from '@nestjs/common';
|
|
2
|
-
import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-
|
|
3
|
-
import '../types-
|
|
4
|
-
import '../configTypes-
|
|
2
|
+
import { A as ArkKernel, C as CreateArkKernelOptions } from '../types-Bdj32QwA.js';
|
|
3
|
+
import '../types-Ik_OakcI.js';
|
|
4
|
+
import '../configTypes-Bbf_MFGe.js';
|
|
5
5
|
|
|
6
6
|
/** Injection token for the Ark kernel instance. */
|
|
7
7
|
declare const ARK_KERNEL: unique symbol;
|