arkgate 4.8.10 → 4.8.13
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 +74 -2
- package/README.md +23 -32
- package/bin/ark-check-runtime.mjs +8 -0
- package/bin/ark-check.mjs +3 -0
- package/bin/lib/adapter-contract-types.mjs +137 -0
- package/bin/lib/adapter-contract.mjs +4 -180
- package/bin/lib/adapter-finding-refs.mjs +63 -0
- package/bin/lib/agent-projection-formatters.mjs +151 -0
- package/bin/lib/agent-projection-merge.mjs +148 -0
- package/bin/lib/agent-projection-types.mjs +42 -0
- package/bin/lib/agent-projection.mjs +3 -309
- package/bin/lib/analysis-engine.mjs +4 -4
- package/bin/lib/ark-order-doctor.mjs +154 -0
- package/bin/lib/ark-order-report.mjs +64 -0
- package/bin/lib/ark-order-sensors.mjs +1 -1
- package/bin/lib/diagnostic-catalog.mjs +2 -2
- package/bin/lib/doctor-advisories.mjs +91 -18
- package/bin/lib/doctor-human.mjs +2 -10
- package/bin/lib/doctor-plan.mjs +4 -3
- package/bin/lib/extra-merge-teeth.mjs +32 -4
- package/bin/lib/html-report-advisories.mjs +2 -0
- package/bin/lib/html-report-depth.mjs +8 -18
- package/bin/lib/html-report.mjs +16 -0
- package/bin/lib/project-root.mjs +70 -4
- package/bin/lib/remediation.mjs +5 -5
- package/bin/lib/rules-under-contract.mjs +14 -0
- package/bin/lib/start-preview.mjs +1 -0
- package/bin/lib/status-command.mjs +28 -0
- package/bin/lib/status-manifest.mjs +23 -0
- package/bin/lib/violations.mjs +10 -1
- package/dist/{diagnosticCatalog-biferT4R.d.ts → diagnosticCatalog-DA565Lja.d.ts} +22 -39
- package/dist/eslint/index.cjs +4 -4
- package/dist/eslint/index.js +4 -4
- package/dist/index.cjs +31 -31
- package/dist/index.d.ts +116 -12
- package/dist/index.js +31 -31
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +15 -15
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +15 -15
- package/docs/README.md +5 -4
- package/docs/agent-guide.md +2 -1
- package/docs/arkorder.md +28 -10
- package/docs/package-surface.md +3 -1
- package/docs/product-voice.md +9 -8
- package/docs/use.md +1 -1
- package/package.json +3 -2
- package/schemas/ark.status-manifest.schema.json +47 -0
- package/server.json +2 -2
package/dist/runtime/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}function od(e,t,n){let r=new Set(e.keys());if(
|
|
1
|
+
var Oo=Object.defineProperty;var s=(e,t)=>Oo(e,"name",{value:t,configurable:!0});var bt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var sa=(e,t)=>{for(var n in t)Oo(e,n,{get:t[n],enumerable:!0})};function so(e,t){return e<t?-1:e>t?1:0}function Uc(e){return[...new Set(e)].sort(so)}function Wt(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return Uc(t)}function Gc(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function Vc(e){return typeof e=="string"&&Hc.has(e)?e:"singleton"}function Ds(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(so)){if(n.length===0)continue;let r=Gc(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function jc(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n={};typeof t.label=="string"&&t.label.length>0&&(n.label=t.label),typeof t.architectureKind=="string"&&t.architectureKind.length>0&&(n.architectureKind=t.architectureKind);let r=Wt(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=Ds(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function ao(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.id=="string"?t.id.trim():"";if(!n)return;let r={id:n,lifetime:Vc(t.lifetime),uses:Wt(t.uses),reactsTo:Wt(t.reactsTo),raises:Wt(t.raises),sends:Wt(t.sends)},o=jc(t.extendedInfo);return o&&(r.extendedInfo=o),r}function Wc(e){return Ds(e)}function lo(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=typeof t.xiHash=="string"?t.xiHash.trim():"";if(!n)return;let r=t.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=t.residual;if(a===null||typeof a!="object"||Array.isArray(a))return;let l=a,c=typeof l.kind=="string"&&Bc.has(l.kind)?l.kind:void 0;if(!c)return;let p={kind:i},g=Wc(o.payload);g&&(p.payload=g);let h={kind:c};return typeof l.reasonCode=="string"&&l.reasonCode.length>0&&(h.reasonCode=l.reasonCode),typeof l.eventId=="string"&&l.eventId.length>0&&(h.eventId=l.eventId),typeof l.target=="string"&&l.target.length>0&&(h.target=l.target),{xiHash:n,event:p,residual:h}}function zc(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=lo(n);r&&t.push(r)}return t}function ke(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let a of n){let l=ao(a);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((a,l)=>so(a.id,l.id));let i=zc(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...i.length>0?{decisionTape:i}:{}}}function Ls(e,t){let n=lo(t),r=e.decisionTape??[],o=n?[...r,n]:[...r];return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components,...o.length>0?{decisionTape:o}:{}}}var Qn,io,Ns,Hc,Bc,mt=bt(()=>{"use strict";Qn="1.0",io=["singleton","transient"],Ns=["absorb","escalate_up","hold"],Hc=new Set(io);s(so,"compare");s(Uc,"uniqueSorted");s(Wt,"nameList");s(Gc,"jsonPrimitive");s(Vc,"closedLifetime");s(Ds,"sanitizeMetadata");s(jc,"sanitizeArkRunExtendedInfo");s(ao,"sanitizeArkRunComponent");Bc=new Set(Ns);s(Wc,"sanitizeTapePayload");s(lo,"sanitizeDecisionTapeRecord");s(zc,"sanitizeDecisionTape");s(ke,"buildDependencyInformationPackage");s(Ls,"appendDecisionTape")});function Yt(e,t){return e<t?-1:e>t?1:0}function po(e){return[...new Set(e)].sort(Yt)}function Ks(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function fo(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function fe(e,t){if(e==null||e==="")return[];if(typeof e=="string")return po(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new Q(t);let n=[];for(let r of e){if(typeof r!="string")throw new Q(t);let o=r.trim();o.length>0&&n.push(o)}return po(n)}function Ws(e,t){if(t==="*")return e.length>0;if(!t.includes("*"))return e===t;let n="^";for(let r of t)r==="*"?n+=".*":/[.*+?^${}()|[\]\\]/.test(r)?n+=`\\${r}`:n+=r;return n+="$",new RegExp(n).test(e)}function zt(e,t){return e?t.some(n=>Ws(e,n)):!1}function zs(e){if(e==null||e==="")return mo;if(typeof e=="string"&&qc.has(e))return e;throw new Q("slice")}function qs(e){if(e==null||e==="")return null;if(typeof e=="string"&&/^(0|[1-9]\d*)$/.test(e))return Number(e);if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;throw new Q("degreesOfSeparation")}function Hs(e,t){if(e==null||e==="")return Ks();if(typeof e=="string"||Array.isArray(e))return{...Ks(),tokens:fe(e,t)};if(typeof e!="object")throw new Q(t);let n=e;for(let r of Object.keys(n))if(!Xc.has(r))throw new Q(t);return{tokens:[],ids:fe(n.ids,t),labels:fe(n.labels,t),tags:fe(n.tags,t),groups:fe(n.groups,t),architectureKinds:fe(n.architectureKinds,t)}}function nr(e={}){if(e==null||e==="")return nr({});if(typeof e!="object"||Array.isArray(e))throw new Q("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!Yc.has(n))throw new Q("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:zs(t.slice),nodeIds:fe(t.nodeIds,"nodeIds"),degreesOfSeparation:qs(t.degreesOfSeparation),include:Hs(t.include,"include"),exclude:Hs(t.exclude,"exclude")}}function rr(e){let t={};e.slice&&(t.slice=zs(e.slice));let n=fe(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=qs(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=fe(e.include??void 0,"include");o.length>0&&(t.include=o);let i=fe(e.exclude??void 0,"exclude");return i.length>0&&(t.exclude=i),t}function Zc(e){let t=[e.id];return e.label&&t.push(e.label),e.group&&t.push(e.group),e.architectureKind&&t.push(e.architectureKind),e.tags&&t.push(...e.tags),t}function Us(e,t){if(!fo(t))return!0;let n=Zc(e);return t.tokens.some(r=>n.some(o=>Ws(o,r)))||zt(e.id,t.ids)||zt(e.label,t.labels)||e.tags?.some(r=>zt(r,t.tags))||zt(e.group,t.groups)?!0:zt(e.architectureKind,t.architectureKinds)}function Jc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return ke({kernelInstanceId:t.kernelInstanceId,components:t.components})}return ke({})}function Qc(e){let t={id:e.id,kind:"component",lifetime:e.lifetime},n=e.extendedInfo;return n?.label&&(t.label=n.label),n?.group&&(t.group=n.group),n?.architectureKind&&(t.architectureKind=n.architectureKind),n?.tags&&n.tags.length>0&&(t.tags=[...n.tags]),t}function er(e){return{id:e,kind:"interaction"}}function qt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function tr(e,t,n,r,o){let i=`${n}\0${o}\0${r}`;t.has(i)||(t.add(i),e.push({from:n,to:r,kind:o}))}function ed(e,t){let n=new Map,r=[],o=new Set;for(let i of e){if(qt(n,Qc(i)),t==="technical"){for(let a of i.uses)qt(n,n.get(a)??er(a)),tr(r,o,i.id,a,"uses");continue}for(let a of i.raises)qt(n,n.get(a)??er(a)),tr(r,o,i.id,a,"raises");for(let a of i.reactsTo)qt(n,n.get(a)??er(a)),tr(r,o,a,i.id,"reactsTo");for(let a of i.sends)qt(n,n.get(a)??er(a)),tr(r,o,i.id,a,"sends")}return{nodes:n,edges:r}}function td(e){let t=new Map,n=s((r,o)=>{let i=t.get(r);i?i.push(o):t.set(r,[o])},"push");for(let r of e)n(r.from,r.to),n(r.to,r.from);return t}function nd(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let i=new Set,a=o.map(l=>({id:l,depth:0}));for(;a.length>0;){let l=a.shift();if(!(!l||i.has(l.id))&&(i.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!i.has(c)&&e.has(c)&&a.push({id:c,depth:l.depth+1})}return i}function Xt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function Gs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function rd(e){let t=new Set,n=new Map;for(let r of e){let o=Xt(r),i=o,a=2;for(;t.has(i);)i=`${o}_${a}`,a+=1;t.add(i),n.set(r,i)}return n}function ho(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=rd(n),o=po(e.nodes.map(l=>l.group).filter(l=>!!l)),i=[`flowchart ${t}`],a=s((l,c)=>{let p=r.get(l.id)??Xt(l.id),g=Gs(l.label??l.id);i.push(`${c}${p}["${g}"]`)},"emitNode");for(let l of o){let c=Xt(`group_${l}`);i.push(` subgraph ${c}["${Gs(l)}"]`);for(let p of e.nodes)p.group===l&&a(p," ");i.push(" end")}for(let l of e.nodes)l.group||a(l," ");for(let l of e.edges){let c=r.get(l.from)??Xt(l.from),p=r.get(l.to)??Xt(l.to);i.push(` ${c} -->|${l.kind}| ${p}`)}return i.join(`
|
|
2
|
+
`)}function od(e,t,n){let r=new Set(e.keys());if(fo(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&Us(c,n.include)}))),fo(n.exclude))for(let l of[...r]){let c=e.get(l);c&&Us(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=nd(r,n.nodeIds,n.degreesOfSeparation,td(o)));let i=[...r].sort(Yt).map(l=>e.get(l)).filter(l=>!!l),a=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Yt(l.from,c.from)||Yt(l.kind,c.kind)||Yt(l.to,c.to));return{nodes:i,edges:a}}function or(e={},t={}){let n=Jc(e),r=nr(t),o=ed(n.components,r.slice),i=od(o.nodes,o.edges,r),a={schemaVersion:go,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:i.nodes,edges:i.edges,mermaid:""};return a.mermaid=ho(a),a}var go,mo,yo,Vs,js,Bs,Q,qc,Yc,Xc,ir=bt(()=>{"use strict";mt();go="1.0",mo="process",yo=["process","technical"],Vs=["component","interaction"],js=["raises","reactsTo","sends"],Bs=["uses"],Q=class extends Error{static{s(this,"InvalidArkRunGraphQueryError")}option;constructor(t,n){super(n??(t==="slice"?'ArkRun graph slice must be "process" or "technical".':t==="degreesOfSeparation"?"ArkRun graph degreesOfSeparation must be a non-negative integer.":`ArkRun graph ${t} is not a closed query.`)),this.name="InvalidArkRunGraphQueryError",this.option=t}},qc=new Set(yo),Yc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),Xc=new Set(["ids","labels","tags","groups","architectureKinds"]);s(Yt,"compare");s(po,"uniqueSorted");s(Ks,"emptyMatch");s(fo,"matchHasCriteria");s(fe,"nameList");s(Ws,"globMatch");s(zt,"anyGlob");s(zs,"closedSlice");s(qs,"closedDegrees");s(Hs,"closedMatch");s(nr,"closeArkRunGraphQuery");s(rr,"arkRunGraphQueryFromSearchParams");s(Zc,"nodeFields");s(Us,"nodeMatches");s(Jc,"asPackage");s(Qc,"componentNode");s(er,"interactionNode");s(qt,"addNode");s(tr,"addEdge");s(ed,"buildSlice");s(td,"adjacency");s(nd,"neighborhood");s(Xt,"mermaidSafeId");s(Gs,"mermaidLabel");s(rd,"uniqueMermaidIds");s(ho,"formatArkRunGraphMermaid");s(od,"filterGraph");s(or,"requestArkRunGraph")});function Ro(e){if(e===void 0)return"local";if(typeof e=="string"&&id.has(e))return e;throw new yt("transport")}function Ao(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new yt("ephemeral")}function sr(e){let t=Ro(e.transport),n=Ao(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",i=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:i,awaitHandoff:n||i}}var Zt,ht,id,yt,Jt=bt(()=>{"use strict";Zt=["local","localBlocking","broker"],ht=!0,id=new Set(Zt),yt=class extends Error{static{s(this,"InvalidArkRunSendOptionError")}option;constructor(t){super(t==="transport"?'ArkRun transport must be "local", "localBlocking", or "broker".':"ArkRun ephemeral must be a boolean."),this.name="InvalidArkRunSendOptionError",this.option=t}};s(Ro,"closedArkRunTransportKind");s(Ao,"closedArkRunEphemeral");s(sr,"resolveArkRunSendPlan")});function lr(e){return e==="production"}function ad(e){let t=e.split(".");if(t.length!==4)return;let n=[];for(let r of t){if(!/^\d{1,3}$/.test(r))return;let o=Number(r);if(o>255)return;n.push(o)}return n}function Ys(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function At(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=Ys(t);if(n)return At(n);let r=ad(t);return r!==void 0&&r[0]===127}function Xs(e){if(e===void 0)return ar;if(typeof e!="string")throw new le(String(e));let t=e.trim();if(sd.has(t.toLowerCase())||!At(t))throw new le(t);let n=t.toLowerCase();if(n==="localhost")return ar;if(n==="[::1]")return"::1";let r=Ys(n);return r?Xs(r):n}function ld(e){if(e===void 0)return Io;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new le(`port:${String(e)}`);return e}function on(e={}){if(lr(e.nodeEnv)||lr(e.processNodeEnv))throw new Rt;return{host:Xs(e.host),port:ld(e.port)}}function Ie(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function cd(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function dd(e){return{kinds:[...Zt],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:Eo}}function xe(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ud(e){let t=xe(e);if(!t||typeof t.id!="string")return;let n=t.status;if(n!=="pending"&&n!=="failed")return;let r=xe(t.event),o=r&&typeof r.intent=="string"?r.intent:typeof t.intent=="string"?t.intent:void 0,i={id:t.id,status:n,attempts:typeof t.attempts=="number"&&Number.isFinite(t.attempts)?t.attempts:0};return o&&(i.intent=o),typeof t.error=="string"&&t.error.length>0&&(i.error=t.error),typeof t.updatedAt=="string"&&(i.updatedAt=t.updatedAt),i}function cr(e){if(typeof e!="number"||!Number.isFinite(e))return re;let t=Math.trunc(e);return t<0?0:t>re?re:t}function Ue(e,t){let n=typeof e=="string"&&e.trim().length>0?e.trim():e&&typeof e=="object"&&"constructor"in e?String(e.constructor?.name??t):t,r=/^InMemory/i.test(n)?"memory":"durable";return{role:t,id:n,kind:r}}function sn(e={}){let t=xe(e),n=xe(t?.durability)??t,r=Array.isArray(n?.stores)?n.stores:Array.isArray(t?.stores)?t.stores:[],o=[];for(let i of r){let a=xe(i);if(!a)continue;let l=a.role;if(l!=="outbox"&&l!=="audit"&&l!=="workflow")continue;let c=typeof a.id=="string"?a.id:typeof a.name=="string"?a.name:void 0;if(!c)continue;let p=a.kind==="memory"||a.kind==="durable"?a.kind:Ue(c,l).kind;o.push({role:l,id:c,kind:p})}return{durability:{stores:o}}}function Ge(e=[],t={}){let n=cr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],i=[];for(let a of r){let l=ud(a);l&&(l.status==="pending"?o.push(l):i.push(l))}return{available:!0,pendingCount:o.length,failedCount:i.length,pending:o.slice(0,n),failed:i.slice(0,n),sampleLimit:n}}function Ke(){return{available:!1,pendingCount:0,failedCount:0,pending:[],failed:[],sampleLimit:re}}function pd(e){let t=xe(e);if(!t||typeof t.id!="string")return;let n=typeof t.workflowName=="string"?t.workflowName:typeof t.name=="string"?t.name:void 0;if(!n)return;let r={id:t.id,name:n,status:typeof t.status=="string"?t.status:"unknown"};return typeof t.currentStep=="string"&&(r.currentStep=t.currentStep),typeof t.error=="string"&&t.error.length>0&&(r.error=t.error),r}function fd(e){return e==="idle"||e==="waiting"}function Ve(e=[],t={}){let n=cr(t.sampleLimit),r=Array.isArray(e)?e:[],o=[],i=0,a=0,l=0,c=0;for(let p of r){let g=pd(p);g&&(o.push(g),g.status==="running"?i+=1:g.status==="compensating"?a+=1:g.status==="failed"?l+=1:fd(g.status)&&(c+=1))}return{available:!0,total:o.length,runningCount:i,compensatingCount:a,failedCount:l,pendingCount:c,workflows:o.slice(0,n),sampleLimit:n}}function He(){return{available:!1,total:0,runningCount:0,compensatingCount:0,failedCount:0,pendingCount:0,workflows:[],sampleLimit:re}}function gd(e){if(e===void 0)return;let t=xe(e);if(!t||t.available===!1)return Ke();let n=cr(t.sampleLimit);if(Array.isArray(t.pending)||Array.isArray(t.failed)||Array.isArray(t.records)){let r=[...Array.isArray(t.pending)?t.pending:[],...Array.isArray(t.failed)?t.failed:[],...Array.isArray(t.records)?t.records:[]],o=Ge(r,{sampleLimit:n}),i=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):o.pendingCount,a=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):o.failedCount;return{...o,pendingCount:i,failedCount:a,sampleLimit:n}}return Ke()}function md(e){if(e===void 0)return;let t=xe(e);if(!t||t.available===!1)return He();let n=cr(t.sampleLimit);if(Array.isArray(t.workflows)){let r=Ve(t.workflows,{sampleLimit:n}),o=typeof t.total=="number"&&Number.isFinite(t.total)?Math.max(0,Math.trunc(t.total)):r.total,i=typeof t.runningCount=="number"&&Number.isFinite(t.runningCount)?Math.max(0,Math.trunc(t.runningCount)):r.runningCount,a=typeof t.compensatingCount=="number"&&Number.isFinite(t.compensatingCount)?Math.max(0,Math.trunc(t.compensatingCount)):r.compensatingCount,l=typeof t.failedCount=="number"&&Number.isFinite(t.failedCount)?Math.max(0,Math.trunc(t.failedCount)):r.failedCount,c=typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.trunc(t.pendingCount)):r.pendingCount;return{...r,total:o,runningCount:i,compensatingCount:a,failedCount:l,pendingCount:c,sampleLimit:n}}return He()}function dr(e={}){let t=on({host:e.host,port:e.port}),n=ke({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]}),r=gd(e.outbox),o=md(e.workflows),i={schemaVersion:ko,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:dd(e),observability:cd(e.observability)??{},hardening:sn(e.hardening)};return r&&(i.outbox=r),o&&(i.workflows=o),i}function an(e){return`event: ${bo}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var go,or,yo,Qt,en,tn,nn,rn,ho,Ro,re,Rt,le,id,ln=bt(()=>{"use strict";gt();Jt();go="1.0",or="127.0.0.1",yo=0,Qt="/snapshot",en="/events",tn="/graph",nn="/outbox",rn="/workflows",ho="snapshot",Ro="in-process-local",re=32,Rt=class extends Error{static{i(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},le=class extends Error{static{i(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},id=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);i(sr,"isArkRunInspectorProductionEnv");i(ad,"ipv4Octets");i(Bi,"unwrapIpv4Mapped");i(At,"isArkRunInspectorLoopbackHost");i(Wi,"closedHost");i(ld,"closedPort");i(on,"resolveArkRunInspectorBind");i(Ie,"arkRunInspectorUrl");i(cd,"jsonClone");i(dd,"closedTransportFacts");i(xe,"asRecord");i(ud,"closedOutboxSummary");i(ir,"closedSampleLimit");i(Ue,"classifyArkRunInspectorStoreDurability");i(sn,"buildArkRunInspectorHardening");i(Ge,"buildArkRunInspectorOutboxMonitor");i(Ke,"unavailableArkRunInspectorOutboxMonitor");i(pd,"closedWorkflowSummary");i(fd,"isPendingWorkflowStatus");i(Ve,"buildArkRunInspectorWorkflowsMonitor");i(He,"unavailableArkRunInspectorWorkflowsMonitor");i(md,"closedOutboxMonitor");i(gd,"closedWorkflowsMonitor");i(ar,"buildArkRunInspectorSnapshot");i(an,"formatArkRunInspectorSseEvent")});var zi={};na(zi,{listenArkRunInspector:()=>bd});function yd(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function hd(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Rd(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Oe(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,yd()),e.end(JSON.stringify(n))}catch{}}function Ad(e,t){let n=e.address();if(n===null||typeof n=="string")throw new le(t.host);if(!At(n.address))throw new le(n.address);return{host:t.host,port:n.port}}async function kd(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ke();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ge([...n??[],...r??[]],{sampleLimit:re})}async function Id(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?He():Ve(await e.workflowEngine.list(),{sampleLimit:re})}async function bd(e,t){let n=await import("http"),r=new Set,o=new Set,s=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=i(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,m)=>{let h=Rd(p.url),u=h.pathname;if(p.method==="GET"&&(u==="/"||u===Qt)){Oe(m,200,l());return}if(p.method==="GET"&&u===tn){try{Oe(m,200,e.requestGraph(er({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(f){if(f instanceof Q){Oe(m,400,{error:f.message,option:f.option});return}throw f}return}if(p.method==="GET"&&u===nn){kd(e).then(f=>Oe(m,200,f)).catch(f=>{Oe(m,500,{error:f instanceof Error?f.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===rn){Id(e).then(f=>Oe(m,200,f)).catch(f=>{Oe(m,500,{error:f instanceof Error?f.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===en){m.writeHead(200,hd()),m.flushHeaders(),m.write(an(l())),r.add(m);let f=s>0?setInterval(()=>{m.write(an(l()))},s):void 0;f&&o.add(f);let g=i(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");p.on("close",g),m.on("close",g);return}Oe(m,404,{error:"not found"})});try{await new Promise((p,m)=>{let h=i(u=>m(u),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{a=Ad(c,t.bind),p()}catch(u){m(u instanceof Error?u:new le(t.bind.host))}})})}catch(p){throw await new Promise(m=>{c.close(()=>m())}),p}return{host:a.host,port:a.port,url:Ie(a.host,a.port,"/"),snapshotUrl:Ie(a.host,a.port,Qt),eventsUrl:Ie(a.host,a.port,en),graphUrl:Ie(a.host,a.port,tn),outboxUrl:Ie(a.host,a.port,nn),workflowsUrl:Ie(a.host,a.port,rn),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,m)=>{c.close(h=>{h?m(h):p()})})}}}var qi=bt(()=>{"use strict";nr();ln();i(yd,"jsonHeaders");i(hd,"sseHeaders");i(Rd,"requestUrl");i(Oe,"writeJson");i(Ad,"boundAddress");i(kd,"resolveOutboxMonitor");i(Id,"resolveWorkflowsMonitor");i(bd,"listenArkRunInspector")});var ur="4.8.10";var ra=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,oa=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,sa=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function ia(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return ra.test(n)?"pure-shared":r==="PersistenceAdapters"&&(oa.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":sa.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}i(ia,"classifyLayerImportKind");function aa(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=ia(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}i(aa,"layerImportNextAction");function la(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}i(la,"arkRunCallSiteName");function ca(e){let t=la(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(ca,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return aa(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return ca(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Do not persist slow key ${e.target} from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again.`:"Do not persist a declared slow key from a use-case. Absorb the field with ingest() or change the pattern with proposeRelease then apply, then preflight again. Never mechanical-safe.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}i(pe,"deterministicNextAction");var fr="1.5",da="docs/diagnostics.md";function x(e){return typeof e=="string"&&e.length>0?e:void 0}i(x,"text");function So(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}i(So,"positiveInteger");function Co(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,s=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",s??""].join("|")}i(Co,"adapterFindingTargetKey");function wo(e){let t=new Map;return e.map(n=>{let r=Co(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}i(wo,"adapterFindingOccurrenceTargetKeys");function ua(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(ua,"adapterFindingRefFromTargetKey");function pa(e){return`${da}#${e}`}i(pa,"adapterDocsCodePath");function fa(e,t,n){return pe({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}i(fa,"nextActionForDiagnostic");function pr(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??Co(e),l=ua(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:So(e.line,1),column:So(e.column,1)},evidence:s,nextAction:x(e.nextAction)??fa(r,s,e),findingRef:l,targetKey:a,docsCodePath:pa(r)}}i(pr,"toAdapterDiagnostic");function ma(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:x(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(h.message)??`Analysis ${t}: required evidence is incomplete.`,...x(h.file)?{file:x(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let s=e.violations??[],a=e.warnings??[],l=wo(s),c=wo(a),p=[...s.map((h,u)=>pr(h,"error",l[u])),...a.map((h,u)=>pr(h,"warning",c[u]))],m={schemaVersion:fr,completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...m,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...h}:{...m,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...m,mode:n,valid:e.valid,completeness:t,...o}:{...m,mode:n,valid:!1,completeness:t,...o}}i(ma,"createAdapterResult");var ga={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:fr},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};var We=class{static{i(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=i(s=>({intent:t,payload:s,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let s of n.dependsOn)this.declareDependency(t,s);if(n?.produces)for(let s of n.produces)this.declareProduction(t,s);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var xo=new We;function Oo(e,t){return xo.define(e,t)}i(Oo,"defineIntent");function pn(){return new We}i(pn,"createIntentRegistry");var Po=xo;var _o=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function fn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!_o.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${_o.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}i(fn,"validateIntentName");var be=class extends Error{static{i(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var ko,ar,Io,Qt,en,tn,nn,rn,bo,Eo,re,Rt,le,sd,ln=bt(()=>{"use strict";mt();Jt();ko="1.0",ar="127.0.0.1",Io=0,Qt="/snapshot",en="/events",tn="/graph",nn="/outbox",rn="/workflows",bo="snapshot",Eo="in-process-local",re=32,Rt=class extends Error{static{s(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},le=class extends Error{static{s(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},sd=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);s(lr,"isArkRunInspectorProductionEnv");s(ad,"ipv4Octets");s(Ys,"unwrapIpv4Mapped");s(At,"isArkRunInspectorLoopbackHost");s(Xs,"closedHost");s(ld,"closedPort");s(on,"resolveArkRunInspectorBind");s(Ie,"arkRunInspectorUrl");s(cd,"jsonClone");s(dd,"closedTransportFacts");s(xe,"asRecord");s(ud,"closedOutboxSummary");s(cr,"closedSampleLimit");s(Ue,"classifyArkRunInspectorStoreDurability");s(sn,"buildArkRunInspectorHardening");s(Ge,"buildArkRunInspectorOutboxMonitor");s(Ke,"unavailableArkRunInspectorOutboxMonitor");s(pd,"closedWorkflowSummary");s(fd,"isPendingWorkflowStatus");s(Ve,"buildArkRunInspectorWorkflowsMonitor");s(He,"unavailableArkRunInspectorWorkflowsMonitor");s(gd,"closedOutboxMonitor");s(md,"closedWorkflowsMonitor");s(dr,"buildArkRunInspectorSnapshot");s(an,"formatArkRunInspectorSseEvent")});var Zs={};sa(Zs,{listenArkRunInspector:()=>bd});function yd(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function hd(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Rd(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Oe(e,t,n){if(!(e.writableEnded||e.destroyed))try{e.writeHead(t,yd()),e.end(JSON.stringify(n))}catch{}}function Ad(e,t){let n=e.address();if(n===null||typeof n=="string")throw new le(t.host);if(!At(n.address))throw new le(n.address);return{host:t.host,port:n.port}}async function kd(e){if(typeof e.listInspectorOutbox=="function")return e.listInspectorOutbox();let t=e.outbox??e.eventBuffer;if(!t||typeof t.list!="function")return Ke();let[n,r]=await Promise.all([t.list("pending"),t.list("failed")]);return Ge([...n??[],...r??[]],{sampleLimit:re})}async function Id(e){return typeof e.listInspectorWorkflows=="function"?e.listInspectorWorkflows():!e.workflowEngine||typeof e.workflowEngine.list!="function"?He():Ve(await e.workflowEngine.list(),{sampleLimit:re})}async function bd(e,t){let n=await import("http"),r=new Set,o=new Set,i=typeof t.sseIntervalMs=="number"&&Number.isFinite(t.sseIntervalMs)?Math.max(0,t.sseIntervalMs):1e3,a=t.bind,l=s(()=>e.getInspectorSnapshot(a),"snapshot"),c=n.createServer((p,g)=>{let h=Rd(p.url),u=h.pathname;if(p.method==="GET"&&(u==="/"||u===Qt)){Oe(g,200,l());return}if(p.method==="GET"&&u===tn){try{Oe(g,200,e.requestGraph(rr({slice:h.searchParams.get("slice"),nodeIds:h.searchParams.get("nodeIds"),degreesOfSeparation:h.searchParams.get("degreesOfSeparation"),include:h.searchParams.get("include"),exclude:h.searchParams.get("exclude")})))}catch(f){if(f instanceof Q){Oe(g,400,{error:f.message,option:f.option});return}throw f}return}if(p.method==="GET"&&u===nn){kd(e).then(f=>Oe(g,200,f)).catch(f=>{Oe(g,500,{error:f instanceof Error?f.message:"outbox monitor failed"})});return}if(p.method==="GET"&&u===rn){Id(e).then(f=>Oe(g,200,f)).catch(f=>{Oe(g,500,{error:f instanceof Error?f.message:"workflows monitor failed"})});return}if(p.method==="GET"&&u===en){g.writeHead(200,hd()),g.flushHeaders(),g.write(an(l())),r.add(g);let f=i>0?setInterval(()=>{g.write(an(l()))},i):void 0;f&&o.add(f);let m=s(()=>{r.delete(g),f&&(clearInterval(f),o.delete(f))},"drop");p.on("close",m),g.on("close",m);return}Oe(g,404,{error:"not found"})});try{await new Promise((p,g)=>{let h=s(u=>g(u),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{a=Ad(c,t.bind),p()}catch(u){g(u instanceof Error?u:new le(t.bind.host))}})})}catch(p){throw await new Promise(g=>{c.close(()=>g())}),p}return{host:a.host,port:a.port,url:Ie(a.host,a.port,"/"),snapshotUrl:Ie(a.host,a.port,Qt),eventsUrl:Ie(a.host,a.port,en),graphUrl:Ie(a.host,a.port,tn),outboxUrl:Ie(a.host,a.port,nn),workflowsUrl:Ie(a.host,a.port,rn),close(){for(let p of o)clearInterval(p);o.clear();for(let p of r)p.end();return r.clear(),new Promise((p,g)=>{c.close(h=>{h?g(h):p()})})}}}var Js=bt(()=>{"use strict";ir();ln();s(yd,"jsonHeaders");s(hd,"sseHeaders");s(Rd,"requestUrl");s(Oe,"writeJson");s(Ad,"boundAddress");s(kd,"resolveOutboxMonitor");s(Id,"resolveWorkflowsMonitor");s(bd,"listenArkRunInspector")});var gr="4.8.13";var aa=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,la=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,ca=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function da(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return aa.test(n)?"pure-shared":r==="PersistenceAdapters"&&(la.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":ca.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}s(da,"classifyLayerImportKind");function ua(e){if(e.typeOnly||e.targetTypeOnlyExports||e.namedBindingsTypeOnly)return"Move the referenced type to a mutually allowed layer, use `import type`, then preflight again.";if(e.peerIsolation)return"Extract the shared dependency to a shared layer, test at the public interface, then preflight again.";let t=da(typeof e.target=="string"?e.target:"",{fromLayer:typeof e.fromLayer=="string"?e.fromLayer:void 0,toLayer:typeof e.toLayer=="string"?e.toLayer:void 0});return t==="pure-shared"?"Adopt the imported constants/types/pure module into DomainModel or SharedKernel (do not inject a port). Then preflight again.":t==="kernel-emit"?"Persistence must not emit. Inject a port or move the event map to SharedTypes; do not import kernel/events/bootstrap from a repository. Then preflight again.":t==="use-case"||e.portProofEligible?`Define a port in ${e.fromLayer??"the source layer"}, inject the ${e.toLayer??"outer-layer"} implementation, test at the public interface, then preflight again.`:"Classify the import: if it is constants/types/pure, adopt into DomainModel or SharedKernel; define a port only if the target is a real use-case. Then preflight again."}s(ua,"layerImportNextAction");function pa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}s(pa,"arkRunCallSiteName");function fa(e){let t=pa(e),n=typeof e.fromLayer=="string"&&e.fromLayer.length>0?e.fromLayer:void 0;switch(e.ruleId){case"ARKRUN_MISSING_ROOT":return t?`Import createStrictArkKernel from arkgate/runtime and call it in composition root ${t} listed in arkRun.compositionRoots, then preflight again.`:"Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKRUN_KERNEL_IN_DOMAIN":return t?`Move the kernel import of ${t} out of ${n??"the Domain-role layer"} into a composition root or adapter. Import from arkgate/runtime, then preflight again.`:"Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe.";case"ARKRUN_DIRECT_NEW":return t?`Resolve ${t} from the kernel instead of constructing it with new, then preflight again.`:"Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision.";case"ARKRUN_UNDECLARED_EMIT":return t?`Add ${t} to raises or sends on the managed component, then preflight again.`:"Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment.";case"ARKRUN_UNDECLARED_HANDLE":return t?`Add ${t} to reactsTo on the managed component, then preflight again.`:"Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment.";case"ARKRUN_UNDECLARED_DEPEND":return t?`Add ${t} to uses on the managed component, then preflight again.`:"Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment.";case"ARKRUN_TRANSPORT_BYPASS":return t?`Send through the ArkRun kernel transport instead of importing ${t}, then preflight again.`:"Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment.";default:return`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}s(fa,"arkRunNextAction");function pe(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return ua(e);case"FORBIDDEN_GLOBAL":return`Inject ${e.target??"the capability"} through a port, test at the public interface, then preflight again.`;case"CAPABILITY_VIOLATION":return`Define a ${String(e.capability??"capability")} port in ${e.fromLayer??"the walled layer"}, bind the implementation outside it, test at the public interface, then preflight again.`;case"CIRCULAR_DEPENDENCY":return"Extract the shared dependency into a third module, test at the public interface, then preflight again.";case"RAW_EVENT_PUBLISH":return"Publish through a registered intent creator, then run Ark again.";case"LITERAL_PATH_DRIFT":return typeof e.target=="string"&&e.target.length>0?`Rewrite the literal to ${e.target}, or run \`arkgate-check --path-drift --base-ref <ref> --write\` to apply every anchored replacement.`:"Rewrite the literal to the rename destination, or run `arkgate-check --path-drift --base-ref <ref> --write` to apply every anchored replacement.";case"LITERAL_PATH_UNRESOLVED":return"Read the candidate and decide: fix the path, or leave it. Advisory \u2014 with no rename to anchor it there is no destination to propose, so --write never touches it.";case"PUBLISH_MISSING_SOURCE":return"Add metadata.source to the publish call, then run Ark again.";case"INVARIANT_COVERAGE_OUTSIDE_ROOTS":return"Move the covering test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json, then run Ark again.";case"ARKRULE_STRUCTURE":case"ARKRULE_INVARIANT":case"INVARIANT_UNCOVERED":return`Fix the structure or invariant for ${typeof e.arkruleId=="string"&&e.arkruleId.length>0?e.arkruleId:"the ArkRule"} (declared in ${typeof e.arkruleSource=="string"&&e.arkruleSource.length>0?e.arkruleSource:"arkrules/<Layer>.json"}), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement.`;case"ARKRUN_MISSING_ROOT":case"ARKRUN_KERNEL_IN_DOMAIN":case"ARKRUN_DIRECT_NEW":case"ARKRUN_UNDECLARED_EMIT":case"ARKRUN_UNDECLARED_HANDLE":case"ARKRUN_UNDECLARED_DEPEND":case"ARKRUN_TRANSPORT_BYPASS":return fa(e);case"ARKORDER_MISSING_PLANE":return typeof e.target=="string"&&e.target.length>0?`Import createOrderPlane from arkgate/order and call it in plane root ${e.target} listed in arkOrder.planeRoots, then preflight again.`:"Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision.";case"ARKORDER_KERNEL_IN_DOMAIN":return"Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe.";case"ARKORDER_GENERIC_UPDATE":return"Don't use a generic update. First freeze with release(). Later, propose the change, then apply it.";case"ARKORDER_TOO_MANY_PARAMS":return"Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe.";case"ARKORDER_INGEST_WRITES_XI":return"Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe.";case"ARKORDER_XI_FIELD_WRITE":return typeof e.target=="string"&&e.target.length>0?`Don't write ${e.target} from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.`:"Don't write a named product choice from a use-case. Take the event in, or change that choice through the valve (proposeRelease then apply), not a generic update.";case"ARKORDER_UNVALVED_RELEASE":return"Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe.";default:return typeof e.ruleId=="string"&&e.ruleId.startsWith("ARKRULE_")?`Fix the ArkRule ${typeof e.arkruleId=="string"?e.arkruleId:e.ruleId}, then preflight again.`:`Resolve ${typeof e.ruleId=="string"&&e.ruleId.length>0?e.ruleId:"ARK_UNKNOWN"} without weakening ark.config.json, then run Ark again.`}}s(pe,"deterministicNextAction");var pn="1.5",mr="docs/diagnostics.md",Po={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.analysis-result.schema.json",title:"ArkGate analysis result",type:"object",additionalProperties:!1,required:["schemaVersion","mode","valid","completeness","completenessReasons","diagnostics"],allOf:[{if:{properties:{completeness:{enum:["partial","unavailable"]}},required:["completeness"]},then:{properties:{valid:{const:!1}}}},{if:{properties:{mode:{const:"resolved-candidate-facts"},completeness:{enum:["complete","partial"]}},required:["mode","completeness"]},then:{required:["policyHash","resolverIdentity","factsHash","candidateTreeHash"]}},{if:{properties:{completeness:{const:"complete"}},required:["completeness"]},then:{properties:{completenessReasons:{maxItems:0}}},else:{properties:{completenessReasons:{minItems:1}}}}],properties:{schemaVersion:{const:"1.5"},mode:{enum:["lexical-compatibility","resolved-candidate-facts"]},valid:{type:"boolean"},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:{type:"string",minLength:1},message:{type:"string",minLength:1},file:{type:"string",minLength:1}}}},policyHash:{type:"string",minLength:1},resolverIdentity:{type:"string",minLength:1},factsHash:{type:"string",minLength:1},candidateTreeHash:{type:"string",minLength:1},diagnostics:{type:"array",items:{type:"object",additionalProperties:!1,required:["ruleId","severity","message","location","evidence"],properties:{ruleId:{type:"string",minLength:1},severity:{enum:["error","warning"]},message:{type:"string",minLength:1},location:{type:"object",additionalProperties:!1,required:["file","line","column"],properties:{file:{type:"string",minLength:1},line:{type:"integer",minimum:1},column:{type:"integer",minimum:1}}},evidence:{type:"object",additionalProperties:!1,properties:{target:{type:"string"},fromLayer:{type:"string"},toLayer:{type:"string"},typeOnly:{type:"boolean"},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"},peerIsolation:{type:"boolean"},capability:{type:"string",minLength:1},edgeKind:{type:"string",minLength:1},arkruleId:{type:"string",minLength:1},arkruleSource:{type:"string",minLength:1}}},nextAction:{type:"string",minLength:1},findingRef:{type:"string",minLength:1,pattern:"^fnv1a-[0-9a-f]{8}$"},targetKey:{type:"string",minLength:1},docsCodePath:{type:"string",minLength:1}}}}}};function fn(e){let t=typeof e.ruleId=="string"?e.ruleId:typeof e.code=="string"?e.code:void 0,n=typeof e.file=="string"?e.file:void 0,r=typeof e.fromLayer=="string"?e.fromLayer:void 0,o=typeof e.toLayer=="string"?e.toLayer:void 0,i=typeof e.target=="string"?e.target:void 0;return[t,n,r??"",o??"",i??""].join("|")}s(fn,"adapterFindingTargetKey");function gn(e){let t=new Map;return e.map(n=>{let r=fn(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}s(gn,"adapterFindingOccurrenceTargetKeys");function yr(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}s(yr,"adapterFindingRefFromTargetKey");function hr(e){return`${mr}#${e}`}s(hr,"adapterDocsCodePath");function x(e){return typeof e=="string"&&e.length>0?e:void 0}s(x,"text");function _o(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}s(_o,"positiveInteger");function ga(e,t,n){return pe({ruleId:e,target:x(t.target)??x(n.target)??void 0,fromLayer:x(t.fromLayer)??void 0,toLayer:x(t.toLayer)??void 0,typeOnly:t.typeOnly===!0,targetTypeOnlyExports:t.targetTypeOnlyExports===!0,namedBindingsTypeOnly:t.namedBindingsTypeOnly===!0,portProofEligible:t.portProofEligible===!0,peerIsolation:t.peerIsolation===!0,sourcePureTypeModule:t.sourcePureTypeModule===!0,edgeKind:x(t.edgeKind)??void 0,capability:x(t.capability)??x(n.capability)??void 0,arkruleId:x(t.arkruleId)??void 0,arkruleSource:x(t.arkruleSource)??void 0})}s(ga,"nextActionForDiagnostic");function Rr(e,t="error",n){let r=x(e.ruleId)??x(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,i={...x(e.target)?{target:x(e.target)}:{},...x(e.fromLayer)?{fromLayer:x(e.fromLayer)}:{},...x(e.toLayer)?{toLayer:x(e.toLayer)}:{},...typeof e.typeOnly=="boolean"?{typeOnly:e.typeOnly}:{},...typeof e.targetTypeOnlyExports=="boolean"?{targetTypeOnlyExports:e.targetTypeOnlyExports}:{},...typeof e.sourcePureTypeModule=="boolean"?{sourcePureTypeModule:e.sourcePureTypeModule}:{},...typeof e.namedBindingsTypeOnly=="boolean"?{namedBindingsTypeOnly:e.namedBindingsTypeOnly}:{},...typeof e.portProofEligible=="boolean"?{portProofEligible:e.portProofEligible}:{},...typeof e.peerIsolation=="boolean"?{peerIsolation:e.peerIsolation}:{},...x(e.capability)?{capability:x(e.capability)}:{},...x(e.edgeKind)?{edgeKind:x(e.edgeKind)}:{},...x(e.arkruleId)?{arkruleId:x(e.arkruleId)}:{},...x(e.arkruleSource)?{arkruleSource:x(e.arkruleSource)}:{}},a=n??fn(e),l=yr(a);return{ruleId:r,severity:o,message:x(e.message)??r,location:{file:x(e.file)??"<unknown>",line:_o(e.line,1),column:_o(e.column,1)},evidence:i,nextAction:x(e.nextAction)??ga(r,i,e),findingRef:l,targetKey:a,docsCodePath:hr(r)}}s(Rr,"toAdapterDiagnostic");function ma(e){let t=e.completeness??"complete",n=e.mode??"lexical-compatibility";if(t==="complete"&&(e.completenessReasons?.length??0)>0)throw new Error("completenessReasons must be empty when completeness is complete.");let r=t==="complete"?[]:e.completenessReasons&&e.completenessReasons.length>0?e.completenessReasons.map(h=>({code:x(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:x(h.message)??`Analysis ${t}: required evidence is incomplete.`,...x(h.file)?{file:x(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...x(e.policyHash)?{policyHash:x(e.policyHash)}:{},...x(e.resolverIdentity)?{resolverIdentity:x(e.resolverIdentity)}:{},...x(e.factsHash)?{factsHash:x(e.factsHash)}:{},...x(e.candidateTreeHash)?{candidateTreeHash:x(e.candidateTreeHash)}:{}};if(n==="resolved-candidate-facts"&&t!=="unavailable"){for(let h of["policyHash","resolverIdentity","factsHash","candidateTreeHash"])if(!o[h])throw new Error(`${h} is required for resolved ${t} adapter evidence.`)}let i=e.violations??[],a=e.warnings??[],l=gn(i),c=gn(a),p=[...i.map((h,u)=>Rr(h,"error",l[u])),...a.map((h,u)=>Rr(h,"warning",c[u]))],g={schemaVersion:"1.5",completenessReasons:r,diagnostics:p};if(n==="resolved-candidate-facts"){if(t==="unavailable")return{...g,mode:n,valid:!1,completeness:t,...o};let h={policyHash:o.policyHash,resolverIdentity:o.resolverIdentity,factsHash:o.factsHash,candidateTreeHash:o.candidateTreeHash};return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...h}:{...g,mode:n,valid:!1,completeness:t,...h}}return t==="complete"?{...g,mode:n,valid:e.valid,completeness:t,...o}:{...g,mode:n,valid:!1,completeness:t,...o}}s(ma,"createAdapterResult");var We=class{static{s(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(t,n){if(this.intents.has(t))throw new Error(`Intent "${t}" is already registered. Intent names must be unique within a registry.`);let r=s(i=>({intent:t,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:t,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(t,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(t,i);if(n?.produces)for(let i of n.produces)this.declareProduction(t,i);return o}declareDependency(t,n){this.dependencies.has(t)||this.dependencies.set(t,new Set),this.dependencies.get(t).add(n)}declareProduction(t,n){this.productions.has(t)||this.productions.set(t,new Set),this.productions.get(t).add(n)}get(t){return this.intents.get(t)}list(){return Array.from(this.intents.values())}getDependencies(t){let n=this.dependencies.get(t);return n?Array.from(n):[]}getProductions(t){let n=this.productions.get(t);return n?Array.from(n):[]}getAllRelationships(){let t=[];for(let[n,r]of this.dependencies.entries())for(let o of r)t.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)t.push({from:n,to:o,kind:"produces"});return t}has(t){return this.intents.has(t)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var To=new We;function No(e,t){return To.define(e,t)}s(No,"defineIntent");function mn(){return new We}s(mn,"createIntentRegistry");var Do=To;var Lo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function yn(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!Lo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${Lo.join(", ")}`};let t=e.slice(e.indexOf(".")+1);return!t||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(t)?{valid:!1,reason:`Intent "${e}" has an invalid segment after the layer prefix`}:{valid:!0}}s(yn,"validateIntentName");var be=class extends Error{static{s(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
6
6
|
`);super(`Hard policy violation(s) detected:
|
|
7
|
-
${n}`),this.name="PolicyViolationError",this.violations=t}};var _e=class{static{i(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let s of this.policies){let a=s.check(t);if(a!==!0){if(a===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(a))for(let l of a)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:a.message,details:a.details})}}let r=n.filter(s=>s.severity==="hard"),o=n.filter(s=>s.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new be(n.hardViolations);return n}clear(){this.policies.length=0}};function ze(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}i(ze,"definePolicy");function ya(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}i(ya,"defaultLayerOf");function No(e,t){return t.resolveLayer?.(e)??ya(e)}i(No,"resolveLayer");function ha(e,t,n){return e===n.from&&t===n.to}i(ha,"matchesRule");function mn(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return ze({name:t,severity:n,tags:["layer"],check:i(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}))],s=[];for(let a of o){let l=No(a.from,e),c=No(a.to,e);for(let p of e.rules)!p.allowed&&ha(l,c,p)&&s.push({policyName:t,severity:n,message:p.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return s.length>0?s:!0},"check")})}i(mn,"defineLayerPolicy");function gn(e){return e.tags?.includes("layer")??!1}i(gn,"isLayerPolicy");var mr={layerIsolation(){return mr.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return mn({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function yn(e,t={}){return mn({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}i(yn,"defineArchitectureProfilePolicy");function hn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}i(hn,"buildPublishPolicyContext");function To(e){return ze(e)}i(To,"definePublishPolicy");var qe=class extends Error{static{i(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ye=class extends Error{static{i(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Xe=class extends Error{static{i(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"}},Ze=class extends Error{static{i(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Ne=class extends Error{static{i(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},Ee=class extends Error{static{i(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Je=class extends Error{static{i(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,s){super(s??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Et(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=fn(e);if(!n.valid)throw new Ye(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new qe(e)}}i(Et,"assertIntentAllowed");function Do(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Ne(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Ne(e.intent,e.metadata.source)}}i(Do,"assertSourceAllowed");function vt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Ze(e.intent,n.issues)}i(vt,"assertContractAllowed");function Qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Qe,"isPlainRecord");function et(e){return Array.isArray(e)?e.map(et):Qe(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,et(n)])):e}i(et,"clonePatchValue");function gr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=et(s);continue}if(Qe(r[o])&&Qe(s)){r[o]=gr(r[o],s,a);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=yr(r[o],s,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}i(gr,"mergeRecordPatch");function yr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let a=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=et(o);return}if(Qe(r[s])&&Qe(o)){r[s]=gr(r[s],o,a);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=yr(r[s],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}i(yr,"mergeArrayPatch");function Lo(e,t){if(Array.isArray(t)){if(e===void 0)return et(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return yr(e,t)}if(e===void 0)return et(t);if(!Qe(e))throw new Error("Object interceptor patch requires an object payload.");return gr(e,t)}i(Lo,"applyPayloadPatch");async function Fo(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let s=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:i(c=>{s.push(c)},"intercept")})),s.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of s)l={...l,payload:Lo(l.payload,c),metadata:{...l.metadata}};vt(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.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:s.length}}),await t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:s.length})}catch(a){await Ra(o,r,a,t)}}return r}i(Fo,"applyInterceptors");async function Ra(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}i(Ra,"recordInterceptorError");var $o=new Map;function Mo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Mo,"escapeLiteral");function Rn(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(Rn,"normalizeGlobSeparators");function Aa(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(Aa,"bracesBalanced");function ge(e){let t=$o.get(e);if(t)return t;let n=Rn(e),r=Aa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Mo(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=Mo(c)}let a=new RegExp(`^${o}$`);return $o.set(e,a),a}i(ge,"globToRegExp");function ka(e){return Rn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}i(ka,"concreteGlobSegments");function hr(e,t){let n=Rn(String(e)),r=ka(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let p of r){let m=-1;for(let h=l;h<a.length;h+=1)if(a[h]===p){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}i(hr,"patternSpecificity");function ce(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(a=>ge(a).test(n))){for(let a of s.patterns??[])if(ge(a).test(n)){let l=hr(a,n);l>o&&(o=l,r=s.name)}}return r}i(ce,"layerForRelativePath");function Ko(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}i(Ko,"sliceIdForPath");function Ia(e){let t=new Set;for(let n of e??[]){let o=Rn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let a=o[s];if((a==="**"||a==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}i(Ia,"inferSliceFoldersFromPatterns");function ba(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return Ia(r?.patterns)}i(ba,"resolveSliceFolders");function Ho(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}i(Ho,"normalizeSegments");function Vo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}i(Vo,"trimTrailingSlashes");var Ea=["src","app"];function va(e){let t=Vo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}i(va,"isBlanketRoot");function Uo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Ho(n);for(let s of t){if(typeof s!="string"||s.length===0||va(s))continue;if(s.includes("*")){let c=Vo(s.toLowerCase());if(ge(c).test(r)||ge(`${c}/**`).test(r))return!0;continue}let a=Ho(s);if(a.length===0)continue;let l=Ea.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let p=!0;for(let m=0;m<a.length;m+=1)if(o[c+m]!==a[m]){p=!1;break}if(p)return!0}}return!1}i(Uo,"pathUnderSharedRoot");function Go(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}i(Go,"sliceMatchesDeclaration");function Sa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Go(r.from,t)&&Go(r.to,n))}i(Sa,"crossSliceEdgeAllowed");function wa(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}i(wa,"peerIsolationDecision");function tt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.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."}}i(tt,"peerIsolationDenyExplanation");function nt(e,t,n,r){return Te(e,t,n,r)?.rule}i(nt,"findDeniedEdgeRule");function Te(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let s=r?.fromPath,a=r?.toPath,l=ba(o,t,r?.layers),c=s?Ko(s,l):void 0,p=a?Ko(a,l):void 0,m=wa({fromPath:s,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Uo(s,o.sharedRoots),toShared:!p&&Uo(a,o.sharedRoots),crossSliceAllowed:Sa(o.allowedCrossSlice,c,p)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:o}}}i(Te,"findDeniedEdgeDecision");async function jo(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),s=r.resolveLayer(e.intent);if(!o||!s)return;let a=nt(r.rules,o,s);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,p={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:p}),await t.recordAudit("layer.observedViolation",e,p),l==="hard")throw new Je(n,e.intent,o,s,c)}i(jo,"assertObservedLayerFlowAllowed");async function Bo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof be&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}i(Bo,"enforcePublishPolicy");function Ca(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}i(Ca,"appendHistory");function St(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}i(St,"appendTrace");async function An(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){St(e,{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)}})}}i(An,"recordAudit");async function Wo(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};St(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await An(e,"event.rawPublish",t,n)}i(Wo,"recordRawPublishDiagnostic");async function zo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Ca(e,o),await e.eventBuffer?.enqueue(t,r),St(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await An(e,"event.published",t,{subscribersNotified:n}),o}i(zo,"recordSuccessfulPublish");function Rr(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}i(Rr,"enrichMetadata");var qo=0;function xa(){return qo+=1,`interceptor-${Date.now()}-${qo}`}i(xa,"nextInterceptorRegistrationId");var rt=class{static{i(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(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new _e(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(gn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Xe;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=hn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let s=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,p=typeof t!="function";if(p){let u=t,f=r??n??{};c={...u,metadata:Rr(u.metadata,f,this.recording.instanceId)}}else{let u=t,f=n,g=r??{},y=u(f);c={...y,metadata:Rr(y.metadata,g,this.recording.instanceId)}}p&&this.strictRegistry&&await Wo(this.recording,c),Et(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Do(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),vt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Fo(c,{interceptorsForIntent:i(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,f,g)=>this.recordAudit(u,f,g),"recordAudit")}),vt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await jo(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,f,g)=>this.recordAudit(u,f,g),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let m=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Bo(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:i(u=>this.appendTrace(u),"appendTrace"),recordAudit:i((u,f,g)=>this.recordAudit(u,f,g),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:i((u,f,g)=>this.safeHook(u,f,g),"safeHook")}),await zo(this.recording,c,s?m.length:0,o.tx);let h=(async()=>{s&&await Promise.all(m.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Et(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:i(async(r,o,s={},a)=>{if(s.source&&s.source!==n)throw new Ee(n,s.source);await this.publish(r,o,{...s,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Et(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let s=this.subscriptionsByIntent.get(r)??[];return s.push(o),this.subscriptionsByIntent.set(r,s),()=>{let a=this.subscriptions.indexOf(o);a>=0&&this.subscriptions.splice(a,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Et(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:xa(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let a=this.interceptorsByIntent.get(o)??[];return a.push(s),this.interceptorsByIntent.set(o,a),s.registrationId}unregisterInterceptor(t){let n=this.interceptors.find(s=>s.registrationId===t);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 s=o.indexOf(n);s>=0&&o.splice(s,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(t){return this.interceptors.filter(n=>!t||n.intentName===t).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(t){St(this.recording,t)}async recordAudit(t,n,r){await An(this.recording,t,n,r)}async invokeHandler(t,n){try{await Promise.resolve(t.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:t.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,t.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(t,n,r){try{await Promise.resolve(t())}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 Yo(e){return new rt(e)}i(Yo,"createEventBus");function Oa(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}i(Oa,"formatStandardSchemaPath");function Pa(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}i(Pa,"actualType");function _a(e,t){return e?`${e}.${t}`:t}i(_a,"formatPath");function Xo(e,t,n,r,o){let s=Pa(e);if(t.type!=="unknown"&&s!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${s}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Zo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{Xo(a,t.items,`${n}[${l}]`,r,o)})}i(Xo,"validateSchemaField");function Zo(e,t,n,r,o){for(let[s,a]of Object.entries(t)){let l=_a(o,s),c=e[s];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Xo(c,a,l,n,r)}}i(Zo,"validateObjectSchema");var wt=class{static{i(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let s=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!s)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Zo(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(s))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:Oa(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function kn(){return new wt}i(kn,"createEventContractRegistry");var Jo=0;function Na(){return Jo+=1,`outbox-${Date.now()}-${Jo}`}i(Na,"nextOutboxId");function Qo(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}i(Qo,"cloneRecord");var De=class{static{i(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Na(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Qo(r)}async markDispatched(t){let n=this.records.get(t);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(t,n){let r=this.records.get(t);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(t){return Array.from(this.records.values()).filter(n=>!t||n.status===t).map(Qo)}async clear(){this.records.clear()}},es=De;function Ar(e){return`${e.from}->${e.to}`}i(Ar,"flowKey");function ts(e){let t=new Set,n=[];for(let r of e){let o=Ar(r);t.has(o)||(t.add(o),n.push(r))}return n}i(ts,"uniqueFlows");function ns(e,t){let n=new Set(t.map(Ar));return e.filter(r=>!n.has(Ar(r)))}i(ns,"difference");function In(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})):[],s=o.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})),a=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=ts([...o,...s]),p=ts([...a,...l]),m=p.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(p.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],u=t?Array.from(new Set(p.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(p.flatMap(y=>[y.from,y.to])),g=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:p,declaredButUnobserved:ns(c,p),observedButUndeclared:ns(p.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:u,registeredButNeverObserved:g}}}}i(In,"createObservabilityReporter");function rs(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}i(rs,"createArkTestHarness");var os=0;function Ta(){return os+=1,`audit-${Date.now()}-${os}`}i(Ta,"createAuditId");function Da(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}i(Da,"matchesQuery");var Ct=class{constructor(t){this.maxRecords=t}maxRecords;static{i(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Da(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},bn=class{constructor(t){this.store=t}store;static{i(this,"AuditTrailImpl")}async record(t){let n={id:Ta(),timestamp:t.timestamp??new Date().toISOString(),type:t.type,source:t.source,actor:t.actor,intent:t.intent,correlationId:t.correlationId,causationId:t.causationId,subject:t.subject,details:t.details};return await this.store.append(n),n}async query(t){return this.store.query(t)}async clear(){await this.store.clear()}};function En(e={}){return new bn(e.store??new Ct(e.maxRecords))}i(En,"createAuditTrail");var vn=class{static{i(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,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 t=`flowchart TD
|
|
7
|
+
${n}`),this.name="PolicyViolationError",this.violations=t}};var _e=class{static{s(this,"PolicyEngine")}policies=[];constructor(t=[]){for(let n of t)this.add(n)}add(t){if(this.policies.some(n=>n.name===t.name))throw new Error(`Policy "${t.name}" is already registered in this engine.`);this.policies.push(t)}getPolicies(){return[...this.policies]}evaluate(t){let n=[];for(let i of this.policies){let a=i.check(t);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 l of a)n.push({policyName:i.name,severity:i.severity,message:l.message,details:l.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(t){let n=this.evaluate(t);if(n.hardViolations.length>0)throw new be(n.hardViolations);return n}clear(){this.policies.length=0}};function ze(e){let t=e.severity??"soft";return{name:e.name,severity:t,tags:e.tags,owner:e.owner,version:e.version,rationale:e.rationale,enforcementMode:e.enforcementMode,deprecated:e.deprecated,replacedBy:e.replacedBy,check:e.check}}s(ze,"definePolicy");function ya(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}s(ya,"defaultLayerOf");function Fo(e,t){return t.resolveLayer?.(e)??ya(e)}s(Fo,"resolveLayer");function ha(e,t,n){return e===n.from&&t===n.to}s(ha,"matchesRule");function hn(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return ze({name:t,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 l=Fo(a.from,e),c=Fo(a.to,e);for(let p of e.rules)!p.allowed&&ha(l,c,p)&&i.push({policyName:t,severity:n,message:p.message??`Layer violation: ${a.from} (${l}) must not relate to ${a.to} (${c})`})}return i.length>0?i:!0},"check")})}s(hn,"defineLayerPolicy");function Rn(e){return e.tags?.includes("layer")??!1}s(Rn,"isLayerPolicy");var Ar={layerIsolation(){return Ar.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return hn({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function An(e,t={}){return hn({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}s(An,"defineArchitectureProfilePolicy");function kn(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}s(kn,"buildPublishPolicyContext");function Mo(e){return ze(e)}s(Mo,"definePublishPolicy");var qe=class extends Error{static{s(this,"UnregisteredIntentError")}intentName;constructor(t){super(`Intent "${t}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=t}},Ye=class extends Error{static{s(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},Xe=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"}},Ze=class extends Error{static{s(this,"EventContractViolationError")}intentName;issues;constructor(t,n){super(`Event contract violation for "${t}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=t,this.issues=n}},Te=class extends Error{static{s(this,"UnknownEventSourceError")}intentName;source;constructor(t,n){super(n?`Event "${t}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${t}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=t,this.source=n}},Ee=class extends Error{static{s(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(t,n){super(`Source-bound publisher for "${t}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=t,this.attemptedSource=n}},Je=class extends Error{static{s(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(t,n,r,o,i){super(i??`Observed layer violation: "${t}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=t,this.intentName=n,this.fromLayer=r,this.toLayer=o}};function Et(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=yn(e);if(!n.valid)throw new Ye(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new qe(e)}}s(Et,"assertIntentAllowed");function $o(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Te(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Te(e.intent,e.metadata.source)}}s($o,"assertSourceAllowed");function vt(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Ze(e.intent,n.issues)}s(vt,"assertContractAllowed");function Qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}s(Qe,"isPlainRecord");function et(e){return Array.isArray(e)?e.map(et):Qe(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,et(n)])):e}s(et,"clonePatchValue");function kr(e,t,n="payload"){let r={...e};for(let[o,i]of Object.entries(t)){let a=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=et(i);continue}if(Qe(r[o])&&Qe(i)){r[o]=kr(r[o],i,a);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=Ir(r[o],i,a);continue}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}return r}s(kr,"mergeRecordPatch");function Ir(e,t,n="payload"){let r=[...e];return t.forEach((o,i)=>{let a=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=et(o);return}if(Qe(r[i])&&Qe(o)){r[i]=kr(r[i],o,a);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=Ir(r[i],o,a);return}throw new Error(`Interceptor patch cannot overwrite existing ${a}.`)}),r}s(Ir,"mergeArrayPatch");function Ko(e,t){if(Array.isArray(t)){if(e===void 0)return et(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return Ir(e,t)}if(e===void 0)return et(t);if(!Qe(e))throw new Error("Object interceptor patch requires an object payload.");return kr(e,t)}s(Ko,"applyPayloadPatch");async function Ho(e,t){if(e.metadata.allowInterception===!1)return e;let n=[...t.interceptorsForIntent(e.intent)],r=e;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:s(c=>{i.push(c)},"intercept")})),i.length===0)continue;let a=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:a}]}};for(let c of i)l={...l,payload:Ko(l.payload,c),metadata:{...l.metadata}};vt(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=a,t.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 t.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(a){await Ra(o,r,a,t)}}return r}s(Ho,"applyInterceptors");async function Ra(e,t,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o}}),await r.recordAudit("interceptor.error",t,{registrationId:e.registrationId,interceptorId:e.interceptorId,error:o})}s(Ra,"recordInterceptorError");var Uo=new Map;function Go(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}s(Go,"escapeLiteral");function In(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}s(In,"normalizeGlobSeparators");function Aa(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}s(Aa,"bracesBalanced");function me(e){let t=Uo.get(e);if(t)return t;let n=In(e),r=Aa(n),o="",i=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Go(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",i+=1):c==="}"&&r&&i>0?(o+=")",i-=1):c===","&&r&&i>0?o+="|":o+=Go(c)}let a=new RegExp(`^${o}$`);return Uo.set(e,a),a}s(me,"globToRegExp");function ka(e){return In(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}s(ka,"concreteGlobSegments");function br(e,t){let n=In(String(e)),r=ka(n),o=n.replace(/\*/g,"").length,i=r.length*1e4+o;if(t==null||t==="")return i;let a=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let p of r){let g=-1;for(let h=l;h<a.length;h+=1)if(a[h]===p){g=h;break}if(g<0)return i;c=g,l=g+1}return(c+1)*1e6+r.length*1e4+o}s(br,"patternSpecificity");function ce(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let i of t??[])if(!(i.exclude??[]).some(a=>me(a).test(n))){for(let a of i.patterns??[])if(me(a).test(n)){let l=br(a,n);l>o&&(o=l,r=i.name)}}return r}s(ce,"layerForRelativePath");function Vo(e,t){if(!t?.length)return;let n=String(e).split(/[/\\]/).filter(Boolean),r=new Set(t.map(o=>String(o).toLowerCase()));for(let o=0;o<n.length-1;o+=1)if(r.has(n[o].toLowerCase()))return`${n[o].toLowerCase()}/${n[o+1].toLowerCase()}`}s(Vo,"sliceIdForPath");function Ia(e){let t=new Set;for(let n of e??[]){let o=In(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let a=o[i];if((a==="**"||a==="*")&&i>0){let l=o[i-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}s(Ia,"inferSliceFoldersFromPatterns");function ba(e,t,n){if(Array.isArray(e.sliceFolders)&&e.sliceFolders.length>0)return e.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===t);return Ia(r?.patterns)}s(ba,"resolveSliceFolders");function jo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}s(jo,"normalizeSegments");function zo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}s(zo,"trimTrailingSlashes");var Ea=["src","app"];function va(e){let t=zo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}s(va,"isBlanketRoot");function Bo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=jo(n);for(let i of t){if(typeof i!="string"||i.length===0||va(i))continue;if(i.includes("*")){let c=zo(i.toLowerCase());if(me(c).test(r)||me(`${c}/**`).test(r))return!0;continue}let a=jo(i);if(a.length===0)continue;let l=Ea.includes(o[0])&&a[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+a.length>o.length)continue;let p=!0;for(let g=0;g<a.length;g+=1)if(o[c+g]!==a[g]){p=!1;break}if(p)return!0}}return!1}s(Bo,"pathUnderSharedRoot");function Wo(e,t){let n=String(e).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=t.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}s(Wo,"sliceMatchesDeclaration");function Sa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Wo(r.from,t)&&Wo(r.to,n))}s(Sa,"crossSliceEdgeAllowed");function wa(e){if(!e.fromPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0;if(!e.toPath)return t?e.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!e.toSlice||e.toShared===!0;return!t||!n?{denied:!0,reason:"unclassifiable-path"}:!e.fromSlice||!e.toSlice?{denied:!1}:e.fromSlice===e.toSlice?{denied:!1}:e.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}s(wa,"peerIsolationDecision");function tt(e,t){switch(e){case"cross-slice":return`cross-slice edge ${t.fromSlice??"?"} \u2192 ${t.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"unclassifiable-path":{let n=[t.fromSlice?void 0:t.fromPath,t.toSlice?void 0:t.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(tt,"peerIsolationDenyExplanation");function nt(e,t,n,r){return Ne(e,t,n,r)?.rule}s(nt,"findDeniedEdgeRule");function Ne(e,t,n,r){for(let o of e??[])if(!(o.from!==t||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,a=r?.toPath,l=ba(o,t,r?.layers),c=i?Vo(i,l):void 0,p=a?Vo(a,l):void 0,g=wa({fromPath:i,toPath:a,folderCount:l.length,fromSlice:c,toSlice:p,fromShared:!c&&Bo(i,o.sharedRoots),toShared:!p&&Bo(a,o.sharedRoots),crossSliceAllowed:Sa(o.allowedCrossSlice,c,p)});if(g.denied)return{rule:o,peerIsolationReason:g.reason,fromSlice:c,toSlice:p};continue}if(t!==n)return{rule:o}}}s(Ne,"findDeniedEdgeDecision");async function qo(e,t){if(t.mode==="off"||!t.architectureProfile)return;let n=e.metadata.source;if(!n||n==="unknown")return;let r=t.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(e.intent);if(!o||!i)return;let a=nt(r.rules,o,i);if(!a)return;let l=t.mode,c=a.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${i}).`,p={source:n,intent:e.intent,fromLayer:o,toLayer:i,severity:l,message:c,rule:a};if(t.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:p}),await t.recordAudit("layer.observedViolation",e,p),l==="hard")throw new Je(n,e.intent,o,i,c)}s(qo,"assertObservedLayerFlowAllowed");async function Yo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof be&&(t.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:o.violations}}),await t.recordAudit("policy.hardViolation",e,{violations:o.violations})),o}r.softViolations.length>0&&(t.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{violations:r.softViolations}}),await t.recordAudit("policy.softViolation",e,{violations:r.softViolations}),t.onSoftViolation&&await t.safeHook(()=>t.onSoftViolation(r,e),"onSoftViolation",e))}s(Yo,"enforcePublishPolicy");function Ca(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}s(Ca,"appendHistory");function St(e,t){e.trace.push(t),e.maxHistorySize!==void 0&&e.trace.length>e.maxHistorySize&&e.trace.splice(0,e.trace.length-e.maxHistorySize);for(let n of e.traceSinks)try{n(t)}catch{}}s(St,"appendTrace");async function bn(e,t,n,r){if(e.auditTrail)try{await e.auditTrail.record({type:t,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){St(e,{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(bn,"recordAudit");async function Xo(e,t){let n={intent:t.intent,source:t.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};St(e,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:n}),await bn(e,"event.rawPublish",t,n)}s(Xo,"recordRawPublishDiagnostic");async function Zo(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return Ca(e,o),await e.eventBuffer?.enqueue(t,r),St(e,{type:"event.published",timestamp:o.publishedAt,intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{subscribersNotified:n}}),await bn(e,"event.published",t,{subscribersNotified:n}),o}s(Zo,"recordSuccessfulPublish");function Er(e,t,n){return{...e,...t,occurredAt:t.occurredAt||e.occurredAt||new Date().toISOString(),source:t.source||e.source||"unknown",kernelInstanceId:t.kernelInstanceId??e.kernelInstanceId??n,eventVersion:t.eventVersion??e.eventVersion,schemaVersion:t.schemaVersion??e.schemaVersion,allowInterception:t.allowInterception??e.allowInterception,interceptions:t.interceptions??e.interceptions,correlationId:t.correlationId??e.correlationId,causationId:t.causationId??e.causationId,traceId:t.traceId??e.traceId,spanId:t.spanId??e.spanId,parentSpanId:t.parentSpanId??e.parentSpanId}}s(Er,"enrichMetadata");var Jo=0;function xa(){return Jo+=1,`interceptor-${Date.now()}-${Jo}`}s(xa,"nextInterceptorRegistrationId");var rt=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(t={}){if(this.onPublish=t.onPublish,this.onSoftViolation=t.onSoftViolation,this.onHandlerError=t.onHandlerError,this.eventContracts=t.eventContracts,this.strictEventContracts=t.strictEventContracts??!1,this.requireKnownSource=t.requireKnownSource??!1,this.architectureProfile=t.architectureProfile,this.enforceObservedLayerFlowMode=t.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=t.rethrowHandlerErrors??!1,this.intentRegistry=t.intentRegistry,this.dependencyGraph=t.dependencyGraph,this.strictRegistry=t.strictRegistry??t.intentRegistry!==void 0,this.validateIntentNaming=t.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:t.maxHistorySize,traceSinks:[...t.traceSinks??[]],auditTrail:t.auditTrail,eventBuffer:t.eventBuffer??t.outbox,instanceId:t.instanceId},t.policyEngine?this.policyEngine=t.policyEngine:t.policies&&t.policies.length>0&&(this.policyEngine=new _e(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Rn)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new Xe;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=kn({intentRegistry:t.intentRegistry,dependencyGraph:t.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(t,n,r,o){await this.dispatch(t,n,r,o)}async dispatch(t,n,r,o={}){let i=o.notifySubscribers!==!1,a=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,p=typeof t!="function";if(p){let u=t,f=r??n??{};c={...u,metadata:Er(u.metadata,f,this.recording.instanceId)}}else{let u=t,f=n,m=r??{},y=u(f);c={...y,metadata:Er(y.metadata,m,this.recording.instanceId)}}p&&this.strictRegistry&&await Xo(this.recording,c),Et(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),$o(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),vt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Ho(c,{interceptorsForIntent:s(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:s(u=>this.appendTrace(u),"appendTrace"),recordAudit:s((u,f,m)=>this.recordAudit(u,f,m),"recordAudit")}),vt(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await qo(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:s(u=>this.appendTrace(u),"appendTrace"),recordAudit:s((u,f,m)=>this.recordAudit(u,f,m),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let g=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Yo(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:s(u=>this.appendTrace(u),"appendTrace"),recordAudit:s((u,f,m)=>this.recordAudit(u,f,m),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:s((u,f,m)=>this.safeHook(u,f,m),"safeHook")}),await Zo(this.recording,c,i?g.length:0,o.tx);let h=(async()=>{i&&await Promise.all(g.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return a?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return Et(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 Ee(n,i.source);await this.publish(r,o,{...i,source:n},a)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;Et(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 l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(t,n,r){let o=typeof t=="string"?t:t.name;Et(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:xa(),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(t){let n=this.interceptors.find(i=>i.registrationId===t);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(t){return this.interceptors.filter(n=>!t||n.intentName===t).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(t){St(this.recording,t)}async recordAudit(t,n,r){await bn(this.recording,t,n,r)}async invokeHandler(t,n){try{await Promise.resolve(t.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:t.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,t.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(t,n,r){try{await Promise.resolve(t())}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 Qo(e){return new rt(e)}s(Qo,"createEventBus");function Oa(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}s(Oa,"formatStandardSchemaPath");function Pa(e){if(Array.isArray(e))return"array";if(e===null)return"object";let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t==="object"?t:"unknown"}s(Pa,"actualType");function _a(e,t){return e?`${e}.${t}`:t}s(_a,"formatPath");function ei(e,t,n,r,o){let i=Pa(e);if(t.type!=="unknown"&&i!==t.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${t.type}, received ${i}.`});return}if(t.enum&&!t.enum.some(a=>Object.is(a,e))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),t.type==="object"&&t.fields){if(e===null||typeof e!="object"||Array.isArray(e)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}ti(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((a,l)=>{ei(a,t.items,`${n}[${l}]`,r,o)})}s(ei,"validateSchemaField");function ti(e,t,n,r,o){for(let[i,a]of Object.entries(t)){let l=_a(o,i),c=e[i];if(c===void 0){a.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}ei(c,a,l,n,r)}}s(ti,"validateObjectSchema");var wt=class{static{s(this,"EventContractRegistryImpl")}contracts=new Map;register(t){let n=this.key(t.intent,t.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...t})}get(t,n){return n?this.contracts.get(this.key(t,n)):this.list(t).at(-1)}list(t){return Array.from(this.contracts.values()).filter(n=>!t||n.intent===t)}validate(t){let n=t.metadata.eventVersion,r=this.get(t.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:t.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:t.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=t.payload!=null&&typeof t.payload=="object"?t.payload:void 0;if(r.schema){if(!i)o.push({intent:t.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(ti(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let a of Object.keys(i))r.schema[a]||o.push({intent:t.intent,version:r.version,field:a,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let a=r.standardSchema["~standard"].validate(t.payload);if(a instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(a.issues)for(let l of a.issues)o.push({intent:t.intent,version:r.version,field:Oa(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(t,n){return`${t}@${n}`}};function En(){return new wt}s(En,"createEventContractRegistry");var ni=0;function Ta(){return ni+=1,`outbox-${Date.now()}-${ni}`}s(Ta,"nextOutboxId");function ri(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}s(ri,"cloneRecord");var De=class{static{s(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:Ta(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),ri(r)}async markDispatched(t){let n=this.records.get(t);n&&(n.status="dispatched",n.updatedAt=new Date().toISOString())}async markFailed(t,n){let r=this.records.get(t);r&&(r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString())}async list(t){return Array.from(this.records.values()).filter(n=>!t||n.status===t).map(ri)}async clear(){this.records.clear()}},oi=De;function vr(e){return`${e.from}->${e.to}`}s(vr,"flowKey");function ii(e){let t=new Set,n=[];for(let r of e){let o=vr(r);t.has(o)||(t.add(o),n.push(r))}return n}s(ii,"uniqueFlows");function si(e,t){let n=new Set(t.map(vr));return e.filter(r=>!n.has(vr(r)))}s(si,"difference");function vn(e){let t=e.registry,n=e.eventBus,r=e.graph;return{report(){let o=t?t.getAllRelationships().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="produces").map(y=>({from:y.from,to:y.to})),a=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=a.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=ii([...o,...i]),p=ii([...a,...l]),g=p.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(p.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],u=t?Array.from(new Set(p.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(p.flatMap(y=>[y.from,y.to])),m=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:p,declaredButUnobserved:si(c,p),observedButUndeclared:si(p.filter(y=>y.from!=="unknown"),c),unknownSources:g,unregisteredObservedSources:h,unregisteredObservedIntents:u,registeredButNeverObserved:m}}}}s(vn,"createObservabilityReporter");function ai(e){return{events(t){return e.eventBus.getHistory().map(n=>n.event).filter(n=>!t||n.intent===t)},traces(t){return e.eventBus.getTrace().filter(n=>!t||n.type===t)},audit(t){return e.auditTrail.query(t)},outbox(t){return e.outbox.list(t)},observability(){return e.syncGraph(),e.observability.report()},async snapshot(){return{events:this.events(),traces:this.traces(),audit:await this.audit(),outbox:await this.outbox(),observability:this.observability()}},async clear(){e.eventBus.clearHistory(),e.eventBus.clearTrace(),await e.auditTrail.clear(),await e.outbox.clear()}}}s(ai,"createArkTestHarness");var li=0;function Na(){return li+=1,`audit-${Date.now()}-${li}`}s(Na,"createAuditId");function Da(e,t){return!(t.type&&e.type!==t.type||t.intent&&e.intent!==t.intent||t.correlationId&&e.correlationId!==t.correlationId||t.subject&&e.subject!==t.subject||t.since&&e.timestamp<t.since||t.until&&e.timestamp>t.until)}s(Da,"matchesQuery");var Ct=class{constructor(t){this.maxRecords=t}maxRecords;static{s(this,"InMemoryAuditStore")}records=[];append(t){this.records.push(t),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(t={}){let n=this.records.filter(r=>Da(r,t));return t.limit===void 0?[...n]:n.slice(-t.limit)}clear(){this.records.length=0}},Sn=class{constructor(t){this.store=t}store;static{s(this,"AuditTrailImpl")}async record(t){let n={id:Na(),timestamp:t.timestamp??new Date().toISOString(),type:t.type,source:t.source,actor:t.actor,intent:t.intent,correlationId:t.correlationId,causationId:t.causationId,subject:t.subject,details:t.details};return await this.store.append(n),n}async query(t){return this.store.query(t)}async clear(){await this.store.clear()}};function wn(e={}){return new Sn(e.store??new Ct(e.maxRecords))}s(wn,"createAuditTrail");var Cn=class{static{s(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(t,n,r="declared"){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,to:n,kind:r})}registerEventFlow(t,n){this.ensureNode(t),this.ensureNode(n),this.addEdge({from:t,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 t=`flowchart TD
|
|
8
8
|
`;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";t+=` ${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)||(t+=` ${this.safeId(r)}
|
|
10
|
-
`);return t.trim()}toLayerMermaid(t){let n=new Map;for(let
|
|
11
|
-
`;for(let
|
|
10
|
+
`);return t.trim()}toLayerMermaid(t){let n=new Map;for(let i of this.nodes.keys()){let a=t.resolveLayer(i)??"Unclassified",l=n.get(a)??[];l.push(i),n.set(a,l)}let r=`flowchart TD
|
|
11
|
+
`;for(let i of t.layers){let a=n.get(i.name)??[];if(a.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
|
|
12
12
|
`;for(let l of a)r+=` ${this.safeId(l)}[${l}]
|
|
13
13
|
`;r+=` end
|
|
14
14
|
`}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
|
|
15
|
-
`;for(let
|
|
15
|
+
`;for(let i of o)r+=` ${this.safeId(i)}[${i}]
|
|
16
16
|
`;r+=` end
|
|
17
|
-
`}for(let
|
|
18
|
-
`}return r.trim()}detectViolations(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let
|
|
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(t=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of t)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(t){this.nodes.has(t)||this.nodes.set(t,{id:t})}addEdge(t){this.edges.some(r=>r.from===t.from&&r.to===t.to&&r.kind===t.kind)||this.edges.push(t)}findSimpleCycles(){let t=new Map;for(let l of this.edges)t.has(l.from)||t.set(l.from,[]),t.get(l.from).push(l.to);let n=[],r=new Set,o=[],i=s(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))i(c);else if(o.includes(c)){let p=o.indexOf(c),g=o.slice(p).concat(c);n.push(g)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||i(l);let a=new Set(n.map(l=>l.join("->")));return Array.from(a).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function xn(){return new Cn}s(xn,"createDependencyGraph");function On(e,t,n={}){let r=n.requireRegisteredTargets??!1;for(let o of e.getAllRelationships())r&&!e.has(o.to)||(o.kind==="dependsOn"?t.registerDependency(o.from,o.to,"declared"):t.registerDependency(o.from,o.to,"produces"))}s(On,"syncRegistryToGraph");var Le={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ci={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Le,default:[]},kernelRoots:{...Le},managedLayers:{...Le,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},di={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Le,default:[]},managedLayers:{...Le,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Le,default:[]},appliesTo:{...Le,default:[]}}};function xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(xt,"isObject");function ui(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)xt(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}s(ui,"declaredLayerNames");function pi(e){if(!xt(e))return e;let t={mode:e.mode===void 0?"advisory":e.mode,compositionRoots:e.compositionRoots===void 0?[]:e.compositionRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,requireDeclarations:e.requireDeclarations===void 0?!0:e.requireDeclarations};return e.kernelRoots!==void 0&&(t.kernelRoots=e.kernelRoots),e.ignoreDirectNewForErrors!==void 0&&(t.ignoreDirectNewForErrors=e.ignoreDirectNewForErrors),{...e,...t}}s(pi,"defaultedArkRun");function fi(e){if(!xt(e))return e;let t=typeof e.maxXiKeys=="number"&&e.maxXiKeys>0?e.maxXiKeys:7;return{...e,mode:e.mode===void 0?"advisory":e.mode,planeRoots:e.planeRoots===void 0?[]:e.planeRoots,managedLayers:e.managedLayers===void 0?[]:e.managedLayers,maxXiKeys:t,xiKeys:e.xiKeys===void 0?[]:e.xiKeys}}s(fi,"defaultedArkOrder");function gi(e,t){let n=e.arkRun;if(n===void 0||!xt(n))return;let r=ui(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((i,a)=>{typeof i=="string"&&i.length>0&&!r.has(i)&&t.push({path:`$.arkRun.managedLayers[${a}]`,message:`layer ${JSON.stringify(i)} is not declared in layers[]`})}),n.mode==="enforced"){let i=n.kernelRoots??n.compositionRoots;(!Array.isArray(i)||i.length===0)&&t.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}s(gi,"validateArkRunExtra");function mi(e,t){let n=e.arkOrder;if(n===void 0||!xt(n))return;let r=ui(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((i,a)=>{typeof i=="string"&&i.length>0&&!r.has(i)&&t.push({path:`$.arkOrder.managedLayers[${a}]`,message:`layer ${JSON.stringify(i)} is not declared in layers[]`})}),n.mode==="enforced"){let i=n.planeRoots;(!Array.isArray(i)||i.length===0)&&t.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(o)||o.length===0)&&t.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}s(mi,"validateArkOrderExtra");var se="1.3",_n="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",yi=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],La=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Fa(){let e=[];for(let t of yi)for(let n of yi)t===n||La.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}s(Fa,"createDefaultRules");var Tn=Fa(),Sr=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ie={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},hi={$schema:"https://json-schema.org/draft/2020-12/schema",$id:_n,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:_n,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:se,default:se},name:{type:"string",minLength:1},include:{...ie,minItems:1,default:["src"]},exclude:{...ie,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:Tn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ie,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:{...ie,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ie,minItems:1},exclude:ie,intentPrefixes:ie,description:{type:"string",minLength:1},forbiddenGlobals:ie,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:{...ie,minItems:1},sharedRoots:{...ie,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget 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.",properties:{testGlobs:{...ie,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:{...ie,minItems:1}}},arkRun:ci,arkOrder:di}},ye=class extends Error{static{s(this,"ArkConfigValidationError")}issues;source;constructor(t,n){super(`Invalid ArkGate config (${t}):
|
|
19
19
|
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
20
|
-
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function
|
|
21
|
-
`));return a}i(As,"createAdapter");function ks(e,t=[]){let n=t.filter(r=>!Is(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}i(ks,"checkContract");function br(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}i(br,"checkAdapterGovernance");function Is(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}i(Is,"hasMember");var vr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),wr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Cr=Object.freeze(Object.keys(wr).sort()),Er=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Sr=Object.freeze({process:Object.freeze(["process","node:process"])});function Pt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=Er[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=Er[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:Er[e.slice(0,s)]??null}i(Pt,"capabilityForModuleSpecifier");function ve(e,t){for(let n of t)if(Sr[n]?.includes(e))return n;return null}i(ve,"forbiddenGlobalForModuleSpecifier");function Dn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=wr[r];if(o)return o}return null}i(Dn,"capabilityForAmbientName");function it(e){if(e?.pure===!0)return[...vr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>vr.includes(r));return[...new Set(n)].sort()}i(it,"effectiveCapabilityDeny");function _t(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}i(_t,"ambientCoveredByForbiddenGlobals");function Ln(e){let t=new Set,n=new Set,r=Object.keys(wr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(a=>a===o||a.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let a of s)t.add(`ambient:${a}`);for(let a of Sr[o]??[])t.add(`import-exact:${a}`)}for(let o of it(e)){if(t.add(`import:${o}`),o==="process")for(let s of Sr.process)t.add(`import-exact:${s}`);for(let s of r)Dn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}i(Ln,"loweredLayerCoverage");function at(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(at,"literalText");function vs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}i(vs,"lineOf");function bs(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(s=>s.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}i(bs,"isTypeOnlyReference");function Ss(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}i(Ss,"singleFileChecker");function xr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}i(xr,"symbolAt");function Or(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):xr(t,r)}catch{s=void 0}return!!s?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}i(Or,"localDeclaration");function lt(e,t){let n,r=[],o=i((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:vs(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),s=i(a=>{if(e.isImportDeclaration(a))o(a,"import",at(e,a.moduleSpecifier),bs(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",at(e,a.moduleSpecifier),bs(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",at(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Or(e,n??(n=Ss(e,t)),t,a.expression);(l||p)&&o(a,p?"require":"dynamic-import",at(e,a.arguments[0]))}e.forEachChild(a,s)},"visit");return s(t),r}i(lt,"extractSemanticDependencies");function Wa(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=at(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}i(Wa,"staticAccessPath");function za(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}i(za,"runtimeIdentifierReference");function Es(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}i(Es,"bestForbiddenMatch");function ct(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Ss(e,t),s=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations)e.isIdentifier(f.name)&&a.add(f.name.text);let l=i(u=>{let f=Wa(e,u);if(!f)return;let g=xr(o,f.root),y=g?s.get(g):void 0;return y?[...y,...f.segments.slice(1)]:Or(e,o,t,f.root)||a.has(f.root.text)?void 0:f.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let g=l(f.initializer),y=xr(o,f.name);!g||!y||s.set(y,g)}let c=[],p=new Set,m=i((u,f)=>{let g=vs(t,f),y=`${u}:${f.getStart(t)}`;p.has(y)||(p.add(y),c.push({name:u,line:g,node:f}))},"flag"),h=i(u=>{let f=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!f){let g=l(u),y=g?Es(r,g):void 0;y&&m(y,u)}else e.isIdentifier(u)&&r.has(u.text)&&za(e,u)&&!Or(e,o,t,u)&&m(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let g=l(u.initializer);if(g)for(let y of u.name.elements){if(!e.isIdentifier(y.name))continue;let v=y.propertyName?at(e,y.propertyName)??y.propertyName.text:y.name.text,E=Es(r,[...g,v]);E&&m(E,u.initializer)}}e.forEachChild(u,h)},"visit");return h(t),c}i(ct,"collectForbiddenCapabilityUses");function Pr(e,t,n){let r=[];for(let o of n?.dependencies??lt(e,t)){if(o.typeOnly||!o.specifier)continue;let s=Pt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??ct(e,t,Cr)){let s=Dn(o.name);s&&r.push({capability:s,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,s)=>o.line-s.line||o.capability.localeCompare(s.capability)||o.symbol.localeCompare(s.symbol))}i(Pr,"collectCapabilityUses");var _r={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Nr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function Tr(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(s=>({layer:r.name,layerIndex:o,prefix:s.endsWith(".")?s:`${s}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}i(Tr,"resolveIntentLayer");function Fe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}i(Fe,"looksLikeArkIntent");function Nt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Fe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:_r.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:_r.PUBLISH_MISSING_SOURCE}),t}i(Nt,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}i(j,"violation");function dt(e,t){return e.slice(0,t).split(`
|
|
22
|
-
`).length}i(dt,"lineOf");var qa=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ya(e,t){return e.index+e[0].indexOf(t)}i(Ya,"captureIndex");function Xa(e){let t=[],n=new Set,r=i((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=i(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let p=c[1];p&&r(p,Ya(c,p))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let s=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=s.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),p=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,m;for(;(m=p.exec(l))!==null;){let h=m[1];h&&r(h,c+m.index+m[0].indexOf(h))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}i(Xa,"extractQuotedStrings");function Za(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let s=o.index+o[0].indexOf(o[1]),a=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}i(Za,"extractModuleSpecifiers");function Ja(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}i(Ja,"isSyntaxWrapper");function Dr(e,t){let n=t;for(;n?.parent&&Ja(e,n.parent);)n=n.parent;return n}i(Dr,"unwrapWrappers");function Lr(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}i(Lr,"callCalleeName");function Qa(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Dr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Lr(e,o)==="publish"){let s=o.arguments;return s[1]===r||s[2]===r}if(e.isPropertyAssignment(o)&&Fr(e,o.name)==="metadata"){let s=o.parent;if(!s)return!1;let l=Dr(e,s).parent;return!!(l&&e.isCallExpression(l)&&Lr(e,l)==="publish")}return!1}i(Qa,"isPublishMetadataSource");function ws(e,t){let n=Dr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Lr(e,r);if(o&&qa.has(o)&&r.arguments.some(s=>s===n))return!0}if(e.isArrayLiteralExpression(r))return ws(e,r);if(e.isPropertyAssignment(r)){let o=Fr(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Qa(e,r))return!0}return!1}i(ws,"isDeclaredIntentSite");function el(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=i(s=>{e.isStringLiteralLike(s)&&ws(e,s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}i(el,"extractQuotedStringsAst");function tl(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}i(tl,"hasInfrastructureToken");function nl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}i(nl,"isKnownInfrastructurePackage");function rl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}i(rl,"layerHasInfrastructureRole");function Dt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}i(Dt,"tsStringLiteralText");function Fr(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}i(Fr,"tsPropertyName");function Cs(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Fr(e,r.name)===n)}i(Cs,"tsObjectProperty");function Lt(e,t,n){return Cs(e,t,n)!==void 0}i(Lt,"tsObjectHasProperty");function Tt(e,t,n){let r=Cs(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}i(Tt,"tsObjectPropertyValue");function ol(e,t){let n=Tt(e,t,"metadata");return Lt(e,n,"source")}i(ol,"tsObjectHasMetadataSource");function xs(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?xs(e,t.name):!1:!1}i(xs,"tsLooksLikeIntentCreatorExpression");function sl(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}i(sl,"tsIsPublishCall");function il(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Dt(e,n);return r!==void 0&&Fe(r)||Lt(e,n,"intent")||xs(e,n)}i(il,"tsIsArkPublishCandidate");function al(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return ol(e,n)||Lt(e,r,"source")||Lt(e,o,"source")}i(al,"tsPublishHasSource");function ll(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Tt(e,n,"metadata");return Dt(e,Tt(e,s,"source"))??Dt(e,Tt(e,r,"source"))??Dt(e,Tt(e,o,"source"))}i(ll,"tsPublishSourceLiteral");function cl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,a=s?.filePath,l=s?.layer,c=[],p=i(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=i(h=>{if(sl(e,h)){let u=h.arguments[0],f=Dt(e,u);for(let y of Nt({publishCall:!0,rawIntentName:f,objectHasIntent:Lt(e,u,"intent"),arkPublishCandidate:il(e,h),hasSource:al(e,h)}))c.push(j(y.ruleId,y.message,{line:p(h),filePath:a}));let g=ll(e,h);if(r&&l&&g&&Fe(g)){let y=r.resolveLayer(g);y&&y!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${g}" resolves to ${y}, but the target file is classified as ${l}.`,{line:p(h),filePath:a,target:g,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}i(cl,"analyzePublishAst");function Os(e={}){let t=new Set((e.intents||[]).map(s=>typeof s=="string"?s:s.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(s,a){let l=[],c=a,p=c?.filePath,m=c?.layer,h=e.typescript,u=h?h.createSourceFile(p??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,f=u?lt(e.typescript,u):void 0,g=f?f.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(u),kind:A.kind,typeOnly:A.typeOnly})):Za(s),y=e.typescript?el(e.typescript,s):Xa(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let A of f?.filter(({unresolved:b})=>b)??[]){let b=A.kind==="require";l.push(j(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:p}))}let v=m!==void 0&&(r.has(m)||rl(m)),E=m!==void 0?` If "${m}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let b=A.exec(s);A.lastIndex=0,b&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:b.index===void 0?void 0:dt(s,b.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else s.includes(A)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:dt(s,s.indexOf(A)),filePath:p}));for(let A of g){let b=e.resolveImportTarget?.(A.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,p)}:void 0),w=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,T=b?.layer;if(T&&m){let I=nt(e.architectureProfile?.rules,m,T,{fromPath:w?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(I){if(A.typeOnly&&!I.peerIsolation)continue;let N=!!I.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",I.message??(N?`Layer "${m}" must not import across slices into "${T}".`:`Layer "${m}" must not import "${T}".`),{line:dt(s,A.index),source:A.value,target:A.value,filePath:p,fromLayer:m,toLayer:T,suggestion:N?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:A.kind,peerIsolation:N,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||A.typeOnly||!tl(A.value)&&!nl(A.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:dt(s,A.index),source:A.value,target:A.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let b=A.check({source:s,context:a});if(b!==!0)if(Array.isArray(b))for(let w of b)l.push(j("POLICY_VIOLATION",w.message,{filePath:p,suggestion:`Fix violation of policy "${A.name}".`}));else b===!1?l.push(j("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",b.message))}if(o&&t.size>0)for(let A of y)Fe(A.value)&&!t.has(A.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:dt(s,A.index),filePath:p,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let A of y){if(!Fe(A.value))continue;let b=e.architectureProfile.resolveLayer(A.value);if(!b)continue;let w=Te(e.architectureProfile.rules,m,b,{fromPath:typeof p=="string"?p:void 0,layers:e.architectureLayers});if(w){let T=w.rule.peerIsolation?tt(w.peerIsolationReason??"cross-slice",{fromPath:typeof p=="string"?p:void 0,fromSlice:w.fromSlice,toSlice:w.toSlice}):void 0,I=`Layer "${m}" must not reference "${b}" through "${A.value}".`,N=T&&w.peerIsolationReason!=="cross-slice"?`${I} ${T}`:w.rule.message?T?`${w.rule.message} (${T})`:w.rule.message:I;l.push(j("LAYER_REFERENCE_VIOLATION",N,{line:dt(s,A.index),filePath:p,target:A.value,fromLayer:m,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:w.rule,peerIsolationReason:w.peerIsolationReason}}))}}if(e.extensions)for(let A of e.extensions)try{let b=A.analyze(s,a);l.push(...b)}catch(b){l.push(j("EXTENSION_ERROR",`Extension "${A.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&u&&m&&e.forbiddenGlobals?.[m]?.length)try{let A=e.forbiddenGlobals[m];l.push(...ct(e.typescript,u,A).map(b=>j("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${b.name}".`,{line:b.line,filePath:p,target:b.name,fromLayer:m,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of f??[]){if(b.typeOnly||!b.specifier)continue;let w=ve(b.specifier,A);w&&l.push(j("FORBIDDEN_GLOBAL",`${m} must not use module "${b.specifier}" because it is the import form of forbidden global "${w}".`,{line:b.line,filePath:p,source:b.specifier,target:b.specifier,fromLayer:m,details:{importKind:b.kind,forbiddenGlobal:w},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&u&&m&&e.capabilityWalls?.[m]?.length)try{let A=new Set(e.capabilityWalls[m]),b=e.forbiddenGlobals?.[m]??[];for(let w of Pr(e.typescript,u))A.has(w.capability)&&(w.source==="ambient-global"&&_t(w.symbol,b)||w.source==="import-based"&&ve(w.symbol,b)||l.push(j("CAPABILITY_VIOLATION",w.source==="import-based"?`${m} denies the ${w.capability} capability; found import of "${w.symbol}".`:`${m} denies the ${w.capability} capability; found ambient "${w.symbol}".`,{line:w.line,filePath:p,target:w.symbol,capability:w.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...cl(e.typescript,s,a,e.architectureProfile))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}i(Os,"createAICodeGate");function W(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}i(W,"deterministicHash");function M(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(M).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`}i(M,"stableSerialize");var $e="1.2";var Ps=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=M(e),r=M(t);return n<r?-1:n>r?1:0}i(B,"compareCanonical");function z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}i(z,"sortedUnique");function Ft(e){let t={schemaVersion:"1.2",include:z(e.include??[]),exclude:z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:z(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:z(n.patterns??[]),exclude:z(n.exclude??[]),forbiddenGlobals:z(n.forbiddenGlobals??[]),intentPrefixes:z(n.intentPrefixes??[]),capabilityDeny:z(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(B),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:z(e.arkRun.compositionRoots),managedLayers:z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return W(M(t))}i(Ft,"resolvedFactsEvidenceRequirementsHash");function dl(e){let t=e.completenessReasons.map(I=>({code:I.code,message:I.message,...I.file?{file:I.file}:{}})).sort(B),n=e.files.map(I=>({...I,typeOnlyExportNames:z(I.typeOnlyExportNames)})).sort((I,N)=>I.path<N.path?-1:I.path>N.path?1:0),r=e.dependencies.map(I=>({...I,...I.namedBindings?{namedBindings:z(I.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(I=>({...I})).sort(B),s=e.ambientUses.map(I=>({...I})).sort(B),a=e.publishCalls.map(I=>({...I})).sort(B),l=e.intentReferences.map(I=>({...I})).sort(B),c=e.safetyUses.map(I=>({...I})).sort(B),p=(e.classShapes??[]).map(I=>({...I,mutatingMethods:[...I.mutatingMethods??[]].map(N=>({...N}))})).sort(B),m=(e.arkRunKernelCalls??[]).map(I=>({...I})).sort(B),h=(e.arkRunManagedNews??[]).map(I=>({...I})).sort(B),u=(e.arkRunCompositionRootHits??[]).map(I=>({...I})).sort(B),f=(e.arkRunDeclarations??[]).map(I=>({...I,uses:z(I.uses),reactsTo:z(I.reactsTo),raises:z(I.raises),sends:z(I.sends)})).sort(B),g=(e.arkOrderPlaneCalls??[]).map(I=>({...I})).sort(B),y=(e.arkOrderGenericUpdates??[]).map(I=>({...I})).sort(B),v=(e.arkOrderRootHits??[]).map(I=>({...I})).sort(B),E=(e.arkOrderXiFieldWrites??[]).map(I=>({...I})).sort(B),A=(e.arkOrderIngestWritesXi??[]).map(I=>({...I})).sort(B),b=(e.arkOrderReleaseKeyCounts??[]).map(I=>({...I})).sort(B),w=e.files.map(({path:I,contentHash:N})=>({path:I,contentHash:N})).sort((I,N)=>I.path<N.path?-1:I.path>N.path?1:0),T=W(M(w));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:T,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:u,arkRunDeclarations:f,arkOrderPlaneCalls:g,arkOrderGenericUpdates:y,arkOrderRootHits:v,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:b}}i(dl,"canonicalResolvedFactsInput");function _s(e){let t=dl(e);return{...t,factsHash:W(M(t))}}i(_s,"createCanonicalResolvedCandidateFacts");function $r(e){return _s(Ts(F(e,"$"),!1))}i($r,"createResolvedCandidateFacts");function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}i(F,"asRecord");function K(e,t,n){let r=new Set(t),o=Object.keys(e).find(s=>!r.has(s));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}i(K,"assertOnlyKeys");function L(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}i(L,"requiredText");function he(e,t,n){if(e[t]!==void 0)return L(e,t,n)}i(he,"optionalText");function H(e,t,n){let r=L(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let s=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(s.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);s.pop()}else s.push(l);let a=s.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}i(H,"requiredProjectPath");function U(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}i(U,"requiredBoolean");function Ns(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}i(Ns,"requiredInteger");function Y(e,t,n){let r=Ns(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}i(Y,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}i(G,"requiredArray");function Re(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}i(Re,"enumValue");function ut(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}i(ut,"parseStringArray");function ul(e,t,n){let r=new Set;for(let o of e){let s=t(o);if(r.has(s))throw new Error(`${n} must not contain duplicate facts (${s}).`);r.add(s)}}i(ul,"assertUnique");function Ts(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Re(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Re(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=F(S,R);K(d,["code","message","file"],R);let _=d.file===void 0?void 0:H(d,"file",R);return{code:L(d,"code",R),message:L(d,"message",R),..._?{file:_}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let s=G(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=F(S,R);return K(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:H(d,"path",R),contentHash:L(d,"contentHash",R),parseStatus:Re(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:Ns(d,"parseDiagnosticCount",R),exportsOnlyTypes:U(d,"exportsOnlyTypes",R),typeOnlyExportNames:ut(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:U(d,"hasTopLevelSideEffects",R)}}),a=G(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=F(S,R);K(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let _=he(d,"specifier",R),$=he(d,"target",R),oe=Re(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(oe==="resolved-project"&&!$)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(oe!=="resolved-project"&&$)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(oe!=="dynamic"&&!_)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:H(d,"from",R),..._?{specifier:_}:{},kind:Re(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:U(d,"typeOnly",R),line:Y(d,"line",R),resolution:oe,...$?{target:H(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:ut(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:U(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:U(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:U(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:U(d,"portProofEligible",R)}:{}}}),l=G(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=F(S,R);return K(d,["file","line","symbol","capability","source"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:L(d,"symbol",R),capability:Re(d,"capability",Ps,R),source:Re(d,"source",["ambient-global","import-based"],R)}}),c=G(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=F(S,R);return K(d,["file","line","symbol"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:L(d,"symbol",R)}}),p=G(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=F(S,R);K(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let _=he(d,"rawIntentName",R),$=he(d,"sourceIntent",R);return{file:H(d,"file",R),line:Y(d,"line",R),..._?{rawIntentName:_}:{},objectHasIntent:U(d,"objectHasIntent",R),arkPublishCandidate:U(d,"arkPublishCandidate",R),hasSource:U(d,"hasSource",R),...$?{sourceIntent:$}:{}}}),m=G(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=F(S,R);return K(d,["file","line","intent"],R),{file:H(d,"file",R),line:Y(d,"line",R),intent:L(d,"intent",R)}}),h=G(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=F(S,R);K(d,["file","line","kind","symbol"],R);let _=he(d,"symbol",R),$=Re(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if($==="in-memory-store"&&!_)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if($!=="in-memory-store"&&_)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:H(d,"file",R),line:Y(d,"line",R),kind:$,..._?{symbol:_}:{}}});ul(s,S=>S.path,"$.files");let u=new Set(s.map(S=>S.path));for(let S of s){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&s.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!u.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let g=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=F(S,R);K(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let _=he(d,"receiver",R),$=he(d,"nameLiteral",R);return{file:H(d,"file",R),line:Y(d,"line",R),kind:Re(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:L(d,"callee",R),viaImport:U(d,"viaImport",R),..._?{receiver:_}:{},...$?{nameLiteral:$}:{}}}),v=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=F(S,R);K(d,["file","line","typeName","importedFrom"],R);let _=he(d,"importedFrom",R);return{file:H(d,"file",R),line:Y(d,"line",R),typeName:L(d,"typeName",R),..._?{importedFrom:_}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=F(S,R);return K(d,["file","matchedRoot","hasKernelFactory"],R),{file:H(d,"file",R),matchedRoot:L(d,"matchedRoot",R),hasKernelFactory:U(d,"hasKernelFactory",R)}}),b=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),T=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=F(S,R);return K(d,["file","line","callee"],R),{file:H(d,"file",R),line:Y(d,"line",R),callee:L(d,"callee",R)}}),N=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=F(S,R);return K(d,["file","line","method"],R),{file:H(d,"file",R),line:Y(d,"line",R),method:L(d,"method",R)}}),me=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=F(S,R);return K(d,["file","matchedRoot","hasPlaneFactory"],R),{file:H(d,"file",R),matchedRoot:L(d,"matchedRoot",R),hasPlaneFactory:U(d,"hasPlaneFactory",R)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=F(S,R);return K(d,["file","line","key"],R),{file:H(d,"file",R),line:Y(d,"line",R),key:L(d,"key",R)}}),X=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=F(S,R);return K(d,["file","line"],R),{file:H(d,"file",R),line:Y(d,"line",R)}}),kt=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=F(S,R);return K(d,["file","line","keyCount"],R),{file:H(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),It=b.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=F(S,R);return K(d,["file","line","uses","reactsTo","raises","sends"],R),{file:H(d,"file",R),line:Y(d,"line",R),uses:ut(d.uses,`${R}.uses`),reactsTo:ut(d.reactsTo,`${R}.reactsTo`),raises:ut(d.raises,`${R}.raises`),sends:ut(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",m],["$.safetyUses",h],["$.arkRunKernelCalls",g],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",It],["$.arkOrderPlaneCalls",T],["$.arkOrderGenericUpdates",N],["$.arkOrderRootHits",me],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",X],["$.arkOrderReleaseKeyCounts",kt]])for(let R of C)if(!u.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Pe=he(e,"projectPackageName","$"),cr=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=F(S,R);K(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let _=G(d,"mutatingMethods",R).map(($,oe)=>{let un=`${R}.mutatingMethods[${oe}]`,dr=F($,un);return K(dr,["name","referencesGuardOrPublish"],un),{name:L(dr,"name",un),referencesGuardOrPublish:U(dr,"referencesGuardOrPublish",un)}});return{file:H(d,"file",R),className:L(d,"className",R),exported:U(d,"exported",R),hasPublicMutableFields:U(d,"hasPublicMutableFields",R),hasPublicSetters:U(d,"hasPublicSetters",R),hasPublicConstructor:U(d,"hasPublicConstructor",R),hasStaticFactory:U(d,"hasStaticFactory",R),mutatingMethods:_,...d.dataOnly===void 0?{}:{dataOnly:U(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:L(e,"resolverIdentity","$"),compilerIdentity:L(e,"compilerIdentity","$"),compilerOptionsHash:L(e,"compilerOptionsHash","$"),tsconfigHash:L(e,"tsconfigHash","$"),evidenceRequirementsHash:L(e,"evidenceRequirementsHash","$"),...Pe?{projectPackageName:Pe}:{},files:s,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:m,safetyUses:h,classShapes:cr,arkRunKernelCalls:g,arkRunManagedNews:v,arkRunCompositionRootHits:A,arkRunDeclarations:It,arkOrderPlaneCalls:T,arkOrderGenericUpdates:N,arkOrderRootHits:me,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:X,arkOrderReleaseKeyCounts:kt}}i(Ts,"parseResolvedFactsInput");function Se(e){let t=F(e,"$"),n=L(t,"factsHash","$"),r=L(t,"candidateTreeHash","$"),o=_s(Ts(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}i(Se,"loadResolvedCandidateFacts");var pl=["network","filesystem","clock","randomness","environment","process","persistence"],O={type:"string",minLength:1},Z={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Mr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:O,message:O,file:V}}},resolverIdentity:O,compilerIdentity:O,compilerOptionsHash:O,tsconfigHash:O,candidateTreeHash:O,evidenceRequirementsHash:O,projectPackageName:O,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:O,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:O},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:V,specifier:O,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Z,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:O},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:V,line:Z,symbol:O,capability:{enum:pl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:Z,symbol:O}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:Z,rawIntentName:O,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:O}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:Z,intent:O}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:Z,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:O},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:V,className:O,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:O,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:Z,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:O,viaImport:{type:"boolean"},receiver:O,nameLiteral:O}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:Z,typeName:O,importedFrom:O}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:O,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:Z,uses:{type:"array",items:O},reactsTo:{type:"array",items:O},raises:{type:"array",items:O},sends:{type:"array",items:O}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:Z,callee:O}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:Z,method:O}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:O,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:Z,key:O}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:Z}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:Z,keyCount:{type:"integer",minimum:1}}}},factsHash:O},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var Kr="1.0";function te(e){return`${e.from}->${e.to}`}i(te,"dependencyKey");function $t(e,t,n,r="dependency"){return{id:`${e}:${r}:${te(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${te(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${te(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${te(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${te(t)} from the candidate, then preflight again.`}:{}}}i($t,"dependencyFinding");function pt(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),o=new Map(e.changeMap.map.dependencies.map(u=>[te(u),u])),s=new Map(e.baseDependencies.map(u=>[te(u),u])),a=new Map(e.candidateDependencies.map(u=>[te(u),u]));for(let u of[...n.values()].sort((f,g)=>f.path.localeCompare(g.path))){let f=r.get(u.path);f?f.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((f,g)=>f.path.localeCompare(g.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...o.values()].sort((f,g)=>te(f).localeCompare(te(g)))){if(a.has(te(u))){t.push($t("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let f={from:u.to,to:u.from};a.has(te(f))?(l.add(te(f)),t.push($t("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push($t("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,f]of[...a].sort(([g],[y])=>g.localeCompare(y)))s.has(u)||o.has(u)||l.has(u)||!c.has(f.from)&&!c.has(f.to)||t.push({...$t("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,f]of[...s].sort(([g],[y])=>g.localeCompare(y)))a.has(u)||p.has(f.from)||p.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...$t("unplanned",f,`${f.from} -> ${f.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let m={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,f)=>m[u.classification]-m[f.classification]||(u.subject===f.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(f.id));let h={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}i(pt,"analyzeArchitectureConvergence");var Ds="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",fl=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Ls={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Lf={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Ds,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:Ds},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...fl]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ls,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ls}}}};function Mt(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}i(Mt,"emptyEffectiveArkRules");function Hr(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}i(Hr,"omitLayerDescriptions");function Fs(e){let{stewards:t,...n}=Hr(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}i(Fs,"effectiveContractPolicyPayload");function $s(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}i($s,"formatCoverageDiscards");function ml(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}i(ml,"isUnderCoverageRoot");function gl(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}i(gl,"titleMatchesInvariant");function yl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let s of Object.values(e))if(!(o&&!s.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(s)||s.includes(t)))return!0;return!1}i(yl,"symbolPresent");function Ms(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,s=e.coverageStats,a=$s(s),l=$s(s,!0),c=s?`coverage file budget exhausted: ${s.filesLoaded} files loaded at the ${s.maxFiles}-file cap, ${s.testFilesRetained} tests retained, ${s.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof s.filesRead=="number"?`; ${s.filesRead} were read`:""})`:"coverage file budget exhausted",p=(e.coverageRoots??[]).filter(g=>typeof g=="string"&&g.length>0),m=p.length>0,h=p.join(", "),u=[],f=[];for(let g of t){let y=[],v=g.coverage?.test!==!1,E=g.coverage?.symbol,A,b;if(!r&&v){let N;for(let ee of n){let me=e.fileContents[ee];if(!(!me||!gl(me,g.id))){if(!m||ml(ee,p)){A=ee,b=m?!1:void 0;break}N??=ee}}A===void 0&&N!==void 0&&(A=N,b=!0),A!==void 0&&y.push("test-title")}E&&yl(e.fileContents,E)&&y.push("symbol");let T=(g.coverage?.test===!0||!!E||g.coverage===void 0)&&y.length>0||g.coverage?.test===!1&&!E?!0:y.length>0,I=r&&v&&y.length===0;if(u.push({invariantId:g.id,layer:g.provenance.layer,sourceFile:g.provenance.sourceFile,mode:g.mode,covered:T&&!I,evidence:y,partial:I,description:g.description,...A!==void 0?{testEvidenceFile:A}:{},...b!==void 0?{outsideDeclaredRoots:b}:{}}),b===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${g.id} is covered only by ${A}, which is outside the declared coverage roots (${h}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:A,line:1,arkruleId:g.id,arkruleSource:g.provenance.sourceFile,fromLayer:g.provenance.layer,severity:"warning",failsStrict:!1}),!T||I){let N=g.mode==="enforced"&&!I,ee=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(I?o?`Invariant ${g.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${g.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:ee==="tests-disappeared"?`Invariant ${g.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${g.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(I&&o?l:a),file:g.provenance.sourceFile,line:1,arkruleId:g.id,arkruleSource:g.provenance.sourceFile,fromLayer:g.provenance.layer,severity:N?"error":"warning",failsStrict:N,kind:ee})}}return{coverage:u,violations:f,partial:u.some(g=>g.partial)}}i(Ms,"evaluateInvariantCoverage");function Ks(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}i(Ks,"canPromoteInvariant");var Vr="1.0";function P(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}i(P,"addFinding");function q(e){return[...new Set(e??[])].sort()}i(q,"sortedUnique");function de(e,t,n,r,o){let s=q(n),a=q(r),l=new Set(s),c=new Set(a),p=a.filter(h=>!l.has(h)),m=s.filter(h=>!c.has(h));p.length===0&&m.length===0||(p.length>0&&P(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:a}),m.length>0&&P(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:a}))}i(de,"compareStringSets");function Kt(e,t,n,r,o,s,a){if(n===r)return;P(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:a,before:n,after:r})}i(Kt,"compareBoolean");function Fn(e,t){let n=new Map,r=new Set;for(let o of e){let s=t(o);n.has(s)?r.add(s):n.set(s,o)}return{values:n,duplicates:[...r].sort()}}i(Fn,"keyed");function hl(e,t,n){let r=Fn(t,s=>s.name),o=Fn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&P(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let s of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!a&&l){P(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){P(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;de(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),de(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let p=Ln(a),m=Ln(l);de(e,`${c}.forbiddenGlobals`,p.rawGlobals,m.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),de(e,`${c}.capabilities`,p.atoms,m.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),q(a.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&P(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:q(a.intentPrefixes),after:q(l.intentPrefixes)}),Kt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Kt(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}i(hl,"compareLayers");function Rl(e,t,n){let r=i(a=>`${a.from}->${a.to}`,"keyOf"),o=Fn(t,r),s=Fn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&P(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:s.duplicates});for(let a of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(a),c=s.values.get(a),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&P(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&P(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&P(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let m=l.peerIsolation===!0,h=c.peerIsolation===!0;if(m!==h){let u=l.from===l.to&&c.from===c.to;P(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?h?"strengthening":"weakening":"judgment-required",message:u?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:m,after:h})}q(l.sliceFolders).join("\0")!==q(c.sliceFolders).join("\0")&&P(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!m&&!h)&&(Us(e,`${p}.sharedRoots`,"shared-roots",q(l.sharedRoots),q(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Us(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(Hs)),q((c.allowedCrossSlice??[]).map(Hs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}i(Rl,"compareRules");function Hs(e){return JSON.stringify([e.from,e.to])}i(Hs,"crossSliceKey");function Us(e,t,n,r,o,s,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),p=l.length>0&&c.length>0;P(e,{kind:p?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":l.length>0?"weakening":"strengthening",message:p?`${s} Entries were added and removed in the same change.`:l.length>0?s:a,before:r,after:o})}i(Us,"compareDeclaredExceptions");function Al(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let a=r[s]??0,l=o[s]??0;a!==l&&P(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])Kt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}i(Al,"compareSafety");function Ur(e){return e.mode==="enforced"?"enforced":"advisory"}i(Ur,"arkRunMode");function Gr(e){return e.mode==="enforced"?"enforced":"advisory"}i(Gr,"arkOrderMode");function kl(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Gr(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=Gr(r),l=Gr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}de(e,`${s}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),de(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}i(kl,"compareArkOrder");function Il(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Ur(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Ur(r),l=Ur(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${s}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}de(e,`${s}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),de(e,`${s}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Kt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}i(Il,"compareArkRun");function bl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}i(bl,"overallClassification");function Gs(e,t){return`${e}::${t}`}i(Gs,"ruleKey");function Vs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Gs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Gs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}i(Vs,"indexEffectiveRules");function El(e,t,n,r,o,s){let a=new Map((s??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let f=l[u],g=c[u],y=`$.arkRules[${u}]`;if(f===void 0&&g!==void 0){P(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:g});continue}if(f!==void 0&&g===void 0){P(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:f});continue}f!==g&&P(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:f,after:g})}let m=Vs(r),h=Vs(o);for(let u of[...new Set([...m.structure.keys(),...h.structure.keys()])].sort()){let f=m.structure.get(u),g=h.structure.get(u),y=`$.arkRules.structure[${u}]`;if(!f&&g){P(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${g.id} was added (${g.mode}).`,after:g});continue}if(f&&!g){P(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!g)){if(f.mode!==g.mode){let v=f.mode==="advisory"&&g.mode==="enforced";P(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${g.id} was promoted to enforced.`:`Structure ArkRule ${g.id} was demoted to advisory.`,before:f.mode,after:g.mode})}f.sensor!==g.sensor&&P(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${g.id} changed sensor identity.`,before:f.sensor,after:g.sensor})}}for(let u of[...new Set([...m.invariants.keys(),...h.invariants.keys()])].sort()){let f=m.invariants.get(u),g=h.invariants.get(u),y=`$.arkRules.invariants[${u}]`;if(!f&&g){P(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${g.id} was added (${g.mode}).`,after:g});continue}if(f&&!g){P(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!g)&&f.mode!==g.mode)if(f.mode==="advisory"&&g.mode==="enforced"){let E=a?.get(g.id),A=Ks(E);A.ok?P(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${g.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:g.mode}):P(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${g.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:g.mode})}else P(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${g.id} was demoted to advisory.`,before:f.mode,after:g.mode})}}i(El,"compareArkRules");function jr(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),de(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Kt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},s=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(s!==a){let l=o[a]===o[s]?"judgment-required":o[a]>o[s]?"strengthening":"weakening";P(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&P(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),hl(r,e.layers,t.layers),Rl(r,e.rules,t.rules),Al(r,e,t),El(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Il(r,e,t),kl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Vr,classification:bl(r),findings:r}}i(jr,"classifyArkPolicyDelta");function Br(e,t){if(!e||e.schemaVersion!==Vr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=q(e.findingIds),r=q(t.findingIds);return n.length===r.length&&n.every((o,s)=>o===r[s])}i(Br,"policyDeltaAcknowledgementMatches");function Me(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}i(Me,"normalizePath");function js(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}i(js,"isIdentifierStart");function $n(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i($n,"isIdentifierCharacter");function ne(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}i(ne,"skipWhitespace");function Ht(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let s=e[t];if(s===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};s==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=s}}i(Ht,"readString");function ae(e,t,n){return e.startsWith(t,n)&&!$n(e[n-1])&&!$n(e[n+t.length])}i(ae,"isWordAt");function Bs(e,t){let n=ne(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ne(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ae(e,"type",n))return!1;let o=ne(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ae(e,"as",o)||!js(e[o]))return!1;for(n=o;n<e.length&&$n(e[n]);)n+=1;if(n=ne(e,n),ae(e,"as",n)){if(n=ne(e,n+2),!js(e[n]))return!1;for(;n<e.length&&$n(e[n]);)n+=1}r=!0}return!1}i(Bs,"bracedNamedBindingsAreTypeOnly");function vl(e,t){if(t=ne(e,t+6),e[t]==="(")return Ht(e,ne(e,t+1));let n=!1;if(ae(e,"type",t)){let o=ne(e,t+4);e[o]!==","&&!ae(e,"from",o)&&(n=!0)}else Bs(e,t)&&(n=!0);let r=Ws(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}i(vl,"specifierAfterImport");function Sl(e,t){t=t+6;let n=ne(e,t),r=!1;if(ae(e,"type",n)){let s=ne(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Bs(e,n)&&(r=!0);let o=Ws(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}i(Sl,"specifierAfterExport");function Ws(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ae(e,"from",t))return Ht(e,ne(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ht(e,t);if(t>0&&(ae(e,"import",t)||ae(e,"export",t)))return}}i(Ws,"specifierInStaticStatement");function wl(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}i(wl,"skipTemplateLiteral");function Cl(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ne(e,t+7);if(e[r]!=="(")return;r=ne(e,r+1);let o=Ht(e,r);return o?{...o,requireCall:!0}:void 0}i(Cl,"specifierAfterRequire");function xl(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
23
|
-
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let
|
|
24
|
-
`).length;r.push({file:e.path,symbol:
|
|
25
|
-
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=Ol(e.path,s,t);n.push({from:e.path,specifier:s,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}i(zs,"moduleFactsFor");function Ol(e,t,n){let r=e.split("/");r.pop();for(let s of t.split("/"))s==="."||s===""||(s===".."?r.pop():r.push(s));let o=r.join("/");for(let s of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(s);if(a)return a}}i(Ol,"resolveSpecifier");function qs(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=nt(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}i(qs,"violationsFor");var Pl={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function _l(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}i(_l,"hasActiveArkRules");function Nl(e,t){return _l(e,t)?W(M(Fs({config:e,arkRules:t,warnings:[]}))):W(M(Hr(e)))}i(Nl,"policyHashFor");function Mn(e,t,n){let r=typeof e=="string"?gs(e,t):Ir(e,t),o=n?.arkRules??Mt();return{...r,arkRules:o,policyHash:Nl(r.config,o)}}i(Mn,"loadContract");function Ys(e){let t=Mn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Mn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=jr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),s=o.length>0,a=s&&Br(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:s,acknowledged:a,valid:!s||a}}i(Ys,"analyzePolicyDelta");function Ut(e){let t=e.files.map(h=>{let u=Me(h.path);return{path:u,content:h.content,contentHash:W(h.content),layer:ce(u,e.contract.config.layers)??null}}).sort((h,u)=>h.path.localeCompare(u.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let u=zs(h,n);r.push(...u.edges),o.push(...u.capabilityUses)}let s=qs(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(it(h))]));for(let h of o){let u=n.get(h.file)?.layer;if(!u)continue;let f=a.get(u),g=ve(h.symbol,f?.forbiddenGlobals??[]);if(g){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${h.symbol}" because it is the import form of forbidden global "${g}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(u)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let c=t.length===0?"complete":"partial",p=c==="complete"?[]:[{...Pl}],m={schemaVersion:Kr,policyHash:e.contract.policyHash,compilerOptionsHash:W(M(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:s};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&s.length===0,ir:m}}i(Ut,"analyzeProject");function Kn(e){let t=new Map(e.files.map(n=>[Me(n.path),n]));for(let n of e.changes){let r=Me(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ut({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}i(Kn,"analyzeChange");function Xs(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}i(Xs,"explainViolation");function Wr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],a=[],l=i(c=>{n.set(c,t),r.set(c,t),t+=1,s.push(c),o.add(c);for(let h of[...e.get(c)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(c,Math.min(r.get(c)??0,n.get(h)??0)):(l(h),r.set(c,Math.min(r.get(c)??0,r.get(h)??0))));if(r.get(c)!==n.get(c))return;let p=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),p.push(m)}while(m!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}i(Wr,"detectArchitectureCycles");function ft(e){let t=e.contentViolations.map(s=>({...s})),n=(e.warnings??[]).map(s=>({...s})),r=new Map(e.files.map(s=>[s,new Set]));for(let s of e.edges){if(s.to&&s.to!==s.from&&!s.typeOnly&&r.has(s.from)&&r.get(s.from)?.add(s.to),!s.to||!s.fromLayer||!s.toLayer)continue;let a=Te(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,p=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?tt(a.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,h=l.message?m?`${l.message} (${m})`:l.message:m?`${s.fromLayer} must not ${s.kind} another slice of ${s.toLayer} (${s.from} \u2192 ${s.to}): ${m}`:`${s.fromLayer} must not ${s.kind} ${s.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:s.from,line:s.line,fromLayer:s.fromLayer,toLayer:s.toLayer,target:s.to,...s.typeOnly?{typeOnly:!0}:{},...s.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...s.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...s.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&s.portProofEligible?{portProofEligible:!0}:{},...s.kind?{edgeKind:s.kind}:{},...c?{peerIsolation:!0}:{},message:p?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...p?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Wr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...s)}return{violations:t,warnings:n,safety:e.safety}}i(ft,"evaluateArchitectureGraph");function Zs(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}i(Zs,"structureFreezeTarget");var Tl=["no-anemic-model"],ti=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],gm=new RegExp(`\\b(${ti.join("|")})\\b`),ni="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",ym=new RegExp(`\\bthis\\.${ni}\\.push\\s*\\(`),hm=new RegExp(`^this\\.${ni}\\s*=\\s*\\[\\s*\\]`);var Dl="truncatedUntil";function Ll(){return`${ti.join(", ")}, or events-array .push(`}i(Ll,"expectedDomainInvariantWordsPhrase");function zr(e){let t=Object.getOwnPropertyDescriptor(e,Dl)?.value;return typeof t=="number"?t:void 0}i(zr,"shapeTruncatedUntil");function Fl(e){let t=zr(e);return t==null?"":` shape analysed until character ${t}`}i(Fl,"shapeTruncationSuffix");function Js(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(Js,"escapeGlobLiteral");function $l(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let s=e[r+1];if("*?{}[],".includes(s)||s==="\\"){t+="\\"+s,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=Js(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Js(o)}return new RegExp(`^${n}$`)}i($l,"globToRegExp");function mt(e,t){return!t||t.length===0?!0:t.some(n=>$l(n).test(e))}i(mt,"matchesAppliesTo");function Ml(e){return Tl.includes(e)}i(Ml,"isTier2");function ri(e){return e.mode==="enforced"&&!Ml(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}i(ri,"severityFor");function we(e,t,n,r=1){let{severity:o,failsStrict:s}=ri(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:s}}i(we,"baseViolation");function Hn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}i(Hn,"isInRuleLayer");function Un(e,t,n){return t.filter(r=>!(!r.exported||!mt(r.file,e.appliesTo)||!Hn(r.file,e,n)))}i(Un,"shapesForRule");function Kl(e,t,n){let r=[];for(let o of Un(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(we(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}i(Kl,"evaluateAggregatePrivateState");function Hl(e,t,n){let r=[];for(let o of Un(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(we(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}i(Hl,"evaluateAlwaysValidFactory");function Ul(e,t,n){let r=[],o=Ll();for(let s of Un(e,t,n)){let a=Fl(s);zr(s)!=null&&r.push(we(e,s.file,`Exported class ${s.className} shape analysed until character ${zr(s)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of s.mutatingMethods)l.referencesGuardOrPublish||r.push(we(e,s.file,`Mutating method ${s.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}i(Ul,"evaluateDomainEventOnMutation");function Gl(e,t){let n=[];for(let r of t.files)mt(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(we(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}i(Gl,"evaluateOrchestrationOnly");function Vl(e,t){let n=[];for(let r of t.files)mt(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(we(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}i(Vl,"evaluateThinAdapter");function jl(e,t){let n=[];for(let r of t.files)mt(r,e.appliesTo)&&Hn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(we(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}i(jl,"evaluateWritesViaAggregate");function Bl(e,t,n){let r=[];for(let o of Un(e,t,n))if(o.dataOnly===!0){let s=we(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...s,severity:"warning",failsStrict:!1})}return r}i(Bl,"evaluateNoAnemicModel");function oi(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Kl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Hl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ul(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Gl(n,e));break;case"thin-adapter":t.push(...Vl(n,e));break;case"writes-via-aggregate":t.push(...jl(n,e));break;case"no-anemic-model":t.push(...Bl(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}i(oi,"evaluateArkRuleSensors");function si(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>mt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=ri(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>mt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}i(si,"collectEmptyAppliesToFindings");var Qs=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,ei=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Wl=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function zl(e){return e==="PersistenceAdapters"}i(zl,"isPersistenceDriverLayer");function ql(e,t){if(Qs.test(e)||ei.test(e))return!0;if(!t)return!1;for(let n of t){if(zl(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(Qs.test(o)||ei.test(o))return!0}return!1}i(ql,"sourceImportsPersistenceDriver");var Yl=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Xl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Zl=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Jl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ql(e,t,n){if(!t)return null;let r=ql(t,n),o=r&&Wl.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let s=t.match(new RegExp(Zl.source,"g"))??[],a=t.match(new RegExp(Jl.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,p=s.length>=2||s.length>=1&&a.length>=2||a.length>=3&&l+c>=6,m=Yl.test(t)||Xl.test(t),h=s.length>=1||a.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),f=r&&h||m&&h||r&&u&&(l>=4||s.length>=1)||m&&r;return!p&&!f&&!o?null:{...p?{orchestrationHeavy:!0}:{},...f?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}i(Ql,"deriveArkRuleFileHints");function ii(e,t){let n={};for(let[r,o]of Object.entries(e)){let s=r.replace(/\\/g,"/"),a=Ql(r,o,t?.[s]);a&&(n[s]=a)}return n}i(ii,"buildArkRuleFileHints");function ec(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}i(ec,"normalizeExtraMergeTeethClassification");function Gn(e){let t=ec(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}i(Gn,"extraMergeTeethAllowed");function ai(e){let t=e.length,n=0,r=new Set;for(let o of e){let s=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;s&&(n+=1,r.add(s))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}i(ai,"classifyResolvedLayerCoverage");var tc=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var bm=new Set(tc);function li(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}i(li,"isArkRunKernelModuleSpecifier");var nc=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],qr=new Set(nc);function ci(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(qr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(qr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:qr.has(e.slice(0,r))}i(ci,"isArkRunTransportBypassSpecifier");var rc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Nm=new Set(rc);var di={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},oc="ARKRUN_INTERACTION_NAME_INCOMPLETE";function fi(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(fi,"isDomainRoleLayer");function sc(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}i(sc,"compareFindings");function Ae(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:di[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:di[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ae,"finding");function ic(e,t){let n=[],r=[],o=[],s=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),s.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}i(ic,"bagForFile");function ui(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}i(ui,"emitKinds");function pi(e){return e==="subscribe"||e==="register-handler"}i(pi,"handleKinds");function ac(e){return e==="resolve"||e==="resolve-singleton"}i(ac,"dependKinds");function lc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Ae(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let s=new Map;for(let a of t){let l=s.get(a.matchedRoot)??[];l.push(a),s.set(a.matchedRoot,l)}for(let a of o){let l=[...s.get(a)??[]].sort((p,m)=>p.file.localeCompare(m.file));if(l.length===0){r.push(Ae(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(Ae(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}i(lc,"evaluateMissingRoot");function cc(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!li(c))continue;let p=r(l.from);p&&fi(p,s.get(p)??[])&&a.push(Ae(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},o))}return a}i(cc,"evaluateKernelInDomain");function dc(e,t,n,r,o,s){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(m=>[m.name,m.intentPrefixes??[]])),c=new Set(r.filter(m=>m.hasKernelFactory).map(m=>m.file)),p=[];for(let m of n){if(c.has(m.file))continue;let h=m.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let u=o(m.file);!u||!a.has(u)||fi(u,l.get(u)??[])||p.push(Ae(e,"arkrun-direct-new",m.file,m.line,`${u} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:m.typeName},s))}return p}i(dc,"evaluateDirectNew");function uc(e,t,n,r,o){let s=[],a=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:a};for(let c of t){if(!ui(c.kind)&&!pi(c.kind)&&!ac(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:oc,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let m=ic(n,c.file);if(ui(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;s.push(Ae(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},o));continue}if(pi(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;s.push(Ae(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},o));continue}m.uses.has(c.nameLiteral)||s.push(Ae(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},o))}return{findings:s,completenessReasons:a}}i(uc,"evaluateUndeclared");function pc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!ci(l))continue;let c=n(a.from);!c||!o.has(c)||s.push(Ae(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}i(pc,"evaluateTransportBypass");function mi(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Gn(e.classification),r=uc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...lc(t,e.compositionRootHits,n),...cc(t,e.layers,e.dependencies,e.layerForFile,n),...dc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...pc(t,e.dependencies,e.layerForFile,n)].sort(sc),s=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:o,completenessReasons:s}}i(mi,"evaluateArkRunSensors");function gi(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}i(gi,"isArkOrderModuleSpecifier");var yi=new Map;function hi(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}i(hi,"escapeAppliesToLiteral");function fc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}i(fc,"normalizeAppliesToGlob");function mc(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}i(mc,"appliesToBracesBalanced");function gc(e){let t=yi.get(e);if(t)return t;let n=fc(e),r=mc(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=hi(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",s+=1):c==="}"&&r&&s>0?(o+=")",s-=1):c===","&&r&&s>0?o+="|":o+=hi(c)}let a=new RegExp(`^${o}$`);return yi.set(e,a),a}i(gc,"globToRegExp");var Ri={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function yc(e,t){return!t||t.length===0?!0:t.some(n=>gc(n).test(e))}i(yc,"matchesArkOrderAppliesTo");function hc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}i(hc,"isDomainRoleLayer");function Ce(e,t,n,r,o,s,a){let l=e.mode==="enforced"&&a;return{ruleId:Ri[t],sensor:t,message:o,file:n,line:r,...s?.fromLayer?{fromLayer:s.fromLayer}:{},...s?.target?{target:s.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:Ri[t],fromLayer:s?.fromLayer,target:s?.target})}}i(Ce,"finding");function Ai(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Gn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Ce(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let p of e.planeRootHits){let m=c.get(p.matchedRoot)??[];m.push(p),c.set(p.matchedRoot,m)}for(let p of o){let m=c.get(p)??[];if(m.length===0){r.push(Ce(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}m.some(h=>h.hasPlaneFactory)||r.push(Ce(t,"arkorder-missing-plane",m[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!gi(p))continue;let m=e.layerForFile(c.from);m&&hc(m,s.get(m)??[])&&r.push(Ce(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:p},n))}for(let c of e.genericUpdates)r.push(Ce(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ce(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Ce(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let p=e.layerForFile(c.file);!p||!l.has(p)||yc(c.file,t.appliesTo)&&r.push(Ce(t,"arkorder-xi-field-write",c.file,c.line,`File writes slow key ${JSON.stringify(c.key)} through a persistence driver; route the field through ingest or a pattern change through proposeRelease.`,{fromLayer:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}i(Ai,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}i(J,"configWarning");function Vn(e){let{config:t,rules:n,files:r,manifest:o}=e,s=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(f=>typeof f!="string"))&&s.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))s.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let g=t.safety[f];g!==void 0&&(!Number.isInteger(g)||g<0)&&s.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);a.length===0&&s.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,m=new Set;for(let f of a){if(!f.name){s.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(f.name)&&m.add(f.name),p.add(f.name),f.forbiddenGlobals!==void 0&&(!Array.isArray(f.forbiddenGlobals)||f.forbiddenGlobals.some(y=>typeof y!="string"))&&s.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${f.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:f.name}));let g=Array.isArray(f.patterns)?f.patterns:[];if(g.length===0){s.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of g){let v;try{v=ge(y)}catch(A){s.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${f.name}" has an invalid pattern "${y}": ${A instanceof Error?A.message:String(A)}`,{layer:f.name,pattern:y}));continue}let E=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>v.test(A))&&!E&&s.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${f.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:f.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let f of m)s.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${f}" is configured more than once.`,{layer:f}));if(c.size>0)for(let f of n??[])f.from&&!c.has(f.from)&&s.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${f.from}".`,{fromLayer:f.from,toLayer:f.to})),f.to&&!c.has(f.to)&&s.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(a.length>1)for(let f of r){let g=-1,y=[];for(let v of a)for(let E of v.patterns??[]){if(!ge(E).test(f))continue;let A=hr(E,f);A>g?(g=A,y=[v.name]):A===g&&!y.includes(v.name)&&y.push(v.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let u=r.filter(f=>!ce(f,a));return u.length>0&&s.push(J("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)})),s}i(Vn,"collectAnalysisConfigWarnings");function ki(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:Zs({sensor:e.sensor,code:e.code})}:{},...r?{freezable:!1}:{},nextAction:t}}i(ki,"toArkRuleEngineViolation");function Rc(e,t){return t.some(n=>{try{return ge(n).test(e)}catch{return!1}})}i(Rc,"matchesAny");function Ac(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,s=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:v})=>({file:y,line:v})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:v})=>({file:y,line:v})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Rc(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),p=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),m=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},u=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let g=c.filter(y=>y.kind==="require");if(g.length>0){let y=g[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${g.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(p.length>0){let y=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${p.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return m.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${m.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:u}}i(Ac,"evaluateSafety");function kc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}i(kc,"ambientForbiddenGlobal");function Ii(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return Tr(e,n.length>0?n:Nr.map(r=>({name:r.layer,prefixes:r.prefixes})))}i(Ii,"intentLayer");function Ic(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let a=n.get(s.file);!a||!kc(s.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,message:`${a} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let a=n.get(s.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],p=s.source==="import-based"?t.dependencies.find(m=>m.from===s.file&&m.line===s.line&&m.specifier===s.symbol&&!m.typeOnly)?.kind:void 0;if(!(s.source==="ambient-global"&&_t(s.symbol,c))){if(s.source==="import-based"){let m=ve(s.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:a,target:s.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}it(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:a,target:s.symbol,capability:s.capability,...p?{edgeKind:p}:{},message:s.source==="import-based"?`${a} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${a} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let a=n.get(s.file);if(!a)continue;for(let c of Nt({publishCall:!0,rawIntentName:s.rawIntentName,objectHasIntent:s.objectHasIntent,arkPublishCandidate:s.arkPublishCandidate,hasSource:s.hasSource}))r.push({ruleId:c.ruleId,file:s.file,line:s.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!s.sourceIntent)continue;let l=Ii(s.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let s of t.intentReferences){let a=n.get(s.file);if(!a)continue;let l=Ii(s.intent,e.contract);if(!l)continue;let c=Te(e.contract.config.rules,a,l,{fromPath:s.file,layers:e.contract.config.layers});if(!c)continue;let p=c.rule.peerIsolation?tt(c.peerIsolationReason??"cross-slice",{fromPath:s.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,m=`${a} must not reference ${l} intent ${s.intent}.`,h=p&&c.peerIsolationReason!=="cross-slice"?`${m} ${p}`:c.rule.message?p?`${c.rule.message} (${p})`:c.rule.message:m;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:a,toLayer:l,target:s.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:h})}return r}i(Ic,"contentViolations");function bc(e){let{facts:t}=e,n=Ft(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",s=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,_)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${_.code}\0${_.file??""}\0${_.message}`;return $<oe?-1:$>oe?1:0}),a=t.files.map(d=>({...d,layer:ce(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let _=d.target?l.get(d.target)??ce(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,..._?{toLayer:_}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),p=Vn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),m=Ac(e,t),h=e.contract.arkRules??Mt(),u=a.map(d=>d.path),g={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ii(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...oi({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),fileHints:g}),...si(h,u)],v=y.filter(d=>d.failsStrict).map(d=>ki(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`)),E=y.filter(d=>!d.failsStrict).map(d=>({...ki(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`),failsStrict:!1})),b=(h.invariants?.length??0)>0?Ms({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},w=b.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),T=b.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),I=ai(a),N=mi({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),ee=e.contract.config.arkRun?.mode,me=N.findings.filter(()=>ee==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),je=N.findings.filter(()=>ee!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),D=Ai({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:i(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),ue=e.contract.config.arkOrder?.mode,X=D.findings.filter(()=>ue==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Be=D.findings.filter(()=>ue!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),It=[...b.partial&&b.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...N.completenessReasons,...D.completenessReasons],Pe=ft({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Ic(e,t,l),...v,...w,...me,...X],edges:c,warnings:[...p,...m.warnings,...E,...T,...je,...Be],safety:m.report}),dn=o==="complete"&&It.length>0?"partial":o,cr=dn==="complete"?s:[...s,...It].sort((d,_)=>{let $=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${_.code}\0${_.file??""}\0${_.message}`;return $<oe?-1:$>oe?1:0}),S=Pe.violations.filter(d=>d.failsStrict!==!1),C=dn==="complete"&&S.length===0,R=C&&Pe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:dn,completenessReasons:cr,valid:C,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:m.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Pe.violations,warnings:Pe.warnings}}}i(bc,"analyzeCanonicalResolvedProject");function Gt(e){return bc({contract:e.contract,facts:Se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}i(Gt,"analyzeResolvedProject");function bi(e){return W(M(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}i(bi,"analysisTreeHash");function Ei(e){let t=Ut(e),n=new Map(t.ir.files.map(g=>[g.path,g])),r=[],o=new Set,s=[];for(let g of e.changes){let y=g.path.replace(/\\/g,"/"),v=Me(g.path);if(!v||v===".."||v.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){s.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(v)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}o.add(v),"delete"in g&&g.delete&&!n.has(v)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in g&&g.delete?{path:v,delete:!0}:{path:v,content:"content"in g?g.content:""})}e.changes.length===0&&s.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Kn({...e,changes:r}),l=new Map(a.ir.files.map(g=>[g.path,g])),c=a.ir.violations.filter(g=>g.ruleId==="CAPABILITY_VIOLATION"||g.ruleId==="FORBIDDEN_GLOBAL").map(g=>{let y=l.get(g.evidence.file)?.layer;return{ruleId:g.ruleId,file:g.evidence.file,line:g.evidence.line,target:g.symbol,...g.capability?{capability:g.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:g.message}}),p=ft({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(g=>g.path),contentViolations:c,edges:a.ir.edges.filter(g=>!!g.fromLayer).map(g=>({from:g.from,fromLayer:g.fromLayer,...g.to?{to:g.to}:{},...g.toLayer?{toLayer:g.toLayer}:{},line:g.evidence.line,kind:"import",...g.typeOnly?{typeOnly:!0}:{},...g.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(g=>{let y=Me(g.path),v=n.get(y),E=l.get(y);return{path:y,operation:"delete"in g&&g.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((g,y)=>g.path.localeCompare(y.path)),h=[...s,...p.violations].map(g=>({...g,nextAction:pe(g)})),u=h.filter(g=>g.failsStrict!==!1),f=e.changeMap?pt({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[]),candidateDependencies:a.ir.edges.flatMap(g=>g.to?[{from:g.from,to:g.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:bi(t.ir.files),candidateTreeHash:bi(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:p.warnings}}i(Ei,"preflightChange");function Ec(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}i(Ec,"canonicalChangePath");function vc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,s])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:s,message:`Base and candidate facts must use the same ${r}.`}))}i(vc,"identityViolations");function Sc(e,t,n,r){let o=n.get(t),s=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...s?{candidateContentHash:s.contentHash}:{}}}i(Sc,"preparedChange");function vi(e){let t=Se(e.baseFacts),n=Se(e.candidateFacts),r=Gt({contract:e.contract,facts:t}),o=Gt({contract:e.contract,facts:n}),s=new Map(t.files.map(f=>[f.path,f])),a=new Map(n.files.map(f=>[f.path,f])),l=vc(t,n),c=new Map,p=[];for(let f of e.changes){let g=Ec(f.path);if(!g){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(g)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:g,line:1,message:`The atomic change set contains more than one operation for ${g}.`});continue}c.set(g,f);let y=s.get(g),v=a.get(g);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:g,line:1,message:`Cannot delete ${g} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:g,line:1,message:`Candidate facts still contain deleted file ${g}.`});else{let E="content"in f?f.content:"",A=W(E);v?v.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:g,line:1,expectedContentHash:A,candidateContentHash:v.contentHash,message:`Candidate facts for ${g} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:g,line:1,message:`Candidate facts do not contain changed file ${g}.`})}p.push(Sc(f,g,s,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...s.keys(),...a.keys()])){if(c.has(f))continue;let g=s.get(f),y=a.get(f);g&&y&&M(g)===M(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:f,line:1,message:`Candidate facts change ${f}, but the atomic change set does not declare it.`})}let m=e.changeMap?pt({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:o.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0,h=[...l,...o.ir.violations].map(f=>({...f,nextAction:pe(f)})),u=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&u.length===0&&(m?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...m?{convergence:m}:{},changes:p.sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),violations:h,warnings:o.ir.warnings}}i(vi,"preflightResolvedChange");var Yr="docs/diagnostics.md",wc="1.0";function k(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}i(k,"entry");var jn=Object.freeze([k("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),k("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),k("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),k("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),k("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),k("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),k("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),k("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),k("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),k("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),k("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),k("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),k("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),k("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),k("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),k("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),k("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),k("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),k("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),k("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),k("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),k("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),k("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),k("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),k("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),k("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),k("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),k("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),k("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),k("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of \u03BE","A call to update/patch/set on the order plane rewrites the slow pattern. Haken slaving forbids generic \u03BE mutation.","Use release() for the first freeze of \u03BE. Later pattern change is proposeRelease then apply(ProposeResult). Never update/patch/set. Never mechanical-safe."),k("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),k("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),k("ARKORDER_XI_FIELD_WRITE","arkorder","Slow key written around the order plane","A managed-layer file imports a persistence driver and writes a declared arkOrder.xiKeys name. Field events absorb or escalate; they do not PATCH the slow pattern.","Keep invoices, seats, hours, and logs on ingest. Change the slow key with proposeRelease then apply(ProposeResult), then preflight again. Never mechanical-safe."),k("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),k("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),k("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),k("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),k("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),k("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),k("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),k("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),k("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),k("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),k("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),k("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),k("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),k("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),k("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),k("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),k("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),k("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),k("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),k("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),k("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),k("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),k("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),k("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),k("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),k("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),k("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),k("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),k("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),k("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),k("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),k("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),k("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),k("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),k("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),k("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),Xr=new Map(jn.map(e=>[e.ruleId,e])),Cc=Object.freeze(jn.map(e=>e.ruleId));function xc(e){return typeof e=="string"&&e.length>0&&Xr.has(e)}i(xc,"isKnownDiagnosticCode");function Oc(e){return typeof e!="string"||e.length===0?!1:Xr.has(e)?!0:e.startsWith("ARKRULE_")}i(Oc,"isCataloguedOrArkRuleFamily");function Bn(e){if(!(typeof e!="string"||e.length===0))return Xr.get(e)}i(Bn,"getDiagnosticCatalogEntry");function Si(e){return`#${Bn(e)?.docsAnchor??e}`}i(Si,"diagnosticDocsFragment");function Pc(e){return`${Yr}${Si(e)}`}i(Pc,"diagnosticDocsPath");function _c(){return{schemaVersion:"1.0",docsPath:Yr,codes:jn}}i(_c,"serializeDiagnosticCatalog");function Nc(e){return Bn(e)?.fix}i(Nc,"catalogFixForRuleId");function Tc(e){return Bn(e)?.why}i(Tc,"catalogWhyForRuleId");var Dc="1.1";var Lc="1.0";var Vt=class{static{i(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Fc(e){return typeof e.initialState=="function"?e.initialState():e.initialState}i(Fc,"initialState");var Wn=class{static{i(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Vt,this.auditTrail=t.auditTrail}register(t){if(this.definitions.has(t.name))throw new Error(`Projection "${t.name}" is already registered.`);this.definitions.set(t.name,t),this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(t){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(t.intent))continue;let o=await this.store.load(r.name)??Fc(r),s=await r.project(t,o);await this.store.save(r.name,s);let a=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(a?.appliedCount??0)+1,lastIntent:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function zn(e){return new Wn(e)}i(zn,"createProjectionRegistry");var qn="1.0";function $c(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}i($c,"policyId");var Zr=class{constructor(t){this.data=t}data;static{i(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Yn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,a=e.projections,l=e.eventContracts,c=e.observability,p=t?t.list().map(E=>({name:E.name,dependencies:t.getDependencies(E.name),productions:t.getProductions(E.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(E=>({id:$c(E.name),name:E.name,severity:E.severity,tags:E.tags?[...E.tags]:void 0,owner:E.owner,version:E.version,rationale:E.rationale,enforcementMode:E.enforcementMode,deprecated:E.deprecated,replacedBy:E.replacedBy,description:E.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],u=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},g=u.filter(E=>(E.emits?.length??0)>0||(E.consumes?.length??0)>0).map(E=>({entity:E.name,emits:E.emits,consumes:E.consumes})),y=a?a.list().map(E=>({name:E.name,sourceIntents:E.sourceIntents,checkpoint:a.getCheckpoint(E.name)})):[],v={schemaVersion:"1.0",version:ur,exportedAt:new Date().toISOString(),intents:p,relationships:m,policies:h,entities:u,graph:f,architecture:s?{profile:s.name,layers:s.layers,rules:s.rules}:void 0,projections:y,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:g}};return new Zr(v)}i(Yn,"createArkManifest");var wi=0;function Ci(e){return wi+=1,`${e}-${Date.now()}-${wi}`}i(Ci,"createWorkflowId");function Jr(e){return e instanceof Error?e.message:String(e)}i(Jr,"errorMessage");function Mc(e){return new Promise(t=>{setTimeout(t,e)})}i(Mc,"sleep");async function Kc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((a,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),s])}finally{o&&clearTimeout(o)}}i(Kc,"withTimeout");var jt=class{static{i(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,n,r){let o=Date.now();for(let s of this.snapshots.values()){if(r&&s.workflowName!==r||s.status!=="running"&&s.status!=="compensating")continue;let a=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||a){s.ownerId=t,s.expiresAt=new Date(o+n).toISOString();let l=(s.version??0)+1;return s.version=l,this.snapshots.set(s.id,{...s,context:{...s.context}}),{...s,context:{...s.context}}}}}clear(){this.snapshots.clear()}},Qr=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new jt}bus;options;static{i(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let s=new Date().toISOString(),a={id:r.id??Ci(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(a,r.tx),await this.audit("workflow.started",a,{workflowName:t}),this.executeSnapshot(a,o,r.tx)}async resume(t,n={}){let r=await this.get(t,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(t,n,r){try{let o=n.steps.filter(s=>!t.completedSteps.includes(s.name));for(let s of o)await this.runStep(t,s,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=Jr(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},s=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=s;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await Kc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<s){o.delayMs&&await Mc(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:a,error:Jr(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let s=n.filter(a=>t.completedSteps.includes(a.name));for(let a=s.length-1;a>=0;a-=1){let l=s[a];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:Jr(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Bt(e,t){return new Qr(e,t)}i(Bt,"createWorkflowEngine");function xi(e,t,n={}){let r=Bt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??Ci(e.name),a="idle",l=[];return{id:s,definition:e,get status(){return a},get completedSteps(){return[...l]},async run(c){a="running",l=[];try{let p=await r.start(e.name,c,{id:s});a=p.status==="waiting"?"idle":p.status,l=[...p.completedSteps]}catch(p){let m=await r.get(s);throw a=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],p}}}}i(xi,"createSaga");gt();function Ni(e){return Object.keys(e).sort()}i(Ni,"sortedKeys");function oo(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],p=Math.max(l.length,c.length);for(let m=0;m<p;m+=1)oo(l[m],c[m],`${n}[${m}]`,r);return}let o=e,s=t,a=new Set([...Ni(o),...Ni(s)]);for(let l of[...a].sort())oo(o[l],s[l],n?`${n}.${l}`:l,r)}i(oo,"walk");function Ti(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}i(Ti,"shadowInformationPackage");function so(e,t){let n=[];return oo(e,t,"",n),{equal:n.length===0,diffs:n}}i(so,"compareInformationPackages");function Di(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(so(e[n-1],e[n]));return t}i(Di,"replayInformationPackages");nr();Jt();ln();ln();async function lr(e,t={}){let n=on({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(qi(),zi));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}i(lr,"startArkRunInspector");nr();ln();gt();Jt();gt();var Ed=new Set(["singleton","transient"]);function Yi(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.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 t}i(Yi,"cloneComponent");function vd(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Ed.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}i(vd,"closedLifetime");function Xi(){let e=new Map,t=new Map,n=new Set;function r(a){let l=e.get(a);if(!l)throw new Error(`ArkRun component "${a}" is not registered.`);return l}i(r,"mustRecord");function o(a,l){if(!l.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 l.factory()}finally{n.delete(a)}}i(o,"instantiate");function s(a,l){if(t.has(a))return t.get(a);let c=o(a,l);return t.set(a,c),c}return i(s,"singleton"),{register(a){let l=typeof a?.id=="string"?a.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=vd(a.lifetime),p=no({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!p)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:p,factory:m}),Yi(p)},resolve(a){let l=r(a);return l.component.lifetime==="transient"?o(a,l):s(a,l)},resolveSingleton(a){let l=r(a);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return s(a,l)},snapshotComponents(){return[...e.values()].map(a=>Yi(a.component))}}}i(Xi,"createComponentRegistry");Jt();function Sd(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Ee(e.source,t.source);return t.source=e.source,t}i(Sd,"stampMetadata");function wd(){}i(wd,"ignoreDetachedFailure");async function Ao(e,t,n,r={}){let o=rr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Sd(r),a=await e.eventBus.dispatch(t,n,s,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(a));o.awaitHandoff?await l:l.then(void 0,wd)}return o}i(Ao,"sendOnArkRunTransport");var ko=1e3,Zi=0;function Cd(){return Zi+=1,`ark-kernel-${Date.now()}-${Zi}`}i(Cd,"nextKernelInstanceId");function Ji(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}i(Ji,"portConstructorId");function cn(e={}){let t=e.strict??!0,n=e.instanceId??Cd(),r=e.profile??st,o=e.maxHistorySize??ko,s=pn(),a=Sn(),l=e.metadata??Tn(),c=e.auditTrail===void 0,p=e.auditTrail??En({maxRecords:o}),m=e.eventContracts??kn(),h=e.eventBuffer===void 0&&e.outbox===void 0,u=e.eventBuffer??e.outbox??new De,f=e.projections??zn({auditTrail:p}),g=new _e([yn(r),...e.policies??[]]),y=i(()=>{wn(s,a,{requireRegisteredTargets:!0})},"syncGraph"),v=e.ephemeral??!0,E=e.broker,A=new rt({intentRegistry:s,dependencyGraph:a,policyEngine:g,strictRegistry:!0,validateIntentNaming:!0,auditTrail:p,eventContracts:m,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:u,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await f.apply(D)}}),b=Bt(A,{auditTrail:p}),w=In({registry:s,eventBus:A,graph:a}),T=Xi(),I=typeof E?.send=="function",N=h?"InMemoryEventBuffer":Ji(u,"EventBufferStore"),ee=c?"InMemoryAuditStore":Ji(p,"AuditTrail"),me=sn({stores:[Ue(N,"outbox"),Ue(ee,"audit"),Ue("InMemoryWorkflowStore","workflow")]}),je={instanceId:n,profile:r,registry:s,graph:a,metadata:l,auditTrail:p,eventContracts:m,eventBuffer:u,outbox:u,projections:f,policyEngine:g,eventBus:A,workflowEngine:b,observability:w,publisher(D){let ue=A.createPublisher(D);return{source:ue.source,publish:ue.publish,send(X,Be,kt={}){return Ao({eventBus:A,broker:E,defaultEphemeral:v},X,Be,{...kt,source:ue.source})}}},send(D,ue,X={}){return Ao({eventBus:A,broker:E,defaultEphemeral:v},D,ue,X)},register(D){return T.register(D)},resolve(D){return T.resolve(D)},resolveSingleton(D){return T.resolveSingleton(D)},getDependencyInformationPackage(){return ke({kernelInstanceId:n,components:T.snapshotComponents()})},requestGraph(D){return tr({kernelInstanceId:n,components:T.snapshotComponents()},D)},getInspectorSnapshot(D){return ar({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:T.snapshotComponents()},observability:w.report(),ephemeralDefault:v,brokerBound:I,hardening:me})},startInspector(D){return lr({getInspectorSnapshot:i(X=>je.getInspectorSnapshot(X),"getInspectorSnapshot"),requestGraph:i(X=>je.requestGraph(X),"requestGraph"),async listInspectorOutbox(){let[X,Be]=await Promise.all([u.list("pending"),u.list("failed")]);return Ge([...X,...Be],{sampleLimit:re})},async listInspectorWorkflows(){return Ve(await b.list(),{sampleLimit:re})}},D)},syncGraph:y,manifest(){return y(),Yn({registry:s,policyEngine:g,metadata:l,graph:a,profile:r,projections:f,eventContracts:m,observability:w})}};return je}i(cn,"createArkKernel");function Io(e={}){return cn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}i(Io,"createStrictArkKernel");function bo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:_n(e,{name:n})}}i(bo,"createOptionsFromConfig");function Qi(e,t={}){return cn(bo(e,t))}i(Qi,"createArkKernelFromConfig");function ea(e,t={}){return Io(bo(e,t))}i(ea,"createStrictArkKernelFromConfig");function ta(e,t={}){return Eo(bo(e,t))}i(ta,"createLenientArkKernelFromConfig");function Eo(e={}){return cn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}i(Eo,"createLenientArkKernel");export{Kr as ANALYSIS_IR_SCHEMA_VERSION,ga as ARK_ANALYSIS_RESULT_SCHEMA,fr as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Lc as ARK_DESIGN_DELTA_SCHEMA_VERSION,Dc as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,eo as ARK_RUN_COMPONENT_LIFETIMES,ht as ARK_RUN_EPHEMERAL_DEFAULT,co as ARK_RUN_GRAPH_DEFAULT_SLICE,Ki as ARK_RUN_GRAPH_NODE_KINDS,Hi as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,lo as ARK_RUN_GRAPH_SCHEMA_VERSION,uo as ARK_RUN_GRAPH_SLICES,Ui as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Xn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,or as ARK_RUN_INSPECTOR_DEFAULT_HOST,yo as ARK_RUN_INSPECTOR_DEFAULT_PORT,en as ARK_RUN_INSPECTOR_EVENTS_PATH,tn as ARK_RUN_INSPECTOR_GRAPH_PATH,re as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,nn as ARK_RUN_INSPECTOR_OUTBOX_PATH,go as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Qt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,ho as ARK_RUN_INSPECTOR_SSE_EVENT,Ro as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,rn as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,Zt as ARK_RUN_TRANSPORT_KINDS,le as ArkRunInspectorBindError,Rt as ArkRunInspectorProductionError,ko as DEFAULT_MAX_HISTORY_SIZE,jn as DIAGNOSTIC_CATALOG,wc as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Yr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Cc as DIAGNOSTIC_RULE_IDS,wt as EventContractRegistryImpl,Ze as EventContractViolationError,Ct as InMemoryAuditStore,De as InMemoryEventBuffer,es as InMemoryOutboxStore,Vt as InMemoryReadModelStore,jt as InMemoryWorkflowStore,We as IntentRegistry,Q as InvalidArkRunGraphQueryError,yt as InvalidArkRunSendOptionError,Ye as InvalidIntentNameError,Xe as LayerPolicyContextError,qn as MANIFEST_SCHEMA_VERSION,Je as ObservedLayerFlowViolationError,Vr as POLICY_DELTA_SCHEMA_VERSION,_e as PolicyEngine,be as PolicyViolationError,Mr as RESOLVED_CANDIDATE_FACTS_SCHEMA,$e as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ee as SourceMetadataOverrideError,Ne as UnknownEventSourceError,qe as UnregisteredIntentError,pt as analyzeArchitectureConvergence,Kn as analyzeChange,Ys as analyzePolicyDelta,Ut as analyzeProject,Gt as analyzeResolvedProject,_i as appendDecisionTape,mr as architecturalPolicies,er as arkRunGraphQueryFromSearchParams,Ie as arkRunInspectorUrl,sn as buildArkRunInspectorHardening,Ge as buildArkRunInspectorOutboxMonitor,ar as buildArkRunInspectorSnapshot,Ve as buildArkRunInspectorWorkflowsMonitor,ke as buildDependencyInformationPackage,hn as buildPublishPolicyContext,Nc as catalogFixForRuleId,Tc as catalogWhyForRuleId,br as checkAdapterGovernance,ks as checkContract,jr as classifyArkPolicyDelta,Ue as classifyArkRunInspectorStoreDurability,Qn as closeArkRunGraphQuery,mo as closedArkRunEphemeral,fo as closedArkRunTransportKind,Vn as collectAnalysisConfigWarnings,ct as collectForbiddenCapabilityUses,so as compareInformationPackages,Os as createAICodeGate,As as createAdapter,ma as createAdapterResult,Pn as createArchitectureProfile,_n as createArchitectureProfileFromArkConfig,cn as createArkKernel,Qi as createArkKernelFromConfig,Yn as createArkManifest,rs as createArkTestHarness,En as createAuditTrail,Sn as createDependencyGraph,hs as createElevenLayerArkConfig,Yo as createEventBus,kn as createEventContractRegistry,pn as createIntentRegistry,Eo as createLenientArkKernel,ta as createLenientArkKernelFromConfig,Tn as createMetadataRegistry,In as createObservabilityReporter,zn as createProjectionRegistry,$r as createResolvedCandidateFacts,xi as createSaga,Io as createStrictArkKernel,ea as createStrictArkKernelFromConfig,Bt as createWorkflowEngine,Po as defaultIntentRegistry,yn as defineArchitectureProfilePolicy,Oo as defineIntent,mn as defineLayerPolicy,ze as definePolicy,Rs as definePort,To as definePublishPolicy,Wr as detectArchitectureCycles,W as deterministicHash,Si as diagnosticDocsFragment,Pc as diagnosticDocsPath,st as elevenLayerProfile,ft as evaluateArchitectureGraph,Xs as explainViolation,lt as extractSemanticDependencies,po as formatArkRunGraphMermaid,an as formatArkRunInspectorSseEvent,Bn as getDiagnosticCatalogEntry,At as isArkRunInspectorLoopbackHost,sr as isArkRunInspectorProductionEnv,Oc as isCataloguedOrArkRuleFamily,xc as isKnownDiagnosticCode,gn as isLayerPolicy,Mn as loadContract,Se as loadResolvedCandidateFacts,Br as policyDeltaAcknowledgementMatches,Ei as preflightChange,vi as preflightResolvedChange,Di as replayInformationPackages,tr as requestArkRunGraph,on as resolveArkRunInspectorBind,rr as resolveArkRunSendPlan,Ft as resolvedFactsEvidenceRequirementsHash,_c as serializeDiagnosticCatalog,Ti as shadowInformationPackage,M as stableSerialize,lr as startArkRunInspector,wn as syncRegistryToGraph,pr as toAdapterDiagnostic,Ke as unavailableArkRunInspectorOutboxMonitor,He as unavailableArkRunInspectorWorkflowsMonitor,fn as validateIntentName,ur as version};
|
|
20
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Ri(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}s(Ri,"isObject");function Pn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}s(Pn,"propertyPath");function ot(e){return e===null?"null":Array.isArray(e)?"array":typeof e}s(ot,"valueType");function Ma(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}s(Ma,"resolveSchemaRef");function Ot(e,t,n,r,o){if(t.$ref){let i=Ma(t.$ref,r);if(!i){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}Ot(e,i,n,r,o);return}if(t.const!==void 0&&!Object.is(e,t.const)){o.push({path:n,message:`must equal ${JSON.stringify(t.const)}`});return}if(t.enum&&!t.enum.some(i=>Object.is(i,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Ri(e)){o.push({path:n,message:`must be an object; received ${ot(e)}`});return}let i=t.properties??{};for(let a of t.required??[])e[a]===void 0&&o.push({path:Pn(n,a),message:"is required"});if(t.additionalProperties===!1)for(let a of Object.keys(e))a in i||o.push({path:Pn(n,a),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let a=t.additionalProperties;for(let l of Object.keys(e))l in i||Ot(e[l],a,Pn(n,l),r,o)}for(let[a,l]of Object.entries(i))e[a]!==void 0&&Ot(e[a],l,Pn(n,a),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${ot(e)}`});return}if(t.minItems!==void 0&&e.length<t.minItems&&o.push({path:n,message:`must contain at least ${t.minItems} item(s)`}),t.uniqueItems){let i=e.map(a=>JSON.stringify(a));new Set(i).size!==i.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((i,a)=>Ot(i,t.items,`${n}[${a}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${ot(e)}`});return}t.minLength!==void 0&&e.length<t.minLength&&o.push({path:n,message:`must contain at least ${t.minLength} character(s)`});return}if(t.type==="boolean"){typeof e!="boolean"&&o.push({path:n,message:`must be a boolean; received ${ot(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${ot(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}s(Ot,"validateNode");function $a(e){let t={...e,$schema:e.$schema===void 0?_n:e.$schema,schemaVersion:e.schemaVersion===void 0?se:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?Tn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=pi(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=fi(e.arkOrder)),t}s($a,"defaultedConfig");function Ka(e){return e===se?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}s(Ka,"migratedFromOf");function Ha(){let e=new Set([se]);for(let t of Sr)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}s(Ha,"knownInputVersions");function Ua(e,t="ark.config.json"){if(!Ri(e))throw new ye(t,[{path:"$",message:`must be an object; received ${ot(e)}`}]);let n=Ha(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${se}`}]);if(r!=="unversioned"&&!n.has(r))throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${se}`}]);let o=r,i={...e},a=0;for(;o!==se&&a<Sr.length+1;){a+=1;let l=Sr.find(c=>c.from===o);if(!l)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${se}`}]);o=l.to,i.schemaVersion=o}if(o!==se)throw new ye(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${se}`}]);return{candidate:$a(i),migratedFrom:Ka(r)}}s(Ua,"migrateArkConfig");function wr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=Ua(e,t),o=[];if(Ot(n,hi,"$",hi,o),gi(n,o),mi(n,o),o.length>0)throw new ye(t,o);return{config:n,migratedFrom:r}}s(wr,"loadArkConfigContract");function Ai(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new ye(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return wr(n,t)}s(Ai,"parseArkConfigJson");function ki(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:_n,schemaVersion:se};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}s(ki,"withArkConfigMetadata");function Ga(e){return e.endsWith(".")?e:`${e}.`}s(Ga,"normalizePrefix");function Va(e,t){let n=e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0;return(t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0)-n}s(Va,"byLongestPrefix");function Nn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(Ga)})),n=[...t].sort(Va),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(a=>o.startsWith(a)))?.name}}}s(Nn,"createArchitectureProfile");function Dn(e,t={}){return Nn({name:t.name??e.name??"ark.config.json",layers:e.layers.map((n,r)=>({name:n.name,prefixes:n.intentPrefixes??[],description:n.description,order:r+1})),rules:e.rules??[]})}s(Dn,"createArchitectureProfileFromArkConfig");var ja=[{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}],it=Nn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:ja,rules:Tn.map(e=>({...e}))}),Ba={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Ii(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ki({include:e.include??[t],layers:it.layers.map(o=>({name:o.name,patterns:(Ba[o.name]??[o.name]).map(i=>`${r}${i}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...it.rules]})}s(Ii,"createElevenLayerArkConfig");var Ln=class{static{s(this,"MetadataRegistryImpl")}entities=new Map;entity(t,n,r={}){if(this.entities.has(t)&&!r.allowOverwrite)throw new Error(`Entity metadata "${t}" is already registered.`);let o={name:t,fields:{},...n};return this.entities.set(t,o),o}getEntity(t){return this.entities.get(t)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(t){return this.listEntities().filter(n=>n.emits?.includes(t)||n.consumes?.includes(t))}validate(){let t=[];for(let n of this.entities.values()){n.name.trim()||t.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||t.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&t.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&t.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:t.length===0,issues:t}}toJSON(){return this.listEntities()}};function Fn(){return new Ln}s(Fn,"createMetadataRegistry");function bi(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}s(bi,"definePort");function Ei(e,t,n,r={}){let o=Array.isArray(n)?{...r,requiredKeys:n}:{...n??{}},i=o.requiredKeys;if(i&&i.length>0){let c=i.filter(p=>!Si(t,p));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let a={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=Cr(a);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
|
+
`));return a}s(Ei,"createAdapter");function vi(e,t=[]){let n=t.filter(r=>!Si(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}s(vi,"checkContract");function Cr(e){let t=e.port.allowedAdapters??[];return t.length===0?{ok:!0,issues:[]}:[e.name,e.intent].filter(o=>typeof o=="string"&&o.length>0).some(o=>t.includes(o))?{ok:!0,issues:[]}:{ok:!1,issues:[{ruleId:"ADAPTER_NOT_ALLOWED_FOR_PORT",port:e.port.name,adapter:e.name??e.intent,message:`Adapter "${e.name??e.intent??"unknown"}" is not allowed for port "${e.port.name}".`}]}}s(Cr,"checkAdapterGovernance");function Si(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}s(Si,"hasMember");var Or=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),_r=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),Tr=Object.freeze(Object.keys(_r).sort()),xr=Object.freeze({fs:"filesystem","node:fs":"filesystem","fs/promises":"filesystem","node:fs/promises":"filesystem","fs-extra":"filesystem","graceful-fs":"filesystem",memfs:"filesystem",chokidar:"filesystem",http:"network",https:"network",http2:"network",net:"network",tls:"network",dgram:"network",dns:"network","node:http":"network","node:https":"network","node:http2":"network","node:net":"network","node:tls":"network","node:dgram":"network","node:dns":"network",axios:"network",undici:"network","node-fetch":"network",got:"network",ky:"network",superagent:"network",ws:"network",process:"process","node:process":"process",child_process:"process","node:child_process":"process","@prisma/client":"persistence",prisma:"persistence",pg:"persistence",mysql:"persistence",mysql2:"persistence",mongodb:"persistence",mongoose:"persistence",sqlite3:"persistence","better-sqlite3":"persistence",redis:"persistence",ioredis:"persistence",typeorm:"persistence",knex:"persistence","drizzle-orm":"persistence",sequelize:"persistence",kysely:"persistence","@supabase/supabase-js":"persistence"}),Pr=Object.freeze({process:Object.freeze(["process","node:process"])});function Pt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=xr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=xr[r];if(o)return o;let i=e.indexOf("/",n+1);return i<0?null:xr[e.slice(0,i)]??null}s(Pt,"capabilityForModuleSpecifier");function ve(e,t){for(let n of t)if(Pr[n]?.includes(e))return n;return null}s(ve,"forbiddenGlobalForModuleSpecifier");function Mn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=_r[r];if(o)return o}return null}s(Mn,"capabilityForAmbientName");function st(e){if(e?.pure===!0)return[...Or].sort();let n=(e?.capabilities?.deny??[]).filter(r=>Or.includes(r));return[...new Set(n)].sort()}s(st,"effectiveCapabilityDeny");function _t(e,t){if(t.length===0)return!1;let n=new Set(t),r=e.split(".");for(let o=r.length;o>=1;o-=1)if(n.has(r.slice(0,o).join(".")))return!0;return!1}s(_t,"ambientCoveredByForbiddenGlobals");function $n(e){let t=new Set,n=new Set,r=Object.keys(_r);for(let o of e?.forbiddenGlobals??[]){let i=r.filter(a=>a===o||a.startsWith(`${o}.`));if(i.length===0)n.add(o);else for(let a of i)t.add(`ambient:${a}`);for(let a of Pr[o]??[])t.add(`import-exact:${a}`)}for(let o of st(e)){if(t.add(`import:${o}`),o==="process")for(let i of Pr.process)t.add(`import-exact:${i}`);for(let i of r)Mn(i)===o&&t.add(`ambient:${i}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}s($n,"loweredLayerCoverage");function at(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}s(at,"literalText");function xi(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}s(xi,"lineOf");function wi(e,t){if(e.isImportDeclaration(t)){let r=t.importClause;if(!r)return!1;if(r.isTypeOnly)return!0;let o=r.namedBindings;return!!(o&&e.isNamedImports(o)&&o.elements.length>0&&o.elements.every(i=>i.isTypeOnly))}if(t.isTypeOnly)return!0;let n=t.exportClause;return!!(n&&e.isNamedExports(n)&&n.elements.length>0&&n.elements.every(r=>r.isTypeOnly))}s(wi,"isTypeOnlyReference");function Oi(e,t){let n={noLib:!0,noResolve:!0,target:e.ScriptTarget.Latest},r=e.createCompilerHost(n,!0);return r.getSourceFile=o=>o===t.fileName?t:void 0,r.fileExists=o=>o===t.fileName,r.readFile=o=>o===t.fileName?t.text:void 0,e.createProgram([t.fileName],n,r).getTypeChecker()}s(Oi,"singleFileChecker");function Nr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}s(Nr,"symbolAt");function Dr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,i;try{i=o?t.getShorthandAssignmentValueSymbol(r.parent):Nr(t,r)}catch{i=void 0}return!!i?.declarations?.some(a=>a.getSourceFile().fileName===n.fileName)}s(Dr,"localDeclaration");function lt(e,t){let n,r=[],o=s((a,l,c,p=!1)=>r.push({specifier:c,kind:l,line:xi(t,a),typeOnly:p,unresolved:c===void 0,node:a}),"add"),i=s(a=>{if(e.isImportDeclaration(a))o(a,"import",at(e,a.moduleSpecifier),wi(e,a));else if(e.isExportDeclaration(a)&&a.moduleSpecifier)o(a,"export",at(e,a.moduleSpecifier),wi(e,a));else if(e.isImportEqualsDeclaration(a)&&e.isExternalModuleReference(a.moduleReference))o(a,"require",at(e,a.moduleReference.expression),a.isTypeOnly===!0);else if(e.isCallExpression(a)){let l=a.expression.kind===e.SyntaxKind.ImportKeyword,p=e.isIdentifier(a.expression)&&a.expression.text==="require"&&!Dr(e,n??(n=Oi(e,t)),t,a.expression);(l||p)&&o(a,p?"require":"dynamic-import",at(e,a.arguments[0]))}e.forEachChild(a,i)},"visit");return i(t),r}s(lt,"extractSemanticDependencies");function Wa(e,t){let n=[],r=t;for(;e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r);){if(e.isPropertyAccessExpression(r))n.unshift(r.name.text);else{let o=at(e,r.argumentExpression);if(o===void 0)return;n.unshift(o)}r=r.expression}if(e.isIdentifier(r))return n.unshift(r.text),{root:r,segments:n}}s(Wa,"staticAccessPath");function za(e,t){let n=t.parent;return e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n)?!1:e.isExpressionNode(t)&&!e.isInTypeQuery(t)||e.isShorthandPropertyAssignment(n)&&n.name===t}s(za,"runtimeIdentifierReference");function Ci(e,t){let n=t[0]==="globalThis"?t.slice(1):t;for(let r=n.length;r>=1;r-=1){let o=n.slice(0,r).join(".");if(e.has(o))return o}}s(Ci,"bestForbiddenMatch");function ct(e,t,n){if(n.length===0)return[];let r=new Set(n),o=Oi(e,t),i=new Map,a=new Set;for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations)e.isIdentifier(f.name)&&a.add(f.name.text);let l=s(u=>{let f=Wa(e,u);if(!f)return;let m=Nr(o,f.root),y=m?i.get(m):void 0;return y?[...y,...f.segments.slice(1)]:Dr(e,o,t,f.root)||a.has(f.root.text)?void 0:f.segments},"resolvePath");for(let u of t.statements)if(e.isVariableStatement(u))for(let f of u.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let m=l(f.initializer),y=Nr(o,f.name);!m||!y||i.set(y,m)}let c=[],p=new Set,g=s((u,f)=>{let m=xi(t,f),y=`${u}:${f.getStart(t)}`;p.has(y)||(p.add(y),c.push({name:u,line:m,node:f}))},"flag"),h=s(u=>{let f=u.parent&&(e.isPropertyAccessExpression(u.parent)||e.isElementAccessExpression(u.parent))&&u.parent.expression===u;if((e.isPropertyAccessExpression(u)||e.isElementAccessExpression(u))&&!f){let m=l(u),y=m?Ci(r,m):void 0;y&&g(y,u)}else e.isIdentifier(u)&&r.has(u.text)&&za(e,u)&&!Dr(e,o,t,u)&&g(u.text,u);if(e.isVariableDeclaration(u)&&e.isObjectBindingPattern(u.name)&&u.initializer){let m=l(u.initializer);if(m)for(let y of u.name.elements){if(!e.isIdentifier(y.name))continue;let v=y.propertyName?at(e,y.propertyName)??y.propertyName.text:y.name.text,E=Ci(r,[...m,v]);E&&g(E,u.initializer)}}e.forEachChild(u,h)},"visit");return h(t),c}s(ct,"collectForbiddenCapabilityUses");function Lr(e,t,n){let r=[];for(let o of n?.dependencies??lt(e,t)){if(o.typeOnly||!o.specifier)continue;let i=Pt(o.specifier);i&&r.push({capability:i,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??ct(e,t,Tr)){let i=Mn(o.name);i&&r.push({capability:i,symbol:o.name,line:o.line,source:"ambient-global"})}return r.sort((o,i)=>o.line-i.line||o.capability.localeCompare(i.capability)||o.symbol.localeCompare(i.symbol))}s(Lr,"collectCapabilityUses");var Fr={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Mr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function $r(e,t){return t.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:o,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>e.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}s($r,"resolveIntentLayer");function Fe(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}s(Fe,"looksLikeArkIntent");function Tt(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&Fe(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Fr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Fr.PUBLISH_MISSING_SOURCE}),t}s(Tt,"classifyPublishFacts");function j(e,t,n){return{ruleId:e,code:e,message:t,...n}}s(j,"violation");function dt(e,t){return e.slice(0,t).split(`
|
|
22
|
+
`).length}s(dt,"lineOf");var qa=new Set(["publish","subscribe","defineIntent","registerHandler"]);function Ya(e,t){return e.index+e[0].indexOf(t)}s(Ya,"captureIndex");function Xa(e){let t=[],n=new Set,r=s((l,c)=>{!l||n.has(c)||(n.add(c),t.push({value:l,index:c}))},"push"),o=s(l=>{l.lastIndex=0;let c;for(;(c=l.exec(e))!==null;){let p=c[1];p&&r(p,Ya(c,p))}},"pushFrom");o(/\b(?:publish|subscribe|defineIntent|registerHandler)\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\(\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\b(?:intent|onEvent)\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g);let i=/\breactsTo\s{0,8}:\s{0,8}\[([^\]]{0,2000})\]/g,a;for(;(a=i.exec(e))!==null;){let l=a[1]??"",c=a.index+a[0].indexOf(l),p=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,g;for(;(g=p.exec(l))!==null;){let h=g[1];h&&r(h,c+g.index+g[0].indexOf(h))}}return o(/\bmetadata\s{0,8}:\s{0,8}\{[^}]{0,400}\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),o(/\bpublish\s{0,8}(?:<[^>]{0,120}>)?\s{0,8}\([^;]{0,400}?\bsource\s{0,8}:\s{0,8}['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g),t.sort((l,c)=>l.index-c.index)}s(Xa,"extractQuotedStrings");function Za(e){let t=[],n=[{kind:"import",re:/\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g},{kind:"export",re:/\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g},{kind:"dynamic-import",re:/\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g},{kind:"require",re:/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g}];for(let r of n){let o;for(;(o=r.re.exec(e))!==null;){let i=o.index+o[0].indexOf(o[1]),a=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(a)||r.kind==="export"&&/\bexport\s+type\b/.test(a);t.push({value:o[1],index:i,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}s(Za,"extractModuleSpecifiers");function Ja(e,t){return!!(t&&(e.isParenthesizedExpression(t)||e.isAsExpression(t)||typeof e.isTypeAssertionExpression=="function"&&e.isTypeAssertionExpression(t)||typeof e.isSatisfiesExpression=="function"&&e.isSatisfiesExpression(t)))}s(Ja,"isSyntaxWrapper");function Kr(e,t){let n=t;for(;n?.parent&&Ja(e,n.parent);)n=n.parent;return n}s(Kr,"unwrapWrappers");function Hr(e,t){if(!t||!e.isCallExpression(t))return;let n=t.expression;if(e.isIdentifier(n))return n.text;if(e.isPropertyAccessExpression(n))return n.name.text}s(Hr,"callCalleeName");function Qa(e,t){let n=t.parent;if(!n||!e.isObjectLiteralExpression(n))return!1;let r=Kr(e,n),o=r.parent;if(!o)return!1;if(e.isCallExpression(o)&&Hr(e,o)==="publish"){let i=o.arguments;return i[1]===r||i[2]===r}if(e.isPropertyAssignment(o)&&Ur(e,o.name)==="metadata"){let i=o.parent;if(!i)return!1;let l=Kr(e,i).parent;return!!(l&&e.isCallExpression(l)&&Hr(e,l)==="publish")}return!1}s(Qa,"isPublishMetadataSource");function Pi(e,t){let n=Kr(e,t),r=n.parent;if(!r)return!1;if(e.isCallExpression(r)){let o=Hr(e,r);if(o&&qa.has(o)&&r.arguments.some(i=>i===n))return!0}if(e.isArrayLiteralExpression(r))return Pi(e,r);if(e.isPropertyAssignment(r)){let o=Ur(e,r.name);if(o==="intent"||o==="onEvent"||o==="reactsTo"||o==="source"&&Qa(e,r))return!0}return!1}s(Pi,"isDeclaredIntentSite");function el(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=s(i=>{e.isStringLiteralLike(i)&&Pi(e,i)&&r.push({value:i.text,index:i.getStart(n)}),e.forEachChild(i,o)},"visit");return o(n),r}s(el,"extractQuotedStringsAst");function tl(e){let t=e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return["adapter","adapters","infra","infrastructure","persistence","repository","repositories","integration","database","db"].some(n=>t.includes(n))}s(tl,"hasInfrastructureToken");function nl(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}s(nl,"isKnownInfrastructurePackage");function rl(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}s(rl,"layerHasInfrastructureRole");function Dt(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}s(Dt,"tsStringLiteralText");function Ur(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}s(Ur,"tsPropertyName");function _i(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Ur(e,r.name)===n)}s(_i,"tsObjectProperty");function Lt(e,t,n){return _i(e,t,n)!==void 0}s(Lt,"tsObjectHasProperty");function Nt(e,t,n){let r=_i(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}s(Nt,"tsObjectPropertyValue");function ol(e,t){let n=Nt(e,t,"metadata");return Lt(e,n,"source")}s(ol,"tsObjectHasMetadataSource");function Ti(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?Ti(e,t.name):!1:!1}s(Ti,"tsLooksLikeIntentCreatorExpression");function il(e,t){if(!e.isCallExpression(t))return!1;let n=t.expression;return e.isPropertyAccessExpression(n)?n.name.text==="publish":e.isIdentifier(n)&&n.text==="publish"}s(il,"tsIsPublishCall");function sl(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=Dt(e,n);return r!==void 0&&Fe(r)||Lt(e,n,"intent")||Ti(e,n)}s(sl,"tsIsArkPublishCandidate");function al(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return ol(e,n)||Lt(e,r,"source")||Lt(e,o,"source")}s(al,"tsPublishHasSource");function ll(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,i=Nt(e,n,"metadata");return Dt(e,Nt(e,i,"source"))??Dt(e,Nt(e,r,"source"))??Dt(e,Nt(e,o,"source"))}s(ll,"tsPublishSourceLiteral");function cl(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),i=n,a=i?.filePath,l=i?.layer,c=[],p=s(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),g=s(h=>{if(il(e,h)){let u=h.arguments[0],f=Dt(e,u);for(let y of Tt({publishCall:!0,rawIntentName:f,objectHasIntent:Lt(e,u,"intent"),arkPublishCandidate:sl(e,h),hasSource:al(e,h)}))c.push(j(y.ruleId,y.message,{line:p(h),filePath:a}));let m=ll(e,h);if(r&&l&&m&&Fe(m)){let y=r.resolveLayer(m);y&&y!==l&&c.push(j("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${m}" resolves to ${y}, but the target file is classified as ${l}.`,{line:p(h),filePath:a,target:m,fromLayer:l,toLayer:y}))}}e.forEachChild(h,g)},"visit");return g(o),c}s(cl,"analyzePublishAst");function Ni(e={}){let t=new Set((e.intents||[]).map(i=>typeof i=="string"?i:i.name)),n=e.forbiddenPatterns||[],r=new Set(e.infrastructureLayers??[]),o=e.enforceIntentAllowlist??t.size>0;return{validate(i,a){let l=[],c=a,p=c?.filePath,g=c?.layer,h=e.typescript,u=h?h.createSourceFile(p??"generated.ts",i,h.ScriptTarget.Latest,!0):void 0,f=u?lt(e.typescript,u):void 0,m=f?f.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(u),kind:A.kind,typeOnly:A.typeOnly})):Za(i),y=e.typescript?el(e.typescript,i):Xa(i);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(p))for(let A of f?.filter(({unresolved:b})=>b)??[]){let b=A.kind==="require";l.push(j(b?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${b?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:p}))}let v=g!==void 0&&(r.has(g)||rl(g)),E=g!==void 0?` If "${g}" is an infrastructure layer, mark it in ark.config.json with "mayImportInfrastructure": true (or name it with an infra token like Adapters/Persistence/Repository).`:"";for(let A of n)if(A instanceof RegExp){A.lastIndex=0;let b=A.exec(i);A.lastIndex=0,b&&l.push(j("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:b.index===void 0?void 0:dt(i,b.index),filePath:p,suggestion:"Remove infrastructure imports from domain/application layers."+E}))}else i.includes(A)&&l.push(j("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:dt(i,i.indexOf(A)),filePath:p}));for(let A of m){let b=e.resolveImportTarget?.(A.value,p)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,p)}:void 0),w=typeof p=="string"?e.resolveImportTarget?.(p)??(e.resolveImportLayer?{layer:g,relPath:void 0}:void 0):void 0,N=b?.layer;if(N&&g){let I=nt(e.architectureProfile?.rules,g,N,{fromPath:w?.relPath,toPath:b?.relPath,layers:e.architectureLayers});if(I){if(A.typeOnly&&!I.peerIsolation)continue;let T=!!I.peerIsolation;l.push(j("LAYER_IMPORT_VIOLATION",I.message??(T?`Layer "${g}" must not import across slices into "${N}".`:`Layer "${g}" must not import "${N}".`),{line:dt(i,A.index),source:A.value,target:A.value,filePath:p,fromLayer:g,toLayer:N,suggestion:T?"Extract shared code to a shared layer, or coordinate slices via events/ports \u2014 do not import across feature/context slices.":"Depend on a port/interface owned by an inner layer instead, or move this code to a layer allowed to make this import.",details:{importKind:A.kind,peerIsolation:T,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}v||A.typeOnly||!tl(A.value)&&!nl(A.value)||l.push(j("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:dt(i,A.index),source:A.value,target:A.value,filePath:p,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+E,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let b=A.check({source:i,context:a});if(b!==!0)if(Array.isArray(b))for(let w of b)l.push(j("POLICY_VIOLATION",w.message,{filePath:p,suggestion:`Fix violation of policy "${A.name}".`}));else b===!1?l.push(j("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(j("POLICY_VIOLATION",b.message))}if(o&&t.size>0)for(let A of y)Fe(A.value)&&!t.has(A.value)&&l.push(j("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:dt(i,A.index),filePath:p,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&g)for(let A of y){if(!Fe(A.value))continue;let b=e.architectureProfile.resolveLayer(A.value);if(!b)continue;let w=Ne(e.architectureProfile.rules,g,b,{fromPath:typeof p=="string"?p:void 0,layers:e.architectureLayers});if(w){let N=w.rule.peerIsolation?tt(w.peerIsolationReason??"cross-slice",{fromPath:typeof p=="string"?p:void 0,fromSlice:w.fromSlice,toSlice:w.toSlice}):void 0,I=`Layer "${g}" must not reference "${b}" through "${A.value}".`,T=N&&w.peerIsolationReason!=="cross-slice"?`${I} ${N}`:w.rule.message?N?`${w.rule.message} (${N})`:w.rule.message:I;l.push(j("LAYER_REFERENCE_VIOLATION",T,{line:dt(i,A.index),filePath:p,target:A.value,fromLayer:g,toLayer:b,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:w.rule,peerIsolationReason:w.peerIsolationReason}}))}}if(e.extensions)for(let A of e.extensions)try{let b=A.analyze(i,a);l.push(...b)}catch(b){l.push(j("EXTENSION_ERROR",`Extension "${A.name}" failed: ${b instanceof Error?b.message:String(b)}`))}if(e.typescript&&u&&g&&e.forbiddenGlobals?.[g]?.length)try{let A=e.forbiddenGlobals[g];l.push(...ct(e.typescript,u,A).map(b=>j("FORBIDDEN_GLOBAL",`${g} must not use the ambient global "${b.name}".`,{line:b.line,filePath:p,target:b.name,fromLayer:g,suggestion:"Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."})));for(let b of f??[]){if(b.typeOnly||!b.specifier)continue;let w=ve(b.specifier,A);w&&l.push(j("FORBIDDEN_GLOBAL",`${g} must not use module "${b.specifier}" because it is the import form of forbidden global "${w}".`,{line:b.line,filePath:p,source:b.specifier,target:b.specifier,fromLayer:g,details:{importKind:b.kind,forbiddenGlobal:w},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&u&&g&&e.capabilityWalls?.[g]?.length)try{let A=new Set(e.capabilityWalls[g]),b=e.forbiddenGlobals?.[g]??[];for(let w of Lr(e.typescript,u))A.has(w.capability)&&(w.source==="ambient-global"&&_t(w.symbol,b)||w.source==="import-based"&&ve(w.symbol,b)||l.push(j("CAPABILITY_VIOLATION",w.source==="import-based"?`${g} denies the ${w.capability} capability; found import of "${w.symbol}".`:`${g} denies the ${w.capability} capability; found ambient "${w.symbol}".`,{line:w.line,filePath:p,target:w.symbol,capability:w.capability,fromLayer:g,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...cl(e.typescript,i,a,e.architectureProfile))}catch(A){l.push(j("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}return{mode:"lexical-compatibility",completeness:"partial",completenessReasons:["LEXICAL_EVIDENCE_INCOMPLETE"],valid:!1,lexicalValid:l.length===0,violations:l}}}}s(Ni,"createAICodeGate");function W(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a-${(t>>>0).toString(16).padStart(8,"0")}`}s(W,"deterministicHash");function $(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map($).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${$(t[n])}`).join(",")}}`}s($,"stableSerialize");var Me="1.2";var Di=["network","filesystem","clock","randomness","environment","process","persistence"];function B(e,t){let n=$(e),r=$(t);return n<r?-1:n>r?1:0}s(B,"compareCanonical");function z(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}s(z,"sortedUnique");function Ft(e){let t={schemaVersion:"1.2",include:z(e.include??[]),exclude:z(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:z(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:z(n.patterns??[]),exclude:z(n.exclude??[]),forbiddenGlobals:z(n.forbiddenGlobals??[]),intentPrefixes:z(n.intentPrefixes??[]),capabilityDeny:z(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(B),safety:{maxTsSuppressions:e.safety?.maxTsSuppressions??0,maxAnyCasts:e.safety?.maxAnyCasts??0,allowInMemory:e.safety?.allowInMemory===!0,allowDisabledPeerIsolation:e.safety?.allowDisabledPeerIsolation===!0},...e.arkRun?{arkRun:{mode:e.arkRun.mode,compositionRoots:z(e.arkRun.compositionRoots),managedLayers:z(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return W($(t))}s(Ft,"resolvedFactsEvidenceRequirementsHash");function dl(e){let t=e.completenessReasons.map(I=>({code:I.code,message:I.message,...I.file?{file:I.file}:{}})).sort(B),n=e.files.map(I=>({...I,typeOnlyExportNames:z(I.typeOnlyExportNames)})).sort((I,T)=>I.path<T.path?-1:I.path>T.path?1:0),r=e.dependencies.map(I=>({...I,...I.namedBindings?{namedBindings:z(I.namedBindings)}:{}})).sort(B),o=e.capabilityUses.map(I=>({...I})).sort(B),i=e.ambientUses.map(I=>({...I})).sort(B),a=e.publishCalls.map(I=>({...I})).sort(B),l=e.intentReferences.map(I=>({...I})).sort(B),c=e.safetyUses.map(I=>({...I})).sort(B),p=(e.classShapes??[]).map(I=>({...I,mutatingMethods:[...I.mutatingMethods??[]].map(T=>({...T}))})).sort(B),g=(e.arkRunKernelCalls??[]).map(I=>({...I})).sort(B),h=(e.arkRunManagedNews??[]).map(I=>({...I})).sort(B),u=(e.arkRunCompositionRootHits??[]).map(I=>({...I})).sort(B),f=(e.arkRunDeclarations??[]).map(I=>({...I,uses:z(I.uses),reactsTo:z(I.reactsTo),raises:z(I.raises),sends:z(I.sends)})).sort(B),m=(e.arkOrderPlaneCalls??[]).map(I=>({...I})).sort(B),y=(e.arkOrderGenericUpdates??[]).map(I=>({...I})).sort(B),v=(e.arkOrderRootHits??[]).map(I=>({...I})).sort(B),E=(e.arkOrderXiFieldWrites??[]).map(I=>({...I})).sort(B),A=(e.arkOrderIngestWritesXi??[]).map(I=>({...I})).sort(B),b=(e.arkOrderReleaseKeyCounts??[]).map(I=>({...I})).sort(B),w=e.files.map(({path:I,contentHash:T})=>({path:I,contentHash:T})).sort((I,T)=>I.path<T.path?-1:I.path>T.path?1:0),N=W($(w));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:N,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:i,publishCalls:a,intentReferences:l,safetyUses:c,classShapes:p,arkRunKernelCalls:g,arkRunManagedNews:h,arkRunCompositionRootHits:u,arkRunDeclarations:f,arkOrderPlaneCalls:m,arkOrderGenericUpdates:y,arkOrderRootHits:v,arkOrderXiFieldWrites:E,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:b}}s(dl,"canonicalResolvedFactsInput");function Li(e){let t=dl(e);return{...t,factsHash:W($(t))}}s(Li,"createCanonicalResolvedCandidateFacts");function Gr(e){return Li(Mi(F(e,"$"),!1))}s(Gr,"createResolvedCandidateFacts");function F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}s(F,"asRecord");function K(e,t,n){let r=new Set(t),o=Object.keys(e).find(i=>!r.has(i));if(o)throw new Error(`${n}.${o} is not part of schema ${"1.2"}.`)}s(K,"assertOnlyKeys");function L(e,t,n){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`${n}.${t} must be a non-empty string.`);return r}s(L,"requiredText");function he(e,t,n){if(e[t]!==void 0)return L(e,t,n)}s(he,"optionalText");function H(e,t,n){let r=L(e,t,n),o=r.replace(/\\/g,"/");if(!o||o.startsWith("/")||/^[A-Za-z]:\//.test(o)||/[\u0000-\u001f\u007f]/.test(o))throw new Error(`${n}.${t} must be a canonical project-relative path.`);let i=[];for(let l of o.split("/"))if(!(!l||l==="."))if(l===".."){if(i.length===0)throw new Error(`${n}.${t} must be a canonical project-relative path.`);i.pop()}else i.push(l);let a=i.join("/");if(!a||a!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return a}s(H,"requiredProjectPath");function U(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}s(U,"requiredBoolean");function Fi(e,t,n){let r=e[t];if(!Number.isInteger(r)||Number(r)<0)throw new Error(`${n}.${t} must be a non-negative integer.`);return Number(r)}s(Fi,"requiredInteger");function Y(e,t,n){let r=Fi(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}s(Y,"requiredPositiveInteger");function G(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}s(G,"requiredArray");function Re(e,t,n,r){let o=e[t];if(typeof o!="string"||!n.includes(o))throw new Error(`${r}.${t} must be one of ${n.join(", ")}.`);return o}s(Re,"enumValue");function ut(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!n))throw new Error(`${t} must be an array of non-empty strings.`);return[...e]}s(ut,"parseStringArray");function ul(e,t,n){let r=new Set;for(let o of e){let i=t(o);if(r.has(i))throw new Error(`${n} must not contain duplicate facts (${i}).`);r.add(i)}}s(ul,"assertUnique");function Mi(e,t){K(e,["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","evidenceRequirementsHash","projectPackageName","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","classShapes","arkRunKernelCalls","arkRunManagedNews","arkRunCompositionRootHits","arkRunDeclarations","arkOrderPlaneCalls","arkOrderGenericUpdates","arkOrderRootHits","arkOrderXiFieldWrites","arkOrderIngestWritesXi","arkOrderReleaseKeyCounts",...t?["candidateTreeHash","factsHash"]:[]],"$");let n=Re(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=Re(e,"completeness",["complete","partial","unavailable"],"$"),o=G(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=F(S,R);K(d,["code","message","file"],R);let _=d.file===void 0?void 0:H(d,"file",R);return{code:L(d,"code",R),message:L(d,"message",R),..._?{file:_}:{}}});if(r==="complete"&&o.length>0)throw new Error("$.completenessReasons must be empty when completeness is complete.");if(r!=="complete"&&o.length===0)throw new Error("$.completenessReasons must explain partial or unavailable facts.");let i=G(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=F(S,R);return K(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:H(d,"path",R),contentHash:L(d,"contentHash",R),parseStatus:Re(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:Fi(d,"parseDiagnosticCount",R),exportsOnlyTypes:U(d,"exportsOnlyTypes",R),typeOnlyExportNames:ut(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:U(d,"hasTopLevelSideEffects",R)}}),a=G(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=F(S,R);K(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let _=he(d,"specifier",R),M=he(d,"target",R),oe=Re(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(oe==="resolved-project"&&!M)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(oe!=="resolved-project"&&M)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(oe!=="dynamic"&&!_)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:H(d,"from",R),..._?{specifier:_}:{},kind:Re(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:U(d,"typeOnly",R),line:Y(d,"line",R),resolution:oe,...M?{target:H(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:ut(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:U(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:U(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:U(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:U(d,"portProofEligible",R)}:{}}}),l=G(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=F(S,R);return K(d,["file","line","symbol","capability","source"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:L(d,"symbol",R),capability:Re(d,"capability",Di,R),source:Re(d,"source",["ambient-global","import-based"],R)}}),c=G(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=F(S,R);return K(d,["file","line","symbol"],R),{file:H(d,"file",R),line:Y(d,"line",R),symbol:L(d,"symbol",R)}}),p=G(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=F(S,R);K(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let _=he(d,"rawIntentName",R),M=he(d,"sourceIntent",R);return{file:H(d,"file",R),line:Y(d,"line",R),..._?{rawIntentName:_}:{},objectHasIntent:U(d,"objectHasIntent",R),arkPublishCandidate:U(d,"arkPublishCandidate",R),hasSource:U(d,"hasSource",R),...M?{sourceIntent:M}:{}}}),g=G(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=F(S,R);return K(d,["file","line","intent"],R),{file:H(d,"file",R),line:Y(d,"line",R),intent:L(d,"intent",R)}}),h=G(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=F(S,R);K(d,["file","line","kind","symbol"],R);let _=he(d,"symbol",R),M=Re(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(M==="in-memory-store"&&!_)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(M!=="in-memory-store"&&_)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:H(d,"file",R),line:Y(d,"line",R),kind:M,..._?{symbol:_}:{}}});ul(i,S=>S.path,"$.files");let u=new Set(i.map(S=>S.path));for(let S of i){if(S.parseStatus==="parsed"&&S.parseDiagnosticCount!==0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be 0 when parseStatus is parsed.`);if(S.parseStatus==="invalid"&&S.parseDiagnosticCount===0)throw new Error(`$.files[${S.path}].parseDiagnosticCount must be positive when parseStatus is invalid.`)}if(r==="complete"&&i.some(S=>S.parseStatus==="invalid"))throw new Error("$.completeness cannot be complete when a candidate file failed to parse.");for(let S of a)if(!u.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let m=(e.arkRunKernelCalls===void 0?[]:G(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=F(S,R);K(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let _=he(d,"receiver",R),M=he(d,"nameLiteral",R);return{file:H(d,"file",R),line:Y(d,"line",R),kind:Re(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:L(d,"callee",R),viaImport:U(d,"viaImport",R),..._?{receiver:_}:{},...M?{nameLiteral:M}:{}}}),v=(e.arkRunManagedNews===void 0?[]:G(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=F(S,R);K(d,["file","line","typeName","importedFrom"],R);let _=he(d,"importedFrom",R);return{file:H(d,"file",R),line:Y(d,"line",R),typeName:L(d,"typeName",R),..._?{importedFrom:_}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:G(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=F(S,R);return K(d,["file","matchedRoot","hasKernelFactory"],R),{file:H(d,"file",R),matchedRoot:L(d,"matchedRoot",R),hasKernelFactory:U(d,"hasKernelFactory",R)}}),b=e.arkRunDeclarations===void 0?[]:G(e,"arkRunDeclarations","$"),N=(e.arkOrderPlaneCalls===void 0?[]:G(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=F(S,R);return K(d,["file","line","callee"],R),{file:H(d,"file",R),line:Y(d,"line",R),callee:L(d,"callee",R)}}),T=(e.arkOrderGenericUpdates===void 0?[]:G(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=F(S,R);return K(d,["file","line","method"],R),{file:H(d,"file",R),line:Y(d,"line",R),method:L(d,"method",R)}}),ge=(e.arkOrderRootHits===void 0?[]:G(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=F(S,R);return K(d,["file","matchedRoot","hasPlaneFactory"],R),{file:H(d,"file",R),matchedRoot:L(d,"matchedRoot",R),hasPlaneFactory:U(d,"hasPlaneFactory",R)}}),D=(e.arkOrderXiFieldWrites===void 0?[]:G(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=F(S,R);return K(d,["file","line","key"],R),{file:H(d,"file",R),line:Y(d,"line",R),key:L(d,"key",R)}}),X=(e.arkOrderIngestWritesXi===void 0?[]:G(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=F(S,R);return K(d,["file","line"],R),{file:H(d,"file",R),line:Y(d,"line",R)}}),kt=(e.arkOrderReleaseKeyCounts===void 0?[]:G(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=F(S,R);return K(d,["file","line","keyCount"],R),{file:H(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),It=b.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=F(S,R);return K(d,["file","line","uses","reactsTo","raises","sends"],R),{file:H(d,"file",R),line:Y(d,"line",R),uses:ut(d.uses,`${R}.uses`),reactsTo:ut(d.reactsTo,`${R}.reactsTo`),raises:ut(d.raises,`${R}.raises`),sends:ut(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",p],["$.intentReferences",g],["$.safetyUses",h],["$.arkRunKernelCalls",m],["$.arkRunManagedNews",v],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",It],["$.arkOrderPlaneCalls",N],["$.arkOrderGenericUpdates",T],["$.arkOrderRootHits",ge],["$.arkOrderXiFieldWrites",D],["$.arkOrderIngestWritesXi",X],["$.arkOrderReleaseKeyCounts",kt]])for(let R of C)if(!u.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Pe=he(e,"projectPackageName","$"),pr=(e.classShapes===void 0?[]:G(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=F(S,R);K(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let _=G(d,"mutatingMethods",R).map((M,oe)=>{let un=`${R}.mutatingMethods[${oe}]`,fr=F(M,un);return K(fr,["name","referencesGuardOrPublish"],un),{name:L(fr,"name",un),referencesGuardOrPublish:U(fr,"referencesGuardOrPublish",un)}});return{file:H(d,"file",R),className:L(d,"className",R),exported:U(d,"exported",R),hasPublicMutableFields:U(d,"hasPublicMutableFields",R),hasPublicSetters:U(d,"hasPublicSetters",R),hasPublicConstructor:U(d,"hasPublicConstructor",R),hasStaticFactory:U(d,"hasStaticFactory",R),mutatingMethods:_,...d.dataOnly===void 0?{}:{dataOnly:U(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:L(e,"resolverIdentity","$"),compilerIdentity:L(e,"compilerIdentity","$"),compilerOptionsHash:L(e,"compilerOptionsHash","$"),tsconfigHash:L(e,"tsconfigHash","$"),evidenceRequirementsHash:L(e,"evidenceRequirementsHash","$"),...Pe?{projectPackageName:Pe}:{},files:i,dependencies:a,capabilityUses:l,ambientUses:c,publishCalls:p,intentReferences:g,safetyUses:h,classShapes:pr,arkRunKernelCalls:m,arkRunManagedNews:v,arkRunCompositionRootHits:A,arkRunDeclarations:It,arkOrderPlaneCalls:N,arkOrderGenericUpdates:T,arkOrderRootHits:ge,arkOrderXiFieldWrites:D,arkOrderIngestWritesXi:X,arkOrderReleaseKeyCounts:kt}}s(Mi,"parseResolvedFactsInput");function Se(e){let t=F(e,"$"),n=L(t,"factsHash","$"),r=L(t,"candidateTreeHash","$"),o=Li(Mi(t,!0));if(o.factsHash!==n)throw new Error(`$.factsHash does not match the canonical payload (${o.factsHash}).`);if(r!==o.candidateTreeHash)throw new Error(`$.candidateTreeHash does not match the canonical file tree (${o.candidateTreeHash}).`);return o}s(Se,"loadResolvedCandidateFacts");var pl=["network","filesystem","clock","randomness","environment","process","persistence"],O={type:"string",minLength:1},Z={type:"integer",minimum:1},V={type:"string",minLength:1,pattern:"^(?!/)(?![A-Za-z]:/)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*[\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"},Vr={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://unpkg.com/arkgate@3/schemas/ark.resolved-candidate-facts.schema.json",title:"ArkGate resolved candidate facts",type:"object",additionalProperties:!1,required:["schemaVersion","completeness","completenessReasons","resolverIdentity","compilerIdentity","compilerOptionsHash","tsconfigHash","candidateTreeHash","evidenceRequirementsHash","files","dependencies","capabilityUses","ambientUses","publishCalls","intentReferences","safetyUses","factsHash"],properties:{schemaVersion:{enum:["1.0","1.1","1.2"]},completeness:{enum:["complete","partial","unavailable"]},completenessReasons:{type:"array",items:{type:"object",additionalProperties:!1,required:["code","message"],properties:{code:O,message:O,file:V}}},resolverIdentity:O,compilerIdentity:O,compilerOptionsHash:O,tsconfigHash:O,candidateTreeHash:O,evidenceRequirementsHash:O,projectPackageName:O,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:V,contentHash:O,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:O},hasTopLevelSideEffects:{type:"boolean"}},allOf:[{if:{properties:{parseStatus:{const:"parsed"}}},then:{properties:{parseDiagnosticCount:{const:0}}}},{if:{properties:{parseStatus:{const:"invalid"}}},then:{properties:{parseDiagnosticCount:{minimum:1}}}}]}},dependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["from","kind","typeOnly","line","resolution"],properties:{from:V,specifier:O,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:Z,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:V,namedBindings:{type:"array",items:O},targetTypeOnlyExports:{type:"boolean"},sourcePureTypeModule:{type:"boolean"},namedBindingsTypeOnly:{type:"boolean"},portProofEligible:{type:"boolean"}},allOf:[{if:{properties:{resolution:{const:"resolved-project"}}},then:{required:["target"]},else:{not:{required:["target"]}}},{if:{properties:{resolution:{const:"dynamic"}}},else:{required:["specifier"]}}]}},capabilityUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol","capability","source"],properties:{file:V,line:Z,symbol:O,capability:{enum:pl},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:V,line:Z,symbol:O}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:V,line:Z,rawIntentName:O,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:O}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:V,line:Z,intent:O}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:V,line:Z,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:O},allOf:[{if:{properties:{kind:{const:"in-memory-store"}}},then:{required:["symbol"]},else:{not:{required:["symbol"]}}}]}},classShapes:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods"],properties:{file:V,className:O,exported:{type:"boolean"},hasPublicMutableFields:{type:"boolean"},hasPublicSetters:{type:"boolean"},hasPublicConstructor:{type:"boolean"},hasStaticFactory:{type:"boolean"},dataOnly:{type:"boolean"},mutatingMethods:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","referencesGuardOrPublish"],properties:{name:O,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:V,line:Z,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:O,viaImport:{type:"boolean"},receiver:O,nameLiteral:O}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:V,line:Z,typeName:O,importedFrom:O}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:V,matchedRoot:O,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:V,line:Z,uses:{type:"array",items:O},reactsTo:{type:"array",items:O},raises:{type:"array",items:O},sends:{type:"array",items:O}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:V,line:Z,callee:O}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:V,line:Z,method:O}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:V,matchedRoot:O,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:V,line:Z,key:O}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:V,line:Z}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:V,line:Z,keyCount:{type:"integer",minimum:1}}}},factsHash:O},allOf:[{if:{properties:{completeness:{const:"complete"}}},then:{properties:{completenessReasons:{maxItems:0},files:{items:{properties:{parseStatus:{const:"parsed"}}}}}}},{if:{properties:{completeness:{enum:["partial","unavailable"]}}},then:{properties:{completenessReasons:{minItems:1}}}}]};var jr="1.0";function te(e){return`${e.from}->${e.to}`}s(te,"dependencyKey");function Mt(e,t,n,r="dependency"){return{id:`${e}:${r}:${te(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${te(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${te(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${te(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${te(t)} from the candidate, then preflight again.`}:{}}}s(Mt,"dependencyFinding");function pt(e){let t=[],n=new Map(e.changeMap.map.files.map(u=>[u.path,u])),r=new Map(e.changes.map(u=>[u.path,u])),o=new Map(e.changeMap.map.dependencies.map(u=>[te(u),u])),i=new Map(e.baseDependencies.map(u=>[te(u),u])),a=new Map(e.candidateDependencies.map(u=>[te(u),u]));for(let u of[...n.values()].sort((f,m)=>f.path.localeCompare(m.path))){let f=r.get(u.path);f?f.operation!==u.operation?t.push({id:`contradictory:file:${u.path}`,classification:"contradictory",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} was planned as ${u.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${u.path} to the planned ${u.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${u.path}`,classification:"satisfied",subject:"file",path:u.path,expectedOperation:u.operation,actualOperation:f.operation,message:`${u.path} matches the planned ${u.operation} operation.`}):t.push({id:`missing:file:${u.path}`,classification:"missing",subject:"file",path:u.path,expectedOperation:u.operation,message:`${u.path} was planned as ${u.operation} but is absent from the actual change.`,nextAction:`${u.operation[0].toUpperCase()}${u.operation.slice(1)} ${u.path} in the complete change set, then preflight again.`})}for(let u of[...r.values()].sort((f,m)=>f.path.localeCompare(m.path)))n.has(u.path)||t.push({id:`unplanned:file:${u.path}`,classification:"unplanned",subject:"file",path:u.path,actualOperation:u.operation,message:`${u.path} has an unplanned ${u.operation} operation.`,nextAction:`Remove ${u.path} from the change set, then preflight again.`});let l=new Set;for(let u of[...o.values()].sort((f,m)=>te(f).localeCompare(te(m)))){if(a.has(te(u))){t.push(Mt("satisfied",u,`${u.from} -> ${u.to} exists in the candidate architecture.`));continue}let f={from:u.to,to:u.from};a.has(te(f))?(l.add(te(f)),t.push(Mt("contradictory",u,`${u.from} -> ${u.to} was planned, but the candidate contains the reverse edge.`))):t.push(Mt("missing",u,`${u.from} -> ${u.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[u,f]of[...a].sort(([m],[y])=>m.localeCompare(y)))i.has(u)||o.has(u)||l.has(u)||!c.has(f.from)&&!c.has(f.to)||t.push({...Mt("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let p=new Set(e.changeMap.map.files.filter(u=>u.operation==="delete").map(u=>u.path));for(let[u,f]of[...i].sort(([m],[y])=>m.localeCompare(y)))a.has(u)||p.has(f.from)||p.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...Mt("unplanned",f,`${f.from} -> ${f.to} was removed without a planned file deletion.`,"dependency-removed"),actualOperation:"removed"});let g={satisfied:0,missing:1,contradictory:2,unplanned:3};t.sort((u,f)=>g[u.classification]-g[f.classification]||(u.subject===f.subject?0:u.subject==="file"?-1:1)||u.id.localeCompare(f.id));let h={satisfied:t.filter(u=>u.classification==="satisfied").length,missing:t.filter(u=>u.classification==="missing").length,contradictory:t.filter(u=>u.classification==="contradictory").length,unplanned:t.filter(u=>u.classification==="unplanned").length};return{schemaVersion:"1.0",readOnly:!0,changeMapHash:e.changeMap.hash,structurallyConverged:h.missing===0&&h.contradictory===0&&h.unplanned===0,behavioralCompletion:"not-evaluated",summary:h,findings:t}}s(pt,"analyzeArchitectureConvergence");var $i="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",fl=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Ki={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Vf={$schema:"https://json-schema.org/draft/2020-12/schema",$id:$i,title:"ArkGate ArkRules (intra-layer contract)",description:"Per-layer structure sensors and invariant catalog consumed by the ArkGate Effective Contract.",type:"object",additionalProperties:!1,required:["schemaVersion","layer"],properties:{$schema:{type:"string",minLength:1,default:$i},schemaVersion:{type:"string",const:"1.0",default:"1.0"},layer:{type:"string",minLength:1},structure:{type:"array",default:[],items:{$ref:"#/$defs/structureEntry"}},invariants:{type:"array",default:[],items:{$ref:"#/$defs/invariantEntry"}}},$defs:{structureEntry:{type:"object",additionalProperties:!1,required:["id","sensor"],properties:{id:{type:"string",minLength:1},sensor:{type:"string",enum:[...fl]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ki,description:{type:"string",minLength:1}}},invariantEntry:{type:"object",additionalProperties:!1,required:["id","description"],properties:{id:{type:"string",minLength:1},description:{type:"string",minLength:1},aggregate:{type:"string",minLength:1},coverage:{type:"object",additionalProperties:!1,properties:{test:{type:"boolean"},symbol:{type:"string",minLength:1}}},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Ki}}}};function $t(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}s($t,"emptyEffectiveArkRules");function Br(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}s(Br,"omitLayerDescriptions");function Hi(e){let{stewards:t,...n}=Br(e.config);return{config:n,arkRules:{schemaVersion:e.arkRules.schemaVersion,structure:e.arkRules.structure.map(r=>({id:r.id,sensor:r.sensor,mode:r.mode,appliesTo:r.appliesTo??null,description:r.description??null,provenance:r.provenance})),invariants:e.arkRules.invariants.map(r=>({id:r.id,description:r.description,aggregate:r.aggregate??null,coverage:r.coverage??null,mode:r.mode,appliesTo:r.appliesTo??null,provenance:r.provenance}))}}}s(Hi,"effectiveContractPolicyPayload");function Ui(e,t=!1){if(!e)return"";let n=e.discarded,r=[];if(n.budget>0&&!t&&r.push(`${n.budget} past the ${e.maxFiles}-file budget`),n.noInvariantMention>0&&r.push(`${n.noInvariantMention} naming no catalogued invariant`),n.oversize>0&&r.push(`${n.oversize} over the per-file byte cap`),n.unreadable>0&&r.push(`${n.unreadable} unreadable (files or directories)`),n.depthLimited>0&&r.push(`${n.depthLimited} directories past the walk depth limit`),n.outOfRoot>0&&r.push(`${n.outOfRoot} symlinked outside the project root`),r.length===0)return"";let o=t?"":` (loaded ${e.filesLoaded} files, kept ${e.testFilesRetained} tests)`;return` Scan discarded ${r.join(", ")}${o}.`}s(Ui,"formatCoverageDiscards");function gl(e,t){let n=e.replace(/\\/g,"/").replace(/^\.\//,"");return t.some(r=>{let o=r.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"");return o===""||o==="."?!0:n===o||n.startsWith(`${o}/`)})}s(gl,"isUnderCoverageRoot");function ml(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}s(ml,"titleMatchesInvariant");function yl(e,t){if(!t)return!1;let n=t.split("."),r=n[n.length-1],o=n.length>1?n[0]:null;for(let i of Object.values(e))if(!(o&&!i.includes(o))&&(new RegExp(`(?:function\\s+|\\b)${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[(<]`).test(i)||i.includes(t)))return!0;return!1}s(yl,"symbolPresent");function Gi(e){let t=e.arkRules.invariants??[];if(t.length===0)return{coverage:[],violations:[],partial:!1};let n=e.testFiles??[],r=e.testGlobsMissing===!0||n.length===0,o=e.coverageBudgetExhausted===!0,i=e.coverageStats,a=Ui(i),l=Ui(i,!0),c=i?`coverage file budget exhausted: ${i.filesLoaded} files loaded at the ${i.maxFiles}-file cap, ${i.testFilesRetained} tests retained, ${i.discarded.budget} files discarded at the cap; raise "coverage.maxFiles" in ark.config.json (the cap bounds files RETAINED as evidence${typeof i.filesRead=="number"?`; ${i.filesRead} were read`:""})`:"coverage file budget exhausted",p=(e.coverageRoots??[]).filter(m=>typeof m=="string"&&m.length>0),g=p.length>0,h=p.join(", "),u=[],f=[];for(let m of t){let y=[],v=m.coverage?.test!==!1,E=m.coverage?.symbol,A,b;if(!r&&v){let T;for(let ee of n){let ge=e.fileContents[ee];if(!(!ge||!ml(ge,m.id))){if(!g||gl(ee,p)){A=ee,b=g?!1:void 0;break}T??=ee}}A===void 0&&T!==void 0&&(A=T,b=!0),A!==void 0&&y.push("test-title")}E&&yl(e.fileContents,E)&&y.push("symbol");let N=(m.coverage?.test===!0||!!E||m.coverage===void 0)&&y.length>0||m.coverage?.test===!1&&!E?!0:y.length>0,I=r&&v&&y.length===0;if(u.push({invariantId:m.id,layer:m.provenance.layer,sourceFile:m.provenance.sourceFile,mode:m.mode,covered:N&&!I,evidence:y,partial:I,description:m.description,...A!==void 0?{testEvidenceFile:A}:{},...b!==void 0?{outsideDeclaredRoots:b}:{}}),b===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${m.id} is covered only by ${A}, which is outside the declared coverage roots (${h}). ArkGate matches declared text and never executes tests, so it cannot tell whether that file is run: move the test under a declared root, or add its root to "coverage.coverageRoots" in ark.config.json.`,file:A,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:"warning",failsStrict:!1}),!N||I){let T=m.mode==="enforced"&&!I,ee=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(I?o?`Invariant ${m.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${m.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:ee==="tests-disappeared"?`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (tests-disappeared \u2014 a suite exists). ArkGate matches declared text; it never executes tests.`:`Invariant ${m.id}: no scanned test names it in a describe/it title and no declared symbol was found (never-had-tests \u2014 the scan found no tests at all). ArkGate matches declared text; it never executes tests.`)+(I&&o?l:a),file:m.provenance.sourceFile,line:1,arkruleId:m.id,arkruleSource:m.provenance.sourceFile,fromLayer:m.provenance.layer,severity:T?"error":"warning",failsStrict:T,kind:ee})}}return{coverage:u,violations:f,partial:u.some(m=>m.partial)}}s(Gi,"evaluateInvariantCoverage");function Vi(e){return e?e.partial?{ok:!1,reason:"Coverage is partial (missing test globs); cannot promote until evidence is complete."}:e.covered?e.outsideDeclaredRoots===!0?{ok:!1,reason:`Invariant ${e.invariantId} is covered only by ${e.testEvidenceFile??"a test"}, outside the declared coverage roots; ArkGate cannot tell whether that test runs, so it will not promote on it.`}:{ok:!0,reason:`Invariant ${e.invariantId} has coverage evidence.`}:{ok:!1,reason:`Invariant ${e.invariantId} is uncovered; add a test title or symbol before promoting to enforced.`}:{ok:!1,reason:"No coverage evidence supplied for this invariant; evaluate coverage before promoting to enforced."}}s(Vi,"canPromoteInvariant");var qr="1.0";function P(e,t){e.push({id:`${t.classification}:${t.path}:${t.kind}`,path:t.path,classification:t.classification,message:t.message,...t.classification==="weakening"||t.classification==="judgment-required"?{nextAction:`Restore the previous protection at ${t.path}, then run ArkGate again.`}:{},...t.before===void 0?{}:{before:t.before},...t.after===void 0?{}:{after:t.after}})}s(P,"addFinding");function q(e){return[...new Set(e??[])].sort()}s(q,"sortedUnique");function de(e,t,n,r,o){let i=q(n),a=q(r),l=new Set(i),c=new Set(a),p=a.filter(h=>!l.has(h)),g=i.filter(h=>!c.has(h));p.length===0&&g.length===0||(p.length>0&&P(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:i,after:a}),g.length>0&&P(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:i,after:a}))}s(de,"compareStringSets");function Kt(e,t,n,r,o,i,a){if(n===r)return;P(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?i:a,before:n,after:r})}s(Kt,"compareBoolean");function Kn(e,t){let n=new Map,r=new Set;for(let o of e){let i=t(o);n.has(i)?r.add(i):n.set(i,o)}return{values:n,duplicates:[...r].sort()}}s(Kn,"keyed");function hl(e,t,n){let r=Kn(t,i=>i.name),o=Kn(n,i=>i.name);(r.duplicates.length>0||o.duplicates.length>0)&&P(e,{kind:"duplicate-layer",path:"$.layers",classification:"judgment-required",message:"Duplicate layer names make policy ownership ambiguous.",before:r.duplicates,after:o.duplicates});for(let i of[...new Set([...r.values.keys(),...o.values.keys()])].sort()){let a=r.values.get(i),l=o.values.get(i),c=`$.layers[${i}]`;if(!a&&l){P(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(a&&!l){P(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:a});continue}if(!a||!l)continue;de(e,`${c}.patterns`,a.patterns,l.patterns,{added:"strengthening",removed:"weakening",addedMessage:"Additional paths are governed by this layer.",removedMessage:"Paths were removed from this layer and may become ungoverned."}),de(e,`${c}.exclude`,a.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let p=$n(a),g=$n(l);de(e,`${c}.forbiddenGlobals`,p.rawGlobals,g.rawGlobals,{added:"strengthening",removed:"weakening",addedMessage:"Additional forbidden globals are enforced in this layer.",removedMessage:"A forbidden-global protection was removed from this layer."}),de(e,`${c}.capabilities`,p.atoms,g.atoms,{added:"strengthening",removed:"weakening",addedMessage:"Additional ambient/import protection is enforced in this layer (coverage atoms).",removedMessage:"An ambient/import protection was lost from this layer (coverage atoms)."}),q(a.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&P(e,{kind:"intent-prefixes-changed",path:`${c}.intentPrefixes`,classification:"judgment-required",message:"Intent ownership changed and must be reviewed against publishers and consumers.",before:q(a.intentPrefixes),after:q(l.intentPrefixes)}),Kt(e,`${c}.mayImportInfrastructure`,a.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),Kt(e,`${c}.optional`,a.optional===!0,l.optional===!0,"weakening","The layer is now optional and can be absent without a strict warning.","The layer is now required when its contract is active.")}}s(hl,"compareLayers");function Rl(e,t,n){let r=s(a=>`${a.from}->${a.to}`,"keyOf"),o=Kn(t,r),i=Kn(n,r);(o.duplicates.length>0||i.duplicates.length>0)&&P(e,{kind:"duplicate-rule",path:"$.rules",classification:"judgment-required",message:"Duplicate rule edges make the effective verdict order-dependent.",before:o.duplicates,after:i.duplicates});for(let a of[...new Set([...o.values.keys(),...i.values.keys()])].sort()){let l=o.values.get(a),c=i.values.get(a),p=`$.rules[${a}]`;if(!l&&c){c.allowed===!1&&P(e,{kind:"deny-added",path:p,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&P(e,{kind:"deny-removed",path:p,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&P(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${p}.allowed`,classification:c.allowed?"weakening":"strengthening",message:c.allowed?"A previously denied dependency edge is now allowed.":"A dependency edge is now denied.",before:l.allowed,after:c.allowed});let g=l.peerIsolation===!0,h=c.peerIsolation===!0;if(g!==h){let u=l.from===l.to&&c.from===c.to;P(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${p}.peerIsolation`,classification:u?h?"strengthening":"weakening":"judgment-required",message:u?h?"Cross-slice dependencies inside this layer are now denied.":"Cross-slice dependencies inside this layer are no longer denied.":"Changing peer isolation on a cross-layer edge changes the denial scope.",before:g,after:h})}q(l.sliceFolders).join("\0")!==q(c.sliceFolders).join("\0")&&P(e,{kind:"slice-folders-changed",path:`${p}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!g&&!h)&&(Bi(e,`${p}.sharedRoots`,"shared-roots",q(l.sharedRoots),q(c.sharedRoots),"Roots declared shared are exempt from the peerIsolation unclassifiable denial.","Roots are no longer declared shared and fall back to the peerIsolation denial."),Bi(e,`${p}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(ji)),q((c.allowedCrossSlice??[]).map(ji)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}s(Rl,"compareRules");function ji(e){return JSON.stringify([e.from,e.to])}s(ji,"crossSliceKey");function Bi(e,t,n,r,o,i,a){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(g=>!r.includes(g)),c=r.filter(g=>!o.includes(g)),p=l.length>0&&c.length>0;P(e,{kind:p?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:p?"judgment-required":l.length>0?"weakening":"strengthening",message:p?`${i} Entries were added and removed in the same change.`:l.length>0?i:a,before:r,after:o})}s(Bi,"compareDeclaredExceptions");function Al(e,t,n){let r=t.safety??{},o=n.safety??{};for(let i of["maxTsSuppressions","maxAnyCasts"]){let a=r[i]??0,l=o[i]??0;a!==l&&P(e,{kind:l>a?"threshold-raised":"threshold-lowered",path:`$.safety.${i}`,classification:l>a?"weakening":"strengthening",message:l>a?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:a,after:l})}for(let i of["allowInMemory","allowDisabledPeerIsolation"])Kt(e,`$.safety.${i}`,r[i]===!0,o[i]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}s(Al,"compareSafety");function Wr(e){return e.mode==="enforced"?"enforced":"advisory"}s(Wr,"arkRunMode");function zr(e){return e.mode==="enforced"?"enforced":"advisory"}s(zr,"arkOrderMode");function kl(e,t,n){let r=t.arkOrder,o=n.arkOrder,i="$.arkOrder";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkorder-added",path:i,classification:"strengthening",message:`ArkOrder extra was added (${zr(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkorder-removed",path:i,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let a=zr(r),l=zr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkorder-promoted":"arkorder-demoted",path:`${i}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkOrder extra was promoted to enforced.":"ArkOrder extra was demoted to advisory.",before:a,after:l})}de(e,`${i}.planeRoots`,r.planeRoots,o.planeRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkOrder plane roots are governed.",removedMessage:"ArkOrder plane roots were removed and may skip the plane."}),de(e,`${i}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkOrder.",removedMessage:"Layers were removed from ArkOrder management."})}s(kl,"compareArkOrder");function Il(e,t,n){let r=t.arkRun,o=n.arkRun,i="$.arkRun";if(!r&&!o)return;if(!r&&o){P(e,{kind:"arkrun-added",path:i,classification:"strengthening",message:`ArkRun extra was added (${Wr(o)}).`,after:o});return}if(r&&!o){P(e,{kind:"arkrun-removed",path:i,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let a=Wr(r),l=Wr(o);if(a!==l){let c=a==="advisory"&&l==="enforced";P(e,{kind:c?"arkrun-promoted":"arkrun-demoted",path:`${i}.mode`,classification:c?"strengthening":"weakening",message:c?"ArkRun extra was promoted to enforced.":"ArkRun extra was demoted to advisory.",before:a,after:l})}de(e,`${i}.compositionRoots`,r.compositionRoots,o.compositionRoots,{added:"strengthening",removed:"weakening",addedMessage:"Additional ArkRun composition roots are governed.",removedMessage:"ArkRun composition roots were removed and may skip the kernel."}),de(e,`${i}.managedLayers`,r.managedLayers,o.managedLayers,{added:"strengthening",removed:"weakening",addedMessage:"Additional layers are managed by ArkRun.",removedMessage:"Layers were removed from ArkRun management."}),Kt(e,`${i}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}s(Il,"compareArkRun");function bl(e){return e.some(t=>t.classification==="weakening")?"weakening":e.some(t=>t.classification==="judgment-required")?"judgment-required":e.some(t=>t.classification==="strengthening")?"strengthening":"neutral"}s(bl,"overallClassification");function Wi(e,t){return`${e}::${t}`}s(Wi,"ruleKey");function zi(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Wi(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Wi(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}s(zi,"indexEffectiveRules");function El(e,t,n,r,o,i){let a=new Map((i??[]).map(u=>[u.invariantId,u])),l=t.arkRules??{},c=n.arkRules??{},p=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let u of p){let f=l[u],m=c[u],y=`$.arkRules[${u}]`;if(f===void 0&&m!==void 0){P(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${u} was added.`,after:m});continue}if(f!==void 0&&m===void 0){P(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${u} was removed.`,before:f});continue}f!==m&&P(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${u} changed; verify the effective rules still match intent.`,before:f,after:m})}let g=zi(r),h=zi(o);for(let u of[...new Set([...g.structure.keys(),...h.structure.keys()])].sort()){let f=g.structure.get(u),m=h.structure.get(u),y=`$.arkRules.structure[${u}]`;if(!f&&m){P(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${m.id} was added (${m.mode}).`,after:m});continue}if(f&&!m){P(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!m)){if(f.mode!==m.mode){let v=f.mode==="advisory"&&m.mode==="enforced";P(e,{kind:v?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:v?"strengthening":"weakening",message:v?`Structure ArkRule ${m.id} was promoted to enforced.`:`Structure ArkRule ${m.id} was demoted to advisory.`,before:f.mode,after:m.mode})}f.sensor!==m.sensor&&P(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${m.id} changed sensor identity.`,before:f.sensor,after:m.sensor})}}for(let u of[...new Set([...g.invariants.keys(),...h.invariants.keys()])].sort()){let f=g.invariants.get(u),m=h.invariants.get(u),y=`$.arkRules.invariants[${u}]`;if(!f&&m){P(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${m.id} was added (${m.mode}).`,after:m});continue}if(f&&!m){P(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!m)&&f.mode!==m.mode)if(f.mode==="advisory"&&m.mode==="enforced"){let E=a?.get(m.id),A=Vi(E);A.ok?P(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${m.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:m.mode}):P(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${m.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:m.mode})}else P(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${m.id} was demoted to advisory.`,before:f.mode,after:m.mode})}}s(El,"compareArkRules");function Yr(e,t,n){let r=[];de(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),de(r,"$.exclude",e.exclude,t.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional project paths are excluded from governance.",removedMessage:"Fewer project paths are excluded from governance."}),de(r,"$.dynamicImportAllowlist",e.dynamicImportAllowlist,t.dynamicImportAllowlist,{added:"weakening",removed:"strengthening",addedMessage:"Additional files may use non-literal dynamic imports.",removedMessage:"Fewer files may use non-literal dynamic imports."}),Kt(r,"$.excludeGenerated",e.excludeGenerated!==!1,t.excludeGenerated!==!1,"weakening","Generated source is now excluded from governance.","Generated source is now governed.");let o={off:0,soft:1,"framework-soft":1,strict:2},i=e.cyclePolicy??"strict",a=t.cyclePolicy??"strict";if(i!==a){let l=o[a]===o[i]?"judgment-required":o[a]>o[i]?"strengthening":"weakening";P(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:i,after:a})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&P(r,{kind:"framework-overlay-changed",path:"$.frameworkOverlay",classification:"judgment-required",message:"The framework overlay changed and may alter effective layer matching.",before:e.frameworkOverlay??null,after:t.frameworkOverlay??null}),hl(r,e.layers,t.layers),Rl(r,e.rules,t.rules),Al(r,e,t),El(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Il(r,e,t),kl(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:qr,classification:bl(r),findings:r}}s(Yr,"classifyArkPolicyDelta");function Xr(e,t){if(!e||e.schemaVersion!==qr||typeof e.basePolicyHash!="string"||typeof e.candidatePolicyHash!="string"||typeof e.reason!="string"||!Array.isArray(e.findingIds)||e.findingIds.some(o=>typeof o!="string")||e.reason.trim().length===0||e.basePolicyHash!==t.basePolicyHash||e.candidatePolicyHash!==t.candidatePolicyHash)return!1;let n=q(e.findingIds),r=q(t.findingIds);return n.length===r.length&&n.every((o,i)=>o===r[i])}s(Xr,"policyDeltaAcknowledgementMatches");function $e(e){let t=[];for(let n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."&&t.length>0&&t.at(-1)!==".."?t.pop():t.push(n));return t.join("/")}s($e,"normalizePath");function qi(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}s(qi,"isIdentifierStart");function Hn(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}s(Hn,"isIdentifierCharacter");function ne(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}s(ne,"skipWhitespace");function Ht(e,t){let n=e[t];if(n!=="'"&&n!=='"')return;let r=t,o="";for(t+=1;t<e.length;t+=1){let i=e[t];if(i===n)return{value:o,offset:r,excerpt:e.slice(r,t+1)};i==="\\"&&t+1<e.length?(o+=e[t+1],t+=1):o+=i}}s(Ht,"readString");function ae(e,t,n){return e.startsWith(t,n)&&!Hn(e[n-1])&&!Hn(e[n+t.length])}s(ae,"isWordAt");function Yi(e,t){let n=ne(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ne(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!ae(e,"type",n))return!1;let o=ne(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||ae(e,"as",o)||!qi(e[o]))return!1;for(n=o;n<e.length&&Hn(e[n]);)n+=1;if(n=ne(e,n),ae(e,"as",n)){if(n=ne(e,n+2),!qi(e[n]))return!1;for(;n<e.length&&Hn(e[n]);)n+=1}r=!0}return!1}s(Yi,"bracedNamedBindingsAreTypeOnly");function vl(e,t){if(t=ne(e,t+6),e[t]==="(")return Ht(e,ne(e,t+1));let n=!1;if(ae(e,"type",t)){let o=ne(e,t+4);e[o]!==","&&!ae(e,"from",o)&&(n=!0)}else Yi(e,t)&&(n=!0);let r=Xi(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}s(vl,"specifierAfterImport");function Sl(e,t){t=t+6;let n=ne(e,t),r=!1;if(ae(e,"type",n)){let i=ne(e,n+4);(e[i]==="{"||e[i]==="*")&&(r=!0)}else Yi(e,n)&&(r=!0);let o=Xi(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}s(Sl,"specifierAfterExport");function Xi(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(ae(e,"from",t))return Ht(e,ne(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return Ht(e,t);if(t>0&&(ae(e,"import",t)||ae(e,"export",t)))return}}s(Xi,"specifierInStaticStatement");function wl(e,t){for(t+=1;t<e.length;t+=1){let n=e[t];if(n==="\\")t+=1;else if(n==="`")return t}return e.length}s(wl,"skipTemplateLiteral");function Cl(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ne(e,t+7);if(e[r]!=="(")return;r=ne(e,r+1);let o=Ht(e,r);return o?{...o,requireCall:!0}:void 0}s(Cl,"specifierAfterRequire");function xl(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="/"&&e[n+1]==="/"){if(n=e.indexOf(`
|
|
23
|
+
`,n+2),n<0)break;continue}if(r==="/"&&e[n+1]==="*"){let i=e.indexOf("*/",n+2);if(i<0)break;n=i+1;continue}if(r==="`"){n=wl(e,n);continue}if(r==="'"||r==='"'){let i=Ht(e,n);i&&(n=i.offset+i.excerpt.length-1);continue}let o=r==="i"&&ae(e,"import",n)?vl(e,n):r==="e"&&ae(e,"export",n)?Sl(e,n):r==="r"&&ae(e,"require",n)?Cl(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}s(xl,"moduleSpecifiers");function Zi(e,t){let n=[],r=[];for(let o of xl(e.content)){let i=o.value;if(!i.startsWith(".")){if(o.typeOnly)continue;let p=Pt(i);if(!p)continue;let g=e.content.slice(0,o.offset).split(`
|
|
24
|
+
`).length;r.push({file:e.path,symbol:i,capability:p,evidence:{kind:"import",file:e.path,line:g,excerpt:o.excerpt}});continue}let a=e.content.slice(0,o.offset).split(`
|
|
25
|
+
`).length,l={kind:"import",file:e.path,line:a,excerpt:o.excerpt},c=Ol(e.path,i,t);n.push({from:e.path,specifier:i,to:c?.path??null,resolution:c?"resolved":"unresolved",fromLayer:e.layer,toLayer:c?.layer??null,evidence:l})}return{edges:n,capabilityUses:r}}s(Zi,"moduleFactsFor");function Ol(e,t,n){let r=e.split("/");r.pop();for(let i of t.split("/"))i==="."||i===""||(i===".."?r.pop():r.push(i));let o=r.join("/");for(let i of[o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}/index.ts`,`${o}/index.tsx`]){let a=n.get(i);if(a)return a}}s(Ol,"resolveSpecifier");function Ji(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=nt(t.rules,r.fromLayer,r.toLayer,{fromPath:r.from,toPath:r.to,layers:t.layers});o&&n.push({ruleId:`layer-dependency:${o.from}->${o.to}`,message:o.message??`${o.from} must not depend on ${o.to}.`,edge:r,evidence:r.evidence})}return n}s(Ji,"violationsFor");var Pl={code:"LEXICAL_EVIDENCE_INCOMPLETE",message:"Lexical compatibility mode cannot prove parse status, TypeScript/package/symlink resolution, or symbol-aware source-policy and safety evidence. Use the resolved candidate facts APIs for an authoritative verdict."};function _l(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}s(_l,"hasActiveArkRules");function Tl(e,t){return _l(e,t)?W($(Hi({config:e,arkRules:t,warnings:[]}))):W($(Br(e)))}s(Tl,"policyHashFor");function Un(e,t,n){let r=typeof e=="string"?Ai(e,t):wr(e,t),o=n?.arkRules??$t();return{...r,arkRules:o,policyHash:Tl(r.config,o)}}s(Un,"loadContract");function Qi(e){let t=Un(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=Un(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=Yr(t.config,n.config,{baseArkRules:t.arkRules,candidateArkRules:n.arkRules,candidateInvariantCoverage:e.candidateInvariantCoverage}),o=r.findings.filter(l=>l.classification==="weakening"||l.classification==="judgment-required").map(l=>l.id).sort(),i=o.length>0,a=i&&Xr(e.acknowledgement,{basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,findingIds:o});return{schemaVersion:r.schemaVersion,basePolicyHash:t.policyHash,candidatePolicyHash:n.policyHash,classification:r.classification,findings:r.findings,blockingFindingIds:o,requiresAcknowledgement:i,acknowledged:a,valid:!i||a}}s(Qi,"analyzePolicyDelta");function Ut(e){let t=e.files.map(h=>{let u=$e(h.path);return{path:u,content:h.content,contentHash:W(h.content),layer:ce(u,e.contract.config.layers)??null}}).sort((h,u)=>h.path.localeCompare(u.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let u=Zi(h,n);r.push(...u.edges),o.push(...u.capabilityUses)}let i=Ji(r,e.contract.config),a=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(st(h))]));for(let h of o){let u=n.get(h.file)?.layer;if(!u)continue;let f=a.get(u),m=ve(h.symbol,f?.forbiddenGlobals??[]);if(m){i.push({ruleId:"FORBIDDEN_GLOBAL",message:`${u} must not use module "${h.symbol}" because it is the import form of forbidden global "${m}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(u)?.has(h.capability)&&i.push({ruleId:"CAPABILITY_VIOLATION",message:`${u} denies the ${h.capability} capability; found import of "${h.symbol}".`,capability:h.capability,symbol:h.symbol,evidence:h.evidence})}let c=t.length===0?"complete":"partial",p=c==="complete"?[]:[{...Pl}],g={schemaVersion:jr,policyHash:e.contract.policyHash,compilerOptionsHash:W($(e.compilerOptions??{})),files:t,layers:e.contract.config.layers.map(h=>h.name),edges:r,capabilityUses:o,violations:i};return{mode:"lexical-compatibility",completeness:c,completenessReasons:p,valid:c==="complete"&&i.length===0,ir:g}}s(Ut,"analyzeProject");function Gn(e){let t=new Map(e.files.map(n=>[$e(n.path),n]));for(let n of e.changes){let r=$e(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ut({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}s(Gn,"analyzeChange");function es(e){let t=`${e.evidence.file}:${e.evidence.line}`;if(!e.edge)return`${e.ruleId} at ${t}: ${e.message}`;let n=e.edge.to??e.edge.specifier;return`${e.ruleId} at ${t}: ${e.edge.from} imports ${n}. ${e.message}`}s(es,"explainViolation");function Zr(e){let t=0,n=new Map,r=new Map,o=new Set,i=[],a=[],l=s(c=>{n.set(c,t),r.set(c,t),t+=1,i.push(c),o.add(c);for(let h of[...e.get(c)??[]].sort())e.has(h)&&(n.has(h)?o.has(h)&&r.set(c,Math.min(r.get(c)??0,n.get(h)??0)):(l(h),r.set(c,Math.min(r.get(c)??0,r.get(h)??0))));if(r.get(c)!==n.get(c))return;let p=[],g;do{if(g=i.pop(),g===void 0)break;o.delete(g),p.push(g)}while(g!==c);p.length>1&&a.push(p.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return a.sort((c,p)=>c[0]<p[0]?-1:c[0]>p[0]?1:0).map(c=>({ruleId:"CIRCULAR_DEPENDENCY",file:c[0],line:1,target:c.join(" \u2192 "),message:`Circular dependency among ${c.length} files: ${c.join(" \u2192 ")} \u2192 ${c[0]}.`,cycleKind:"value"}))}s(Zr,"detectArchitectureCycles");function ft(e){let t=e.contentViolations.map(i=>({...i})),n=(e.warnings??[]).map(i=>({...i})),r=new Map(e.files.map(i=>[i,new Set]));for(let i of e.edges){if(i.to&&i.to!==i.from&&!i.typeOnly&&r.has(i.from)&&r.get(i.from)?.add(i.to),!i.to||!i.fromLayer||!i.toLayer)continue;let a=Ne(e.rules,i.fromLayer,i.toLayer,{fromPath:i.from,toPath:i.to,layers:e.config.layers});if(!a)continue;let l=a.rule,c=!!l.peerIsolation,p=!c&&!!(i.typeOnly||i.namedBindingsTypeOnly),g=c?tt(a.peerIsolationReason??"cross-slice",{fromPath:i.from,toPath:i.to,fromSlice:a.fromSlice,toSlice:a.toSlice}):void 0,h=l.message?g?`${l.message} (${g})`:l.message:g?`${i.fromLayer} must not ${i.kind} another slice of ${i.toLayer} (${i.from} \u2192 ${i.to}): ${g}`:`${i.fromLayer} must not ${i.kind} ${i.toLayer}.`;t.push({ruleId:"LAYER_IMPORT_VIOLATION",file:i.from,line:i.line,fromLayer:i.fromLayer,toLayer:i.toLayer,target:i.to,...i.typeOnly?{typeOnly:!0}:{},...i.targetTypeOnlyExports?{targetTypeOnlyExports:!0}:{},...i.sourcePureTypeModule?{sourcePureTypeModule:!0}:{},...i.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{},...!c&&i.portProofEligible?{portProofEligible:!0}:{},...i.kind?{edgeKind:i.kind}:{},...c?{peerIsolation:!0}:{},message:p?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...p?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let i=Zr(r);o==="soft"||o==="framework-soft"?n.push(...i.map(a=>({...a,message:`${a.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,failsStrict:!1}))):t.push(...i)}return{violations:t,warnings:n,safety:e.safety}}s(ft,"evaluateArchitectureGraph");function ts(e){if(typeof e.target=="string"&&e.target.length>0)return e.target;let t=String(e.sensor||e.code||"").trim();if(!t&&typeof e.message=="string"){let r=e.message.match(/\(sensor ([a-z0-9-]+)\)/i);r?.[1]&&(t=r[1])}let n=String(e.symbol||"").trim();return t?n?`${t}:${n}`:t:n}s(ts,"structureFreezeTarget");var Nl=["no-anemic-model"],is=["ensureInvariants","assertInvariants","validate","publish","emit","raise","record"],Eg=new RegExp(`\\b(${is.join("|")})\\b`),ss="(?:_?pendingEvents|domainEvents|uncommittedEvents|recordedEvents)",vg=new RegExp(`\\bthis\\.${ss}\\.push\\s*\\(`),Sg=new RegExp(`^this\\.${ss}\\s*=\\s*\\[\\s*\\]`);var Dl="truncatedUntil";function Ll(){return`${is.join(", ")}, or events-array .push(`}s(Ll,"expectedDomainInvariantWordsPhrase");function Jr(e){let t=Object.getOwnPropertyDescriptor(e,Dl)?.value;return typeof t=="number"?t:void 0}s(Jr,"shapeTruncatedUntil");function Fl(e){let t=Jr(e);return t==null?"":` shape analysed until character ${t}`}s(Fl,"shapeTruncationSuffix");function ns(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}s(ns,"escapeGlobLiteral");function Ml(e){let t="";for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"&&r+1<e.length){let i=e[r+1];if("*?{}[],".includes(i)||i==="\\"){t+="\\"+i,r+=1;continue}t+="/";continue}t+=o}let n="";for(let r=0;r<t.length;r+=1){let o=t[r];o==="\\"&&r+1<t.length?(n+=ns(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=ns(o)}return new RegExp(`^${n}$`)}s(Ml,"globToRegExp");function gt(e,t){return!t||t.length===0?!0:t.some(n=>Ml(n).test(e))}s(gt,"matchesAppliesTo");function $l(e){return Nl.includes(e)}s($l,"isTier2");function as(e){return e.mode==="enforced"&&!$l(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}s(as,"severityFor");function we(e,t,n,r=1){let{severity:o,failsStrict:i}=as(e);return{ruleId:"ARKRULE_STRUCTURE",code:e.sensor,message:n,file:t,line:r,fromLayer:e.provenance.layer,arkruleId:e.id,arkruleSource:e.provenance.sourceFile,severity:o,sensor:e.sensor,failsStrict:i}}s(we,"baseViolation");function Vn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}s(Vn,"isInRuleLayer");function jn(e,t,n){return t.filter(r=>!(!r.exported||!gt(r.file,e.appliesTo)||!Vn(r.file,e,n)))}s(jn,"shapesForRule");function Kl(e,t,n){let r=[];for(let o of jn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(we(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}s(Kl,"evaluateAggregatePrivateState");function Hl(e,t,n){let r=[];for(let o of jn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(we(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}s(Hl,"evaluateAlwaysValidFactory");function Ul(e,t,n){let r=[],o=Ll();for(let i of jn(e,t,n)){let a=Fl(i);Jr(i)!=null&&r.push(we(e,i.file,`Exported class ${i.className} shape analysed until character ${Jr(i)}; later methods may be invisible (sensor domain-event-on-mutation).`));for(let l of i.mutatingMethods)l.referencesGuardOrPublish||r.push(we(e,i.file,`Mutating method ${i.className}.${l.name} does not reference ${o} (sensor domain-event-on-mutation).${a}`))}return r}s(Ul,"evaluateDomainEventOnMutation");function Gl(e,t){let n=[];for(let r of t.files)gt(r,e.appliesTo)&&Vn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(we(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}s(Gl,"evaluateOrchestrationOnly");function Vl(e,t){let n=[];for(let r of t.files)gt(r,e.appliesTo)&&Vn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(we(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}s(Vl,"evaluateThinAdapter");function jl(e,t){let n=[];for(let r of t.files)gt(r,e.appliesTo)&&Vn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(we(e,r,"File imports a persistence driver and issues a write; route the write through a Domain aggregate and a persistence adapter (sensor writes-via-aggregate)."));return n}s(jl,"evaluateWritesViaAggregate");function Bl(e,t,n){let r=[];for(let o of jn(e,t,n))if(o.dataOnly===!0){let i=we(e,o.file,`Exported type ${o.className} looks data-only / anemic (sensor no-anemic-model; advisory only).`);r.push({...i,severity:"warning",failsStrict:!1})}return r}s(Bl,"evaluateNoAnemicModel");function ls(e){if(!e.arkRules.structure.length)return[];let t=[];for(let n of e.arkRules.structure)switch(n.sensor){case"aggregate-private-state":t.push(...Kl(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...Hl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...Ul(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...Gl(n,e));break;case"thin-adapter":t.push(...Vl(n,e));break;case"writes-via-aggregate":t.push(...jl(n,e));break;case"no-anemic-model":t.push(...Bl(n,e.classShapes,e.layerForFile));break;case"invariant-coverage":break;default:break}return t.sort((n,r)=>n.file.localeCompare(r.file)||n.arkruleId.localeCompare(r.arkruleId)||n.message.localeCompare(r.message))}s(ls,"evaluateArkRuleSensors");function cs(e,t){let n=[],r=t.map(o=>o.replace(/\\/g,"/"));for(let o of e.structure){if(!o.appliesTo||o.appliesTo.length===0||r.some(c=>gt(c,o.appliesTo)))continue;let{severity:a,failsStrict:l}=as(o);n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule structure "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>gt(l,o.appliesTo)))continue;let a=o.mode==="enforced";n.push({ruleId:"ARKRULE_SCOPE_EMPTY",code:"appliesTo-zero-match",message:`ArkRule invariant "${o.id}" appliesTo matched zero governed files (patterns: ${o.appliesTo.join(", ")}). A zero-match scope is almost always misconfiguration.`,file:o.provenance.sourceFile,line:1,fromLayer:o.provenance.layer,arkruleId:o.id,arkruleSource:o.provenance.sourceFile,severity:a?"error":"warning",sensor:"invariant-coverage",failsStrict:a})}return n.sort((o,i)=>o.file.localeCompare(i.file)||o.arkruleId.localeCompare(i.arkruleId)||o.message.localeCompare(i.message))}s(cs,"collectEmptyAppliesToFindings");var rs=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm(?:\/[^'"]+)?|postgres(?:\/[^'"]+)?|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|postgres(?:\/[^'"]+)?|drizzle-orm(?:\/[^'"]+)?|knex|typeorm|mongoose)/,os=/\bfrom\s+['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)(?:\.[cm]?[jt]sx?)?['"]|require\(\s*['"](?:@\/|~\/)?(?:[\w.-]+\/)*(?:db|database|prisma|drizzle)/,Wl=/\b(?:db|tx|client|prisma(?:Client)?|drizzle)\b(?:\s*\.\s*[A-Za-z_]\w*)*\s*\.\s*(?:insert(?:One|Many)?|update(?:One|Many)?|upsert|delete(?:One|Many)?|createMany|create|replaceOne|findOneAnd(?:Update|Delete|Replace))\s*\(|\bINSERT\s+INTO\b|\bUPDATE\s+[A-Za-z_][\w.]*\s+SET\b|\bDELETE\s+FROM\b/i;function zl(e){return e==="PersistenceAdapters"}s(zl,"isPersistenceDriverLayer");function ql(e,t){if(rs.test(e)||os.test(e))return!0;if(!t)return!1;for(let n of t){if(zl(n.layer))return!0;let r=n.specifier;if(!r)continue;let o=`from '${r}'`;if(rs.test(o)||os.test(o))return!0}return!1}s(ql,"sourceImportsPersistenceDriver");var Yl=/\b(?:@Controller|@Get|@Post|@Put|@Delete|Router\(\)|createRouter|express\.Router|fastify\.(?:get|post)|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)\b|export\s+const\s+(?:GET|POST|PUT|DELETE|PATCH)\s*=)/,Xl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Zl=/\b(?:export\s+)?(?:async\s+)?function\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*|\b(?:export\s+)?const\s+(?:can|calculate|compute|should|ensure|validate|is|has)[A-Z]\w*\s*=/,Jl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Ql(e,t,n){if(!t)return null;let r=ql(t,n),o=r&&Wl.test(t);if(t.length<40)return o?{persistenceWrite:!0}:null;let i=t.match(new RegExp(Zl.source,"g"))??[],a=t.match(new RegExp(Jl.source,"g"))??[],l=(t.match(/\bif\s*\(/g)??[]).length,c=(t.match(/\bswitch\s*\(/g)??[]).length,p=i.length>=2||i.length>=1&&a.length>=2||a.length>=3&&l+c>=6,g=Yl.test(t)||Xl.test(t),h=i.length>=1||a.length>=2,u=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),f=r&&h||g&&h||r&&u&&(l>=4||i.length>=1)||g&&r;return!p&&!f&&!o?null:{...p?{orchestrationHeavy:!0}:{},...f?{adapterThick:!0}:{},...o?{persistenceWrite:!0}:{}}}s(Ql,"deriveArkRuleFileHints");function ds(e,t){let n={};for(let[r,o]of Object.entries(e)){let i=r.replace(/\\/g,"/"),a=Ql(r,o,t?.[i]);a&&(n[i]=a)}return n}s(ds,"buildArkRuleFileHints");function ec(e){if(!e)return{};let t=typeof e.governedPercent=="number"?e.governedPercent:null,n=typeof e.populatedLayerCount=="number"?e.populatedLayerCount:null;return n==null&&typeof e.classifiedFiles=="number"&&(n=e.classifiedFiles>0?1:0),{governedPercent:t,populatedLayerCount:n}}s(ec,"normalizeExtraMergeTeethClassification");function Bn(e){let t=ec(e),n=typeof t.governedPercent=="number"?t.governedPercent:null,r=typeof t.populatedLayerCount=="number"?t.populatedLayerCount:null;return n==null&&r==null?!0:(n??0)>=50&&(r??0)>=1}s(Bn,"extraMergeTeethAllowed");function us(e){let t=e.length,n=0,r=new Set;for(let o of e){let i=typeof o.layer=="string"&&o.layer.length>0?o.layer:null;i&&(n+=1,r.add(i))}return{governedPercent:t>0?Math.round(n/t*100):0,populatedLayerCount:r.size}}s(us,"classifyResolvedLayerCoverage");var tc=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var Pg=new Set(tc);function ps(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}s(ps,"isArkRunKernelModuleSpecifier");var nc=["events","node:events","eventemitter2","eventemitter3","emittery","kafkajs","kafka-node","amqplib","amqp","bull","bullmq","mqtt","nats","@aws-sdk/client-sqs","@aws-sdk/client-sns","@aws-sdk/client-eventbridge","@google-cloud/pubsub","@azure/service-bus"],Qr=new Set(nc);function fs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Qr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Qr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Qr.has(e.slice(0,r))}s(fs,"isArkRunTransportBypassSpecifier");var rc=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Hg=new Set(rc);var gs={"arkrun-missing-root":"ARKRUN_MISSING_ROOT","arkrun-kernel-in-domain":"ARKRUN_KERNEL_IN_DOMAIN","arkrun-direct-new":"ARKRUN_DIRECT_NEW","arkrun-undeclared-emit":"ARKRUN_UNDECLARED_EMIT","arkrun-undeclared-handle":"ARKRUN_UNDECLARED_HANDLE","arkrun-undeclared-depend":"ARKRUN_UNDECLARED_DEPEND","arkrun-transport-bypass":"ARKRUN_TRANSPORT_BYPASS"},oc="ARKRUN_INTERACTION_NAME_INCOMPLETE";function hs(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)||/^(?:entit(?:y|ies)|aggregates?)(?:$|(?=[A-Z_\-\s]))/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}s(hs,"isDomainRoleLayer");function ic(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}s(ic,"compareFindings");function Ae(e,t,n,r,o,i,a){let l=e.mode==="enforced"&&a;return{ruleId:gs[t],sensor:t,message:o,file:n,line:r,...i?.fromLayer?{fromLayer:i.fromLayer}:{},...i?.target?{target:i.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:gs[t],fromLayer:i?.fromLayer,target:i?.target})}}s(Ae,"finding");function sc(e,t){let n=[],r=[],o=[],i=[];for(let a of e)a.file===t&&(n.push(...a.uses),r.push(...a.reactsTo),o.push(...a.raises),i.push(...a.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(i)}}s(sc,"bagForFile");function ms(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}s(ms,"emitKinds");function ys(e){return e==="subscribe"||e==="register-handler"}s(ys,"handleKinds");function ac(e){return e==="resolve"||e==="resolve-singleton"}s(ac,"dependKinds");function lc(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(Ae(e,"arkrun-missing-root","ark.config.json",1,"ArkRun kernelRoots is empty; no createArkKernel factory site is declared.",void 0,n)),r;let i=new Map;for(let a of t){let l=i.get(a.matchedRoot)??[];l.push(a),i.set(a.matchedRoot,l)}for(let a of o){let l=[...i.get(a)??[]].sort((p,g)=>p.file.localeCompare(g.file));if(l.length===0){r.push(Ae(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(a)} matched no governed files and has no createArkKernel factory.`,{target:a},n));continue}if(l.some(p=>p.hasKernelFactory))continue;let c=l[0];r.push(Ae(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(a)} has no createArkKernel / createStrictArkKernel factory.`,{target:a},n))}return r}s(lc,"evaluateMissingRoot");function cc(e,t,n,r,o){let i=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),a=[];for(let l of n){let c=l.specifier;if(!c||!ps(c))continue;let p=r(l.from);p&&hs(p,i.get(p)??[])&&a.push(Ae(e,"arkrun-kernel-in-domain",l.from,l.line,`${p} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:p,target:c},o))}return a}s(cc,"evaluateKernelInDomain");function dc(e,t,n,r,o,i){let a=new Set(e.managedLayers);if(a.size===0)return[];let l=new Map(t.map(g=>[g.name,g.intentPrefixes??[]])),c=new Set(r.filter(g=>g.hasKernelFactory).map(g=>g.file)),p=[];for(let g of n){if(c.has(g.file))continue;let h=g.typeName;if(e.ignoreDirectNewForErrors!==!1&&(h.endsWith("Error")||h==="Error")||h.endsWith("DTO")||h.endsWith("VO"))continue;let u=o(g.file);!u||!a.has(u)||hs(u,l.get(u)??[])||p.push(Ae(e,"arkrun-direct-new",g.file,g.line,`${u} must not construct ${g.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:u,target:g.typeName},i))}return p}s(dc,"evaluateDirectNew");function uc(e,t,n,r,o){let i=[],a=[];if(e.requireDeclarations!==!0)return{findings:i,completenessReasons:a};let l=new Set(e.managedLayers);if(l.size===0)return{findings:i,completenessReasons:a};for(let c of t){if(!ms(c.kind)&&!ys(c.kind)&&!ac(c.kind))continue;let p=r(c.file);if(!p||!l.has(p))continue;if(!c.nameLiteral){e.mode==="enforced"&&a.push({code:oc,file:c.file,message:`ArkRun ${c.kind} call in ${c.file} has no string-literal name; enforced extra cannot prove the declaration.`});continue}let g=sc(n,c.file);if(ms(c.kind)){if(g.raises.has(c.nameLiteral)||g.sends.has(c.nameLiteral))continue;i.push(Ae(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:p,target:c.nameLiteral},o));continue}if(ys(c.kind)){if(g.reactsTo.has(c.nameLiteral))continue;i.push(Ae(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:p,target:c.nameLiteral},o));continue}g.uses.has(c.nameLiteral)||i.push(Ae(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:p,target:c.nameLiteral},o))}return{findings:i,completenessReasons:a}}s(uc,"evaluateUndeclared");function pc(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let i=[];for(let a of t){if(a.typeOnly)continue;let l=a.specifier;if(!l||!fs(l))continue;let c=n(a.from);!c||!o.has(c)||i.push(Ae(e,"arkrun-transport-bypass",a.from,a.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return i}s(pc,"evaluateTransportBypass");function Rs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Bn(e.classification),r=uc(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...lc(t,e.compositionRootHits,n),...cc(t,e.layers,e.dependencies,e.layerForFile,n),...dc(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...pc(t,e.dependencies,e.layerForFile,n)].sort(ic),i=[...r.completenessReasons].sort((a,l)=>{let c=`${a.code}\0${a.file??""}\0${a.message}`,p=`${l.code}\0${l.file??""}\0${l.message}`;return c<p?-1:c>p?1:0});return{findings:o,completenessReasons:i}}s(Rs,"evaluateArkRunSensors");function As(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}s(As,"isArkOrderModuleSpecifier");var ks=new Map;function Is(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}s(Is,"escapeAppliesToLiteral");function fc(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"&&n+1<e.length){let o=e[n+1];if("*?{}[],".includes(o)||o==="\\"){t+="\\"+o,n+=1;continue}t+="/";continue}t+=r}return t}s(fc,"normalizeAppliesToGlob");function gc(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="{")t+=1;else if(r==="}"&&(t-=1,t<0))return!1}return t===0}s(gc,"appliesToBracesBalanced");function mc(e){let t=ks.get(e);if(t)return t;let n=fc(e),r=gc(n),o="",i=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Is(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",i+=1):c==="}"&&r&&i>0?(o+=")",i-=1):c===","&&r&&i>0?o+="|":o+=Is(c)}let a=new RegExp(`^${o}$`);return ks.set(e,a),a}s(mc,"globToRegExp");var bs={"arkorder-missing-plane":"ARKORDER_MISSING_PLANE","arkorder-kernel-in-domain":"ARKORDER_KERNEL_IN_DOMAIN","arkorder-generic-update":"ARKORDER_GENERIC_UPDATE","arkorder-too-many-params":"ARKORDER_TOO_MANY_PARAMS","arkorder-ingest-writes-xi":"ARKORDER_INGEST_WRITES_XI","arkorder-xi-field-write":"ARKORDER_XI_FIELD_WRITE","arkorder-information-budget":"ARKORDER_INFORMATION_BUDGET","arkorder-xi-ttl":"ARKORDER_XI_TTL"};function yc(e,t){return!t||t.length===0?!0:t.some(n=>mc(n).test(e))}s(yc,"matchesArkOrderAppliesTo");function hc(e,t=[]){let n=e.trim();return/^domain(?:model)?$/i.test(n)||/^domain(?=[A-Z_\-\s])/i.test(n)?!0:t.some(r=>{let o=r.trim().replace(/\.+$/,"");return o==="Domain"||o.startsWith("Domain.")})}s(hc,"isDomainRoleLayer");function Ce(e,t,n,r,o,i,a){let l=e.mode==="enforced"&&a;return{ruleId:bs[t],sensor:t,message:o,file:n,line:r,...i?.fromLayer?{fromLayer:i.fromLayer}:{},...i?.target?{target:i.target}:{},severity:l?"error":"warning",failsStrict:l,nextAction:pe({ruleId:bs[t],fromLayer:i?.fromLayer,target:i?.target})}}s(Ce,"finding");function Es(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Bn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(Ce(t,"arkorder-missing-plane","ark.config.json",1,"ArkOrder planeRoots is empty; no createOrderPlane site is declared.",void 0,n));else{let c=new Map;for(let p of e.planeRootHits){let g=c.get(p.matchedRoot)??[];g.push(p),c.set(p.matchedRoot,g)}for(let p of o){let g=c.get(p)??[];if(g.length===0){r.push(Ce(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(p)} matched no governed files and has no createOrderPlane factory.`,{target:p},n));continue}g.some(h=>h.hasPlaneFactory)||r.push(Ce(t,"arkorder-missing-plane",g[0].file,1,`ArkOrder plane root ${JSON.stringify(p)} has no createOrderPlane factory.`,{target:p},n))}}let i=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let p=c.specifier;if(!p||!As(p))continue;let g=e.layerForFile(c.from);g&&hc(g,i.get(g)??[])&&r.push(Ce(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:g,target:p},n))}for(let c of e.genericUpdates)r.push(Ce(t,"arkorder-generic-update",c.file,c.line,`Generic ${c.method}() on the order plane rewrites \u03BE; Haken forbids it.`,{target:c.method},n));let a=t.xiKeys??[];for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(Ce(t,"arkorder-too-many-params",c.file,c.line,`release() freezes ${c.keyCount} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(c.keyCount)},n));for(let c of e.ingestWritesXi??[])r.push(Ce(t,"arkorder-ingest-writes-xi",c.file,c.line,"ingest() result is assigned into a Release or \u03BE store; ingest may absorb or escalate, never mint a pattern.",void 0,n));let l=new Set(t.managedLayers);for(let c of a.length===0?[]:e.xiFieldWrites??[]){let p=e.layerForFile(c.file);!p||!l.has(p)||yc(c.file,t.appliesTo)&&r.push(Ce(t,"arkorder-xi-field-write",c.file,c.line,`This file writes ${JSON.stringify(c.key)} the same way it would write a seat count. Take the event in, or change that choice through the valve (propose, then apply).`,{fromLayer:p,target:c.key},n))}return r.sort((c,p)=>c.file.localeCompare(p.file)||c.ruleId.localeCompare(p.ruleId)||c.line-p.line),{findings:r,completenessReasons:[]}}s(Es,"evaluateArkOrderSensors");function J(e,t,n={}){return{ruleId:e,message:t,...n}}s(J,"configWarning");function Wn(e){let{config:t,rules:n,files:r,manifest:o}=e,i=[];if(t.dynamicImportAllowlist!==void 0&&(!Array.isArray(t.dynamicImportAllowlist)||t.dynamicImportAllowlist.some(f=>typeof f!="string"))&&i.push(J("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","dynamicImportAllowlist must be an array of file globs.")),t.safety!==void 0&&(t.safety===null||typeof t.safety!="object"||Array.isArray(t.safety)))i.push(J("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let m=t.safety[f];m!==void 0&&(!Number.isInteger(m)||m<0)&&i.push(J("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let a=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...a.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);a.length===0&&i.push(J("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let p=new Set,g=new Set;for(let f of a){if(!f.name){i.push(J("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}p.has(f.name)&&g.add(f.name),p.add(f.name),f.forbiddenGlobals!==void 0&&(!Array.isArray(f.forbiddenGlobals)||f.forbiddenGlobals.some(y=>typeof y!="string"))&&i.push(J("CONFIG_INVALID_FORBIDDEN_GLOBALS",`Layer "${f.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,{layer:f.name}));let m=Array.isArray(f.patterns)?f.patterns:[];if(m.length===0){i.push(J("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of m){let v;try{v=me(y)}catch(A){i.push(J("CONFIG_INVALID_LAYER_PATTERN",`Layer "${f.name}" has an invalid pattern "${y}": ${A instanceof Error?A.message:String(A)}`,{layer:f.name,pattern:y}));continue}let E=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>v.test(A))&&!E&&i.push(J("CONFIG_LAYER_PATTERN_NO_MATCHES",`Layer "${f.name}" pattern "${y}" matched no included files (possible typo). Mark the layer reserved/allowEmpty if this house is reserved for later.`,{layer:f.name,pattern:y,failsStrict:!1,reserved:!1}))}}for(let f of g)i.push(J("CONFIG_DUPLICATE_LAYER",`Layer "${f}" is configured more than once.`,{layer:f}));if(c.size>0)for(let f of n??[])f.from&&!c.has(f.from)&&i.push(J("CONFIG_RULE_UNKNOWN_FROM_LAYER",`Rule references unknown source layer "${f.from}".`,{fromLayer:f.from,toLayer:f.to})),f.to&&!c.has(f.to)&&i.push(J("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(a.length>1)for(let f of r){let m=-1,y=[];for(let v of a)for(let E of v.patterns??[]){if(!me(E).test(f))continue;let A=br(E,f);A>m?(m=A,y=[v.name]):A===m&&!y.includes(v.name)&&y.push(v.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&i.push(J("CONFIG_AMBIGUOUS_LAYERS",`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...h].join(", ")}.`,{pairs:[...h]}));let u=r.filter(f=>!ce(f,a));return u.length>0&&i.push(J("CONFIG_UNCLASSIFIED_FILES",`${u.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:u.length,samples:u.slice(0,5)})),i}s(Wn,"collectAnalysisConfigWarnings");function vs(e,t){let n=e.ruleId==="ARKRULE_STRUCTURE",r=e.ruleId==="ARKRULE_SCOPE_EMPTY";return{ruleId:e.ruleId,file:e.file,line:e.line,message:e.message,fromLayer:e.fromLayer,arkruleId:e.arkruleId,arkruleSource:e.arkruleSource,...n?{sensor:e.sensor,code:e.code,target:ts({sensor:e.sensor,code:e.code})}:{},...r?{freezable:!1}:{},nextAction:t}}s(vs,"toArkRuleEngineViolation");function Rc(e,t){return t.some(n=>{try{return me(n).test(e)}catch{return!1}})}s(Rc,"matchesAny");function Ac(e,t){let n=e.contract.config.safety??{},r=Number.isInteger(n.maxTsSuppressions)?Number(n.maxTsSuppressions):0,o=Number.isInteger(n.maxAnyCasts)?Number(n.maxAnyCasts):0,i=e.contract.config.dynamicImportAllowlist??[],a=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:v})=>({file:y,line:v})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:v})=>({file:y,line:v})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Rc(y.file,i)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),p=n.allowInMemory===!0||t.projectPackageName==="arkgate"?[]:t.safetyUses.filter(y=>y.kind==="in-memory-store").map(y=>({file:y.file,line:y.line,store:y.symbol??"in-memory store"})),g=n.allowDisabledPeerIsolation===!0?[]:(e.contract.config.rules??[]).filter(y=>y.peerIsolation===!1||y.allowed===!1&&!!y.from&&y.from===y.to&&y.peerIsolation!==!0).map(y=>({from:y.from,to:y.to})),h={tsSuppressions:a,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:p,disabledPeerIsolationRules:g,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},u=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];u.push({ruleId:"DYNAMIC_IMPORT_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${f.length} non-literal dynamic import(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}let m=c.filter(y=>y.kind==="require");if(m.length>0){let y=m[0];u.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${m.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(a.length>r){let y=a[0];u.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${a.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];u.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(p.length>0){let y=p[0];u.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${p.length} ArkGate InMemory store risk(s) appear in governed production source. Provide durable stores or set safety.allowInMemory only for an explicitly ephemeral service.`})}return g.length>0&&u.push({ruleId:"PEER_ISOLATION_DISABLED",message:`${g.length} rule(s) disable or omit required peerIsolation. Restore peerIsolation: true or set safety.allowDisabledPeerIsolation only with a documented production exception.`}),{report:h,warnings:u}}s(Ac,"evaluateSafety");function kc(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}s(kc,"ambientForbiddenGlobal");function Ss(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return $r(e,n.length>0?n:Mr.map(r=>({name:r.layer,prefixes:r.prefixes})))}s(Ss,"intentLayer");function Ic(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(i=>[i.name,i]));for(let i of t.ambientUses){let a=n.get(i.file);!a||!kc(i.symbol,o.get(a)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,message:`${a} must not use the ambient global "${i.symbol}".`})}for(let i of t.capabilityUses){let a=n.get(i.file);if(!a)continue;let l=o.get(a),c=l?.forbiddenGlobals??[],p=i.source==="import-based"?t.dependencies.find(g=>g.from===i.file&&g.line===i.line&&g.specifier===i.symbol&&!g.typeOnly)?.kind:void 0;if(!(i.source==="ambient-global"&&_t(i.symbol,c))){if(i.source==="import-based"){let g=ve(i.symbol,c);if(g){r.push({ruleId:"FORBIDDEN_GLOBAL",file:i.file,line:i.line,fromLayer:a,target:i.symbol,...p?{edgeKind:p}:{},message:`${a} must not use module "${i.symbol}" because it is the import form of forbidden global "${g}".`});continue}}st(l).includes(i.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:i.file,line:i.line,fromLayer:a,target:i.symbol,capability:i.capability,...p?{edgeKind:p}:{},message:i.source==="import-based"?`${a} denies the ${i.capability} capability; found import of "${i.symbol}".`:`${a} denies the ${i.capability} capability; found ambient "${i.symbol}".`})}}for(let i of t.publishCalls){let a=n.get(i.file);if(!a)continue;for(let c of Tt({publishCall:!0,rawIntentName:i.rawIntentName,objectHasIntent:i.objectHasIntent,arkPublishCandidate:i.arkPublishCandidate,hasSource:i.hasSource}))r.push({ruleId:c.ruleId,file:i.file,line:i.line,...c.ruleId==="PUBLISH_MISSING_SOURCE"?{fromLayer:a}:{},message:c.message});if(!i.sourceIntent)continue;let l=Ss(i.sourceIntent,e.contract);!l||l===a||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:i.file,line:i.line,fromLayer:a,toLayer:l,target:i.sourceIntent,message:`Publish source "${i.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${a}.`})}for(let i of t.intentReferences){let a=n.get(i.file);if(!a)continue;let l=Ss(i.intent,e.contract);if(!l)continue;let c=Ne(e.contract.config.rules,a,l,{fromPath:i.file,layers:e.contract.config.layers});if(!c)continue;let p=c.rule.peerIsolation?tt(c.peerIsolationReason??"cross-slice",{fromPath:i.file,fromSlice:c.fromSlice,toSlice:c.toSlice}):void 0,g=`${a} must not reference ${l} intent ${i.intent}.`,h=p&&c.peerIsolationReason!=="cross-slice"?`${g} ${p}`:c.rule.message?p?`${c.rule.message} (${p})`:c.rule.message:g;r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:i.file,line:i.line,fromLayer:a,toLayer:l,target:i.intent,...c.rule.peerIsolation?{peerIsolation:!0}:{},message:h})}return r}s(Ic,"contentViolations");function bc(e){let{facts:t}=e,n=Ft(e.contract.config),r=t.evidenceRequirementsHash===n,o=r?t.completeness:"unavailable",i=r?t.completenessReasons:[...t.completenessReasons,{code:"EVIDENCE_REQUIREMENTS_MISMATCH",message:"Resolved facts were collected for different policy-controlled evidence requirements."}].sort((d,_)=>{let M=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${_.code}\0${_.file??""}\0${_.message}`;return M<oe?-1:M>oe?1:0}),a=t.files.map(d=>({...d,layer:ce(d.path,e.contract.config.layers)??null})),l=new Map(a.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let _=d.target?l.get(d.target)??ce(d.target,e.contract.config.layers):void 0;return{from:d.from,fromLayer:l.get(d.from)??null,...d.resolution==="resolved-project"&&d.target?{to:d.target,..._?{toLayer:_}:{}}:{},line:d.line,kind:d.kind,typeOnly:d.typeOnly,...d.targetTypeOnlyExports?{targetTypeOnlyExports:d.targetTypeOnlyExports}:{},...d.sourcePureTypeModule?{sourcePureTypeModule:d.sourcePureTypeModule}:{},...d.namedBindingsTypeOnly?{namedBindingsTypeOnly:d.namedBindingsTypeOnly}:{},...d.portProofEligible?{portProofEligible:d.portProofEligible}:{}}}),p=Wn({config:e.contract.config,rules:e.contract.config.rules,files:a.map(d=>d.path)}),g=Ac(e,t),h=e.contract.arkRules??$t(),u=a.map(d=>d.path),m={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?ds(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...ls({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:u,layerForFile:s(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),fileHints:m}),...cs(h,u)],v=y.filter(d=>d.failsStrict).map(d=>vs(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule. ARKRULE_SCOPE_EMPTY is a config diagnostic and is not freezable (even with --force). Land the rule as advisory until the folder exists, then promote.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`)),E=y.filter(d=>!d.failsStrict).map(d=>({...vs(d,d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory). Empty scope is not freezable; promote only after the folder exists.`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`),failsStrict:!1})),b=(h.invariants?.length??0)>0?Gi({arkRules:h,fileContents:e.coverageInputs?.fileContents??{},testFiles:e.coverageInputs?.testFiles??[],testGlobsMissing:e.coverageInputs?.testGlobsMissing===!0||e.coverageInputs===void 0||(e.coverageInputs.testFiles?.length??0)===0,coverageBudgetExhausted:e.coverageInputs?.coverageBudgetExhausted===!0,...e.coverageInputs?.stats?{coverageStats:e.coverageInputs.stats}:{},...e.coverageInputs?.coverageRoots?{coverageRoots:e.coverageInputs.coverageRoots}:{}}):{coverage:[],violations:[],partial:!1},w=b.violations.filter(d=>d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,nextAction:`Add a test title or declared symbol covering ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),N=b.violations.filter(d=>!d.failsStrict).map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,arkruleId:d.arkruleId,arkruleSource:d.arkruleSource,failsStrict:!1,nextAction:d.ruleId==="INVARIANT_COVERAGE_OUTSIDE_ROOTS"?`Move ${d.file} under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json.`:`Cover invariant ${d.arkruleId} in ${d.arkruleSource} (advisory / partial).`})),I=us(a),T=Rs({arkRun:e.contract.config.arkRun,layers:e.contract.config.layers,kernelCalls:t.arkRunKernelCalls,managedNews:t.arkRunManagedNews,compositionRootHits:t.arkRunCompositionRootHits,declarations:t.arkRunDeclarations,dependencies:t.dependencies,layerForFile:s(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),ee=e.contract.config.arkRun?.mode,ge=T.findings.filter(()=>ee==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),je=T.findings.filter(()=>ee!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),D=Es({arkOrder:e.contract.config.arkOrder,layers:e.contract.config.layers,planeCalls:t.arkOrderPlaneCalls,genericUpdates:t.arkOrderGenericUpdates,planeRootHits:t.arkOrderRootHits,xiFieldWrites:t.arkOrderXiFieldWrites,ingestWritesXi:t.arkOrderIngestWritesXi,releaseKeyCounts:t.arkOrderReleaseKeyCounts,dependencies:t.dependencies,layerForFile:s(d=>l.get(d)??ce(d,e.contract.config.layers),"layerForFile"),classification:I}),ue=e.contract.config.arkOrder?.mode,X=D.findings.filter(()=>ue==="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:d.failsStrict,...d.severity?{severity:d.severity}:{}})),Be=D.findings.filter(()=>ue!=="enforced").map(d=>({ruleId:d.ruleId,file:d.file,line:d.line,message:d.message,fromLayer:d.fromLayer,target:d.target,nextAction:d.nextAction,sensor:d.sensor,failsStrict:!1})),It=[...b.partial&&b.coverage.some(d=>d.mode==="enforced"&&d.partial)?[{code:"INVARIANT_COVERAGE_PARTIAL",message:"Enforced ArkRules invariant coverage cannot be fully proven (missing test globs or empty test set); reporting partial, never covered."}]:[],...T.completenessReasons,...D.completenessReasons],Pe=ft({config:e.contract.config,rules:e.contract.config.rules,files:a.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Ic(e,t,l),...v,...w,...ge,...X],edges:c,warnings:[...p,...g.warnings,...E,...N,...je,...Be],safety:g.report}),dn=o==="complete"&&It.length>0?"partial":o,pr=dn==="complete"?i:[...i,...It].sort((d,_)=>{let M=`${d.code}\0${d.file??""}\0${d.message}`,oe=`${_.code}\0${_.file??""}\0${_.message}`;return M<oe?-1:M>oe?1:0}),S=Pe.violations.filter(d=>d.failsStrict!==!1),C=dn==="complete"&&S.length===0,R=C&&Pe.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:dn,completenessReasons:pr,valid:C,strictValid:R,policyHash:e.contract.policyHash,factsHash:t.factsHash,resolverIdentity:t.resolverIdentity,candidateTreeHash:t.candidateTreeHash,safety:g.report,ir:{schemaVersion:"1.0",policyHash:e.contract.policyHash,compilerOptionsHash:t.compilerOptionsHash,files:a,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Pe.violations,warnings:Pe.warnings}}}s(bc,"analyzeCanonicalResolvedProject");function Gt(e){return bc({contract:e.contract,facts:Se(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}s(Gt,"analyzeResolvedProject");function ws(e){return W($(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}s(ws,"analysisTreeHash");function Cs(e){let t=Ut(e),n=new Map(t.ir.files.map(m=>[m.path,m])),r=[],o=new Set,i=[];for(let m of e.changes){let y=m.path.replace(/\\/g,"/"),v=$e(m.path);if(!v||v===".."||v.startsWith("../")||y.startsWith("/")||/^[A-Za-z]:\//.test(y)||y.includes("\0")){i.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a safe, non-empty project-relative path."});continue}if(o.has(v)){i.push({ruleId:"DUPLICATE_CHANGE_PATH",file:v,line:1,message:`The atomic change set contains more than one operation for ${v}.`});continue}o.add(v),"delete"in m&&m.delete&&!n.has(v)&&i.push({ruleId:"DELETE_TARGET_MISSING",file:v,line:1,message:`Cannot delete ${v} because it is not present in the supplied base tree.`}),r.push("delete"in m&&m.delete?{path:v,delete:!0}:{path:v,content:"content"in m?m.content:""})}e.changes.length===0&&i.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});let a=Gn({...e,changes:r}),l=new Map(a.ir.files.map(m=>[m.path,m])),c=a.ir.violations.filter(m=>m.ruleId==="CAPABILITY_VIOLATION"||m.ruleId==="FORBIDDEN_GLOBAL").map(m=>{let y=l.get(m.evidence.file)?.layer;return{ruleId:m.ruleId,file:m.evidence.file,line:m.evidence.line,target:m.symbol,...m.capability?{capability:m.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:m.message}}),p=ft({config:e.contract.config,rules:e.contract.config.rules,files:a.ir.files.map(m=>m.path),contentViolations:c,edges:a.ir.edges.filter(m=>!!m.fromLayer).map(m=>({from:m.from,fromLayer:m.fromLayer,...m.to?{to:m.to}:{},...m.toLayer?{toLayer:m.toLayer}:{},line:m.evidence.line,kind:"import",...m.typeOnly?{typeOnly:!0}:{},...m.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),g=r.map(m=>{let y=$e(m.path),v=n.get(y),E=l.get(y);return{path:y,operation:"delete"in m&&m.delete?"delete":v?"update":"create",...v?{beforeContentHash:v.contentHash}:{},...E?{candidateContentHash:E.contentHash}:{}}}).sort((m,y)=>m.path.localeCompare(y.path)),h=[...i,...p.violations].map(m=>({...m,nextAction:pe(m)})),u=h.filter(m=>m.failsStrict!==!1),f=e.changeMap?pt({changeMap:e.changeMap,changes:g,baseDependencies:t.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[]),candidateDependencies:a.ir.edges.flatMap(m=>m.to?[{from:m.from,to:m.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&a.valid&&u.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:a.ir.compilerOptionsHash,baseTreeHash:ws(t.ir.files),candidateTreeHash:ws(a.ir.files),baseCompleteness:t.completeness,candidateCompleteness:a.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:a.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:g,violations:h,warnings:p.warnings}}s(Cs,"preflightChange");function Ec(e){let t=e.replace(/\\/g,"/");if(!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.includes("\0"))return;let n=[];for(let o of t.split("/"))if(!(!o||o==="."))if(o===".."){if(n.length===0)return;n.pop()}else n.push(o);let r=n.join("/");return r&&r===t?r:void 0}s(Ec,"canonicalChangePath");function vc(e,t){return[["resolverIdentity",e.resolverIdentity,t.resolverIdentity],["compilerIdentity",e.compilerIdentity,t.compilerIdentity],["evidenceRequirementsHash",e.evidenceRequirementsHash,t.evidenceRequirementsHash],["projectPackageName",e.projectPackageName??"",t.projectPackageName??""]].filter(([,r,o])=>r!==o).map(([r,o,i])=>({ruleId:"FACTS_IDENTITY_MISMATCH",file:"<change-set>",line:1,field:r,before:o,candidate:i,message:`Base and candidate facts must use the same ${r}.`}))}s(vc,"identityViolations");function Sc(e,t,n,r){let o=n.get(t),i=r.get(t);return{path:t,operation:"delete"in e&&e.delete?"delete":o?"update":"create",...o?{beforeContentHash:o.contentHash}:{},...i?{candidateContentHash:i.contentHash}:{}}}s(Sc,"preparedChange");function xs(e){let t=Se(e.baseFacts),n=Se(e.candidateFacts),r=Gt({contract:e.contract,facts:t}),o=Gt({contract:e.contract,facts:n}),i=new Map(t.files.map(f=>[f.path,f])),a=new Map(n.files.map(f=>[f.path,f])),l=vc(t,n),c=new Map,p=[];for(let f of e.changes){let m=Ec(f.path);if(!m){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(m)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:m,line:1,message:`The atomic change set contains more than one operation for ${m}.`});continue}c.set(m,f);let y=i.get(m),v=a.get(m);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:m,line:1,message:`Cannot delete ${m} because it is not present in the supplied base facts.`}),v&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:m,line:1,message:`Candidate facts still contain deleted file ${m}.`});else{let E="content"in f?f.content:"",A=W(E);v?v.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:m,line:1,expectedContentHash:A,candidateContentHash:v.contentHash,message:`Candidate facts for ${m} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:m,line:1,message:`Candidate facts do not contain changed file ${m}.`})}p.push(Sc(f,m,i,a))}e.changes.length===0&&l.push({ruleId:"CHANGE_SET_EMPTY",file:"<change-set>",line:1,message:"Atomic preflight requires at least one create, update, or delete."});for(let f of new Set([...i.keys(),...a.keys()])){if(c.has(f))continue;let m=i.get(f),y=a.get(f);m&&y&&$(m)===$(y)||l.push({ruleId:"UNDECLARED_CANDIDATE_CHANGE",file:f,line:1,message:`Candidate facts change ${f}, but the atomic change set does not declare it.`})}let g=e.changeMap?pt({changeMap:e.changeMap,changes:p,baseDependencies:r.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[]),candidateDependencies:o.ir.edges.flatMap(f=>f.to?[{from:f.from,to:f.to}]:[])}):void 0,h=[...l,...o.ir.violations].map(f=>({...f,nextAction:pe(f)})),u=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&u.length===0&&(g?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,resolverIdentity:n.resolverIdentity,compilerIdentity:n.compilerIdentity,compilerOptionsHash:n.compilerOptionsHash,tsconfigHash:n.tsconfigHash,baseCompilerOptionsHash:t.compilerOptionsHash,candidateCompilerOptionsHash:n.compilerOptionsHash,baseTsconfigHash:t.tsconfigHash,candidateTsconfigHash:n.tsconfigHash,evidenceRequirementsHash:n.evidenceRequirementsHash,baseFactsHash:t.factsHash,candidateFactsHash:n.factsHash,baseTreeHash:t.candidateTreeHash,candidateTreeHash:n.candidateTreeHash,baseCompleteness:r.completeness,candidateCompleteness:o.completeness,baseCompletenessReasons:r.completenessReasons,candidateCompletenessReasons:o.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...g?{convergence:g}:{},changes:p.sort((f,m)=>f.path<m.path?-1:f.path>m.path?1:0),violations:h,warnings:o.ir.warnings}}s(xs,"preflightResolvedChange");var eo="docs/diagnostics.md",wc="1.0";function k(e,t,n,r,o,i){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...i?.oftenAdvisory?{oftenAdvisory:!0}:{}}}s(k,"entry");var zn=Object.freeze([k("LAYER_IMPORT_VIOLATION","layer","Layer import not allowed","A module import (or re-export) crosses a layer edge that ark.config.json does not allow. The architecture contract forbids that dependency direction so outer infrastructure cannot leak into pure or inner layers.","Branch by import kind: constants/types/pure \u2192 adopt into DomainModel or SharedKernel (do not invent a port); kernel/events/bootstrap from Persistence \u2192 inject a port or move the map to SharedTypes (Persistence must not emit); define a port only when the target is a real use-case. Type-only edges use `import type`. Then preflight again. Do not weaken the layer rule without a hash-bound policy acknowledgement."),k("LAYER_INTENT_REFERENCE_VIOLATION","layer","Intent referenced across a blocked layer edge","A string intent (or intent-like reference) names a layer that the file\u2019s layer may not reach under the contract rules \u2014 the same plane as import edges, for event/intent coupling.","Reference that intent from a layer allowed to know about it (usually an adapter or application layer), or relocate the reference \u2014 then preflight again."),k("LAYER_REFERENCE_VIOLATION","layer","Layer reference blocked (snippet / AI gate)","Snippet analysis found an intent or string reference that would couple layers in a direction the architecture profile forbids.","Move the reference to an allowed layer or introduce a port/event boundary, then re-run the snippet gate."),k("CIRCULAR_DEPENDENCY","layer","Dependency cycle","Two or more modules import each other in a loop. Cycles make ownership unclear and break stable layer direction.","Extract the shared dependency into a third module, invert one edge behind a port, or merge units that are truly one \u2014 then preflight again."),k("FORBIDDEN_GLOBAL","capability","Forbidden ambient global or dual import","The file\u2019s layer lists this ambient (or its exact import dual, e.g. process / node:process) in forbiddenGlobals. Pure layers must not reach wall-clock, network, process, or similar effects directly.","Inject the capability through a small port (Clock, HttpPort, Config, \u2026), bind the implementation outside the walled layer, then preflight again."),k("CAPABILITY_VIOLATION","capability","Denied effect capability","The layer denies an effect capability (network, filesystem, clock, randomness, environment, process, persistence) and the candidate uses that effect via ambient or import evidence.","Define a capability port in the walled layer, bind the implementation in an adapter layer, then preflight again. Never mechanical-safe \u2014 port shape is a design decision."),k("RAW_EVENT_PUBLISH","publish","Raw event publish","Publish went through a raw string or object instead of a registered intent creator, bypassing Ark intent contracts and tooling.","Publish through a registered intent creator, then run Ark again."),k("PUBLISH_MISSING_SOURCE","publish","Publish missing metadata.source","A strict Ark publish call omitted metadata.source, so the publishing layer cannot be verified.","Add metadata.source to the publish call, then run Ark again."),k("PUBLISH_SOURCE_LAYER_MISMATCH","publish","Publish source layer mismatch","metadata.source resolves to a different layer than the file performing the publish.","Use a source intent owned by the same layer as this file, or move the publish call to the owning layer."),k("UNKNOWN_INTENT","publish","Unknown intent reference","Snippet analysis saw an intent string that is not registered in the intent registry / profile under check.","Register the intent or use a known intent name from the project registry, then re-run the gate."),k("DYNAMIC_IMPORT_NOT_ALLOWLISTED","safety","Non-literal dynamic import","A dynamic import(expr) cannot be resolved statically and the file is not on dynamicImportAllowlist. Unresolved dynamics can hide layer edges.","Rewrite to a static import when possible, or add only reviewed files to dynamicImportAllowlist after human sign-off."),k("DYNAMIC_REQUIRE_NOT_ALLOWLISTED","safety","Non-literal require","A require(expr) cannot be resolved statically and is not allowlisted \u2014 same hide-the-edge risk as dynamic import.","Prefer static import, or allowlist only reviewed files after sign-off."),k("TS_SUPPRESSION_THRESHOLD_EXCEEDED","safety","@ts-ignore / @ts-nocheck threshold","Count of TypeScript suppressions in governed production source exceeds safety.maxTsSuppressions.","Remove suppressions by fixing types, or raise the threshold only with an explicit production exception in ark.config.json."),k("ANY_CAST_THRESHOLD_EXCEEDED","safety","Explicit any cast threshold","Count of explicit any casts exceeds safety.maxAnyCasts.","Replace any with precise types, or raise the threshold only with a documented exception."),k("IN_MEMORY_STORE_IN_PRODUCTION_SOURCE","safety","In-memory store in production source","Governed production source references an Ark InMemory* store without safety.allowInMemory \u2014 durable systems should not ship ephemeral stores by accident.","Provide a durable store implementation, or set safety.allowInMemory only for an explicitly ephemeral service."),k("PEER_ISOLATION_DISABLED","safety","peerIsolation disabled on a rule","A same-layer or peer rule disables peerIsolation (or omits it where required), which allows cross-slice coupling the contract otherwise blocks.","Restore peerIsolation: true, or set safety.allowDisabledPeerIsolation only with a documented production exception."),k("ARKRULE_STRUCTURE","arkrules","ArkRule structure sensor failed","An opt-in ArkRules structure sensor (private state, factory shape, event publish, persistence write outside an aggregate, \u2026) failed on a governed file for a declared arkruleId.","Restore the declared structure for the ArkRule (see arkruleSource), then preflight again. Do not demote the rule without a hash-bound policy acknowledgement."),k("ARKRULE_INVARIANT","arkrules","ArkRule invariant failed","Reserved / remediation-recognized code for invariant-plane failures bound to an ArkRule id (coverage path also emits INVARIANT_UNCOVERED).","Fix the invariant for the ArkRule declared in arkrules/<Layer>.json, then preflight again. Do not demote without acknowledgement."),k("ARKRULE_SCOPE_EMPTY","arkrules","ArkRule appliesTo matched zero files","An ArkRule\u2019s appliesTo globs matched no governed files \u2014 the rule cannot observe what it claims to protect.","Fix appliesTo globs so they match governed files, or remove the rule. Enforced empty scope fails; advisory empty scope warns.",{oftenAdvisory:!0}),k("ARKRULE_HINT_BUDGET_EXHAUSTED","arkrules","Structural-hint budget exhausted","orchestration-only, thin-adapter, and writes-via-aggregate only evaluate files the hint loader preloaded. When eligible governed files exceed that budget (coverage.maxFiles, default 400 \u2014 there is no arkrules.hintBudget), those sensors never saw the rest of their scope. Enforced + unreviewed is not green. The finding names exact hinted/governed counts and per-sensor reviewed N/M of scope.","Raise coverage.maxFiles in ark.config.json (this cap also bounds structural-hint preload; --doctor names the coupling) so hinted/governed counts match, then re-run with --strict-config. An enforced hint sensor that cannot see its scope fails strict."),k("INVARIANT_UNCOVERED","arkrules","Invariant without coverage evidence","An ArkRules invariant is under contract but no covering test title or declared symbol evidence was found (or coverage is partial). Kind is never-had-tests (adopt residual) vs tests-disappeared (suite exists).","Add a test title or declared symbol covering the arkruleId, then preflight again. Treat never-had-tests as adopt residual; treat tests-disappeared as a regression. Missing test globs report partial \u2014 never fake green. When the message reports an exhausted file budget, raise coverage.maxFiles (or narrow coverage.testGlobs) in ark.config.json."),k("INVARIANT_COVERAGE_OUTSIDE_ROOTS","arkrules","Covering test outside the declared coverage roots","The only test naming this invariant sits outside coverage.coverageRoots \u2014 the places the project declares its runner executes. ArkGate matches declared text and never executes tests, so it cannot tell whether that file is ever run: coverage there is a test that exists, not a test that runs.","Move the test under a declared coverage root, or add its root to coverage.coverageRoots in ark.config.json. Advisory: it never fails strict, but promotion to enforced refuses on it.",{oftenAdvisory:!0}),k("ARKRUN_MISSING_ROOT","arkrun","No kernel factory in composition roots","The ArkRun extra is on but no createArkKernel / createStrictArkKernel / createArkKernelFromConfig / createStrictArkKernelFromConfig factory was found in arkRun.compositionRoots, so agents can skip the kernel while the write gate stays green.","Import createStrictArkKernel from arkgate/runtime (same npm package; @arkgate/runtime is deprecated) and call it in a composition root listed in arkRun.compositionRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKRUN_KERNEL_IN_DOMAIN","arkrun","Domain-role layer imports the kernel","A Domain-role layer imports arkgate/runtime, @arkgate/runtime, or kernel types. Domain stays kernel-free; composition roots and adapters own the factory.","Move the kernel import out of the Domain-role layer into a composition root or adapter. Import from arkgate/runtime (same npm package; @arkgate/runtime is deprecated), then preflight again. Never mechanical-safe."),k("ARKRUN_DIRECT_NEW","arkrun","Managed type constructed with new","A managed non-Domain file constructs an admitted type with new outside an ArkRun composition-root factory, skipping kernel resolve/registration.","Resolve the type from the kernel instead of constructing it with new, then preflight again. Never mechanical-safe \u2014 rewiring construction is a design decision."),k("ARKRUN_UNDECLARED_EMIT","arkrun","Emit name not in raises/sends","A publisher / publish / raise / send call-site literal is not listed in the file\u2019s raises or sends declaration.","Add the existing call-site name to raises or sends on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new emit stays judgment."),k("ARKRUN_UNDECLARED_HANDLE","arkrun","Handle name not in reactsTo","A subscribe / registerHandler call-site literal is not listed in the file\u2019s reactsTo declaration.","Add the existing call-site name to reactsTo on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new handle stays judgment."),k("ARKRUN_UNDECLARED_DEPEND","arkrun","Depend name not in uses","A resolve / resolveSingleton call-site literal is not listed in the file\u2019s uses declaration.","Add the existing call-site name to uses on the managed component, then preflight again. Mechanical-safe only when that literal already exists and the edit is the declaration list; inventing a new depend stays judgment."),k("ARKRUN_TRANSPORT_BYPASS","arkrun","Homemade broker or emitter import","A managed layer imports a closed broker/queue/emitter specifier (EventEmitter, queue clients, \u2026) instead of the ArkRun kernel transport.","Send through the ArkRun kernel transport instead of importing that broker or emitter, then preflight again. Never mechanical-safe \u2014 homemade buses stay judgment."),k("ARKORDER_MISSING_PLANE","arkorder","No createOrderPlane in plane roots","The ArkOrder extra is on but no createOrderPlane factory was found in arkOrder.planeRoots, so agents can skip the pattern plane while the write gate stays green.","Import createOrderPlane from arkgate/order and call it in a plane root listed in arkOrder.planeRoots, then preflight again. Never mechanical-safe \u2014 factory placement is a design decision."),k("ARKORDER_KERNEL_IN_DOMAIN","arkorder","Domain-role layer imports the order plane","A Domain-role layer imports arkgate/order. Domain stays plane-free; planeRoots own the factory.","Move the arkgate/order import out of the Domain-role layer into a plane root or adapter, then preflight again. Never mechanical-safe."),k("ARKORDER_GENERIC_UPDATE","arkorder","Generic update of a big product choice","A call to update/patch/set rewrites a named product choice (like billing plan) as if it were a seat count.","Don't use a generic update. First freeze with release(). Later, propose the change, then apply it."),k("ARKORDER_TOO_MANY_PARAMS","arkorder","Too many slow keys","\u03BE has more keys than arkOrder.maxXiKeys. Haken requires a few slow modes, not a dump of microstate.","Cut \u03BE to the slow keys that actually slave the rest, then preflight again. Never mechanical-safe."),k("ARKORDER_INGEST_WRITES_XI","arkorder","ingest assigned into \u03BE","An ingest() result is written into a Release or \u03BE store. ingest may absorb, escalate_up, or hold; it never mints a pattern.","Keep ingest results as absorb/escalate_up/hold only. Change \u03BE with proposeRelease then apply(ProposeResult). Never mechanical-safe."),k("ARKORDER_XI_FIELD_WRITE","arkorder","Big product choice written like a seat count","A use-case writes a named product choice (like billing plan) through a database update. Invoices and seats can flow. That choice cannot.","Keep invoices and seats as events. Change the choice through the valve (proposeRelease then apply), not a generic update."),k("ARKORDER_INFORMATION_BUDGET","arkorder","Projection observes a forbidden kind","h(\u03BE) allowedKinds includes a kind listed in informationBudget.cannotObserve. A scale may not look at what it was told not to see.","Cut that kind from the projector or from cannotObserve, then preflight again. Never mechanical-safe."),k("ARKORDER_XI_TTL","arkorder","Slow key carries a freshness field","\u03BE named ttl/freshUntil/maxAge. Freshness belongs on \u03C3. A slow parameter that expires per transaction is not slow.","Move freshness onto \u03C3 (freshUntil) and keep \u03BE stable, then preflight again. Never mechanical-safe."),k("ARKORDER_STALE_SIGMA","arkorder","\u03C3 is stale","ingest ran after \u03C3.freshUntil (or sigmaMaxAgeMs). \u03BE does not TTL.","Call refreshSigma and ingest again, or proposeRelease then apply(ProposeResult) if the pattern changed. Never mechanical-safe."),k("ARKORDER_UNVALVED_RELEASE","arkorder","Unvalved second freeze of \u03BE","release() ran after a pattern was already frozen and the new \u03BE differs. First freeze is release(); later pattern change is proposeRelease then apply.","Change \u03BE with proposeRelease then apply(ProposeResult). release() is only the first freeze. Never mechanical-safe."),k("INVALID_CHANGE_PATH","preflight","Unsafe change path","A change set entry is not a safe, non-empty project-relative path (absolute, escape, empty, or NUL).","Use canonical project-relative paths only in the atomic change set, then preflight again."),k("DUPLICATE_CHANGE_PATH","preflight","Duplicate path in change set","The atomic change set lists more than one operation for the same path.","Collapse to one create/update/delete per path, then preflight again."),k("DELETE_TARGET_MISSING","preflight","Delete target missing","A delete operation targets a path that is not present in the supplied base tree.","Remove the delete, or include the file in the base tree facts, then preflight again."),k("CHANGE_SET_EMPTY","preflight","Empty change set","Atomic preflight was invoked with no create, update, or delete operations.","Provide at least one change operation, then preflight again."),k("FACTS_IDENTITY_MISMATCH","preflight","Base/candidate facts identity mismatch","Base and candidate resolved facts disagree on resolver, compiler, evidence requirements, or package identity \u2014 verdicts would not be comparable.","Regenerate both fact snapshots with the same resolver/compiler/evidence requirements, then preflight again."),k("CANDIDATE_DELETE_NOT_APPLIED","preflight","Candidate still contains deleted path","Facts claim a delete, but the candidate tree still includes the path.","Ensure the candidate facts apply the delete (path absent), then preflight again."),k("CANDIDATE_CHANGE_MISSING","preflight","Declared change missing from candidate","The change set declares a create/update whose path is missing from candidate facts.","Include the new content in the candidate facts (or drop the operation), then preflight again."),k("CANDIDATE_CONTENT_HASH_MISMATCH","preflight","Candidate content hash mismatch","The candidate file content hash does not match the hash expected for the declared change.","Rebuild candidate facts from the exact proposed content, then preflight again."),k("UNDECLARED_CANDIDATE_CHANGE","preflight","Undeclared candidate change","Candidate facts differ from base for a path that was not listed in the explicit change set.","Declare every path that changes in the atomic change set, then preflight again."),k("ATOMIC_PREFLIGHT_UNAVAILABLE","preflight","Atomic preflight unavailable","The host/MCP path could not run the atomic preflight engine (missing facts, incomplete setup, or unsupported mode).","Use resolved-candidate facts / ark_prepare_change with a complete batch, or fall back to ark-check on disk. Do not treat missing preflight as green."),k("DESIGN_SMELL_REGRESSION","preflight","Design smell regression on base-relative ratchet","Compared to the base ref, the candidate introduces a created-path domain-logic-in-ui file under --strict-merge, or introduces or worsens a blocking design-smell class under --fail-on-new-smells.","Move the new UI business rule out of the created file (or revert a --fail-on-new-smells regression), then re-run with the same base ref."),k("ANALYSIS_PARSE_INCOMPLETE","analysis","Parse incomplete","Governed source could not be fully parsed; evidence includes the TypeScript diagnostic (line + message). Incremental mid-edit parse is normal for agents. Contract exclude paths skip the write hook.","Finish the source or fix the reported syntax error, then re-run `npx arkgate-check`. The write hook does not deny solely on mid-edit parse. Partial never means pass."),k("LEXICAL_EVIDENCE_INCOMPLETE","analysis","Lexical evidence incomplete","Single-file validation cannot prove project module resolution. The write hook is already the verdict.","Re-run `npx arkgate-check --root . --config ark.config.json`, or treat the hook deny as final. Do not call ark_prepare_change from a hook deny."),k("ANALYSIS_COVERS_NO_FILES","analysis","Analysis covered no files","No file matched the contract include and layer patterns under the analyzed root, so the run had nothing to check. Every rule is vacuously satisfied on an empty set: a green here would read exactly like a green over a governed tree while certifying nothing. Usual causes are a --root that is not the tree the contract describes (including a contract found outside the requested root, whose directory is then adopted as the project root), include / exclude patterns that match nothing, or layer patterns written for a different layout.","Point --root at the tree the contract describes, or keep the contract inside that tree, or fix the include / exclude / layer patterns so they match real files \u2014 then re-run `npx arkgate-check --root . --config ark.config.json`. This is a refusal about ArkGate\u2019s own inputs, not a finding about your code; no baseline or policy acknowledgement can suppress it."),k("ANALYSIS_HOST_UNAVAILABLE","analysis","Analysis host unavailable","No usable TypeScript / analysis host was available for this invocation.","Install a supported TypeScript version visible to the project, then re-run. Unavailable analysis is fail-closed."),k("ADAPTER_NOT_ALLOWED_FOR_PORT","adapter","Adapter not allowed for port","Runtime/port wiring selected an adapter implementation that the architecture profile does not allow for that port.","Bind an allowed adapter for the port, or adjust the profile with an explicit policy decision \u2014 then re-run."),k("FORBIDDEN_PATTERN","snippet-policy","Forbidden regex pattern","Snippet content matched a project or profile forbiddenPatterns rule.","Remove or rewrite the matching code so the pattern no longer matches, then re-run the snippet gate."),k("FORBIDDEN_SUBSTRING","snippet-policy","Forbidden substring","Snippet content contained a forbidden substring from the AI gate options/profile.","Remove the forbidden substring, then re-run the snippet gate."),k("FORBIDDEN_IMPORT","snippet-policy","Forbidden import target","Snippet imported or required a module listed as forbidden for the active profile.","Import an allowed module or inject the dependency behind a port, then re-run."),k("POLICY_VIOLATION","snippet-policy","Policy engine violation","A registered Policy failed on the snippet or generated code under evaluation.","Adjust the code to satisfy the named policy, or change the policy only through an explicit contract decision."),k("EXTENSION_ERROR","snippet-policy","AI gate extension error","A registered AICodeGate extension threw while analyzing the snippet.","Fix or remove the failing extension; do not ignore extension failures as pass."),k("AST_ANALYZER_ERROR","snippet-policy","AST analyzer error","Built-in AST/symbol analysis failed (host error or unexpected analyzer exception).","Ensure TypeScript host and snippet are valid; re-run. If the analyzer crashes on valid input, file a bug with a minimal fixture."),k("CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST","config","Invalid dynamicImportAllowlist","dynamicImportAllowlist is present but not an array of file globs.","Set dynamicImportAllowlist to an array of project-relative globs (or omit it).",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY","config","Invalid safety object","The safety field is present but not an object.","Use a safety object with optional maxTsSuppressions, maxAnyCasts, allowInMemory, allowDisabledPeerIsolation.",{oftenAdvisory:!0}),k("CONFIG_INVALID_SAFETY_THRESHOLD","config","Invalid safety threshold","A safety threshold (maxTsSuppressions / maxAnyCasts) is not a non-negative integer.","Set each threshold to a non-negative integer.",{oftenAdvisory:!0}),k("CONFIG_NO_LAYERS","config","No layers configured","ark.config.json has no file layers, so import-boundary enforcement cannot classify files.","Declare at least one layer with name + patterns (or run ark start / a preset).",{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_NAME","config","Layer missing name","A configured layer entry has no name.","Give every layer a unique non-empty name.",{oftenAdvisory:!0}),k("CONFIG_INVALID_FORBIDDEN_GLOBALS","config","Invalid forbiddenGlobals","A layer\u2019s forbiddenGlobals is not an array of strings; the entry is ignored.",'Use an array of strings (e.g. ["fetch", "Date.now"]).',{oftenAdvisory:!0}),k("CONFIG_LAYER_WITHOUT_PATTERNS","config","Layer without patterns","A named layer has no file patterns and will never classify files.","Add patterns globs that match the layer\u2019s source tree.",{oftenAdvisory:!0}),k("CONFIG_INVALID_LAYER_PATTERN","config","Invalid layer pattern","A layer pattern is not a valid glob / failed to compile.","Fix the pattern syntax for that layer.",{oftenAdvisory:!0}),k("CONFIG_LAYER_PATTERN_NO_MATCHES","config","Layer pattern matched no files","A layer pattern matched zero included files (often a typo or include mismatch). Reserved/allowEmpty houses do not emit this.","Adjust the pattern or include roots, or mark the layer reserved/allowEmpty if the glob is a future house.",{oftenAdvisory:!0}),k("CONFIG_DUPLICATE_LAYER","config","Duplicate layer name","The same layer name appears more than once in configuration.","Rename or merge duplicate layer entries.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_FROM_LAYER","config","Rule unknown from layer","A dependency rule references a source layer name that is not declared.","Fix the rule\u2019s from field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_RULE_UNKNOWN_TO_LAYER","config","Rule unknown to layer","A dependency rule references a target layer name that is not declared.","Fix the rule\u2019s to field to a declared layer name.",{oftenAdvisory:!0}),k("CONFIG_AMBIGUOUS_LAYERS","config","Ambiguous layer classification","Some files match multiple layers at equal specificity; classification falls back to declaration order.","Disambiguate overlapping patterns so each file has one clear layer owner.",{oftenAdvisory:!0}),k("CONFIG_UNCLASSIFIED_FILES","config","Unclassified included files","Included source files match no layer pattern; import rules will not enforce on them.","Extend layer patterns or narrow include so every governed file is classified.",{oftenAdvisory:!0}),k("LITERAL_PATH_DRIFT","drift","Literal path moved by a rename","A repo path written inside a string, a comment or a docstring no longer resolves, and the rename set says where it went. Nothing in the gate sees this class: `tsc` resolves imports, not strings, and ESLint does not either, so the rename compiles green and the reference lies afterwards. It appears in four forms \u2014 the tsconfig alias, a relative literal, a path written without the include-root prefix, and prose \u2014 and a hand sweep reliably covers one of them.","Apply the suggested replacement, or re-run `npx arkgate-check --path-drift --base-ref <ref> --write` to apply every writable anchored replacement at once. The rewrite is mechanical and one-directional: the destination comes from the rename, it must itself resolve and be path-shaped, and the token is rewritten in the form the author wrote it in. A destination that leaves the alias root of the literal is reported with the target only and must be rewritten by hand."),k("LITERAL_PATH_UNRESOLVED","drift","Literal path does not resolve","A literal that looks like a repo path does not resolve under this root, and no rename explains where it went. Unlike LITERAL_PATH_DRIFT this is a candidate, not a verdict: with nothing to anchor it, ArkGate cannot tell a dead reference from an illustrative path in a comment, an example in documentation, or a path belonging to another tree.","Read the candidate and decide: fix the path, or leave it. Advisory only \u2014 it never fails a run and is never rewritten by --write, because there is no destination to propose. Run `--path-drift --all` to list the sweep.",{oftenAdvisory:!0}),k("ARK_UNKNOWN","meta","Unknown diagnostic","A diagnostic lacked a stable ruleId/code; adapters may emit this fallback so agents never see an empty id.","Resolve the underlying finding without weakening ark.config.json, then run Ark again. Prefer fixing the producer to emit a catalogued ruleId.")]),to=new Map(zn.map(e=>[e.ruleId,e])),Cc=Object.freeze(zn.map(e=>e.ruleId));function xc(e){return typeof e=="string"&&e.length>0&&to.has(e)}s(xc,"isKnownDiagnosticCode");function Oc(e){return typeof e!="string"||e.length===0?!1:to.has(e)?!0:e.startsWith("ARKRULE_")}s(Oc,"isCataloguedOrArkRuleFamily");function qn(e){if(!(typeof e!="string"||e.length===0))return to.get(e)}s(qn,"getDiagnosticCatalogEntry");function Os(e){return`#${qn(e)?.docsAnchor??e}`}s(Os,"diagnosticDocsFragment");function Pc(e){return`${eo}${Os(e)}`}s(Pc,"diagnosticDocsPath");function _c(){return{schemaVersion:"1.0",docsPath:eo,codes:zn}}s(_c,"serializeDiagnosticCatalog");function Tc(e){return qn(e)?.fix}s(Tc,"catalogFixForRuleId");function Nc(e){return qn(e)?.why}s(Nc,"catalogWhyForRuleId");var Dc="1.1";var Lc="1.0";var Vt=class{static{s(this,"InMemoryReadModelStore")}states=new Map;load(t){return this.states.get(t)}save(t,n){this.states.set(t,n)}clear(t){t?this.states.delete(t):this.states.clear()}};function Fc(e){return typeof e.initialState=="function"?e.initialState():e.initialState}s(Fc,"initialState");var Yn=class{static{s(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new Vt,this.auditTrail=t.auditTrail}register(t){if(this.definitions.has(t.name))throw new Error(`Projection "${t.name}" is already registered.`);this.definitions.set(t.name,t),this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(t){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(t.intent))continue;let o=await this.store.load(r.name)??Fc(r),i=await r.project(t,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:t.intent,lastCorrelationId:t.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:t.intent,correlationId:t.metadata.correlationId,causationId:t.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(t){return this.store.load(t)}getCheckpoint(t){return this.checkpoints.get(t)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let t of this.definitions.values())this.checkpoints.set(t.name,{projection:t.name,appliedCount:0})}};function Xn(e){return new Yn(e)}s(Xn,"createProjectionRegistry");var Zn="1.0";function Mc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}s(Mc,"policyId");var no=class{constructor(t){this.data=t}data;static{s(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Jn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,i=e.profile,a=e.projections,l=e.eventContracts,c=e.observability,p=t?t.list().map(E=>({name:E.name,dependencies:t.getDependencies(E.name),productions:t.getProductions(E.name)})):[],g=t?t.getAllRelationships():[],h=n?n.getPolicies().map(E=>({id:Mc(E.name),name:E.name,severity:E.severity,tags:E.tags?[...E.tags]:void 0,owner:E.owner,version:E.version,rationale:E.rationale,enforcementMode:E.enforcementMode,deprecated:E.deprecated,replacedBy:E.replacedBy,description:E.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],u=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},m=u.filter(E=>(E.emits?.length??0)>0||(E.consumes?.length??0)>0).map(E=>({entity:E.name,emits:E.emits,consumes:E.consumes})),y=a?a.list().map(E=>({name:E.name,sourceIntents:E.sourceIntents,checkpoint:a.getCheckpoint(E.name)})):[],v={schemaVersion:"1.0",version:gr,exportedAt:new Date().toISOString(),intents:p,relationships:g,policies:h,entities:u,graph:f,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:y,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:m}};return new no(v)}s(Jn,"createArkManifest");var Ps=0;function _s(e){return Ps+=1,`${e}-${Date.now()}-${Ps}`}s(_s,"createWorkflowId");function ro(e){return e instanceof Error?e.message:String(e)}s(ro,"errorMessage");function $c(e){return new Promise(t=>{setTimeout(t,e)})}s($c,"sleep");async function Kc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,i=new Promise((a,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${t}ms.`);r.abort(c),l(c)},t)});try{return await Promise.race([e(r.signal),i])}finally{o&&clearTimeout(o)}}s(Kc,"withTimeout");var jt=class{static{s(this,"InMemoryWorkflowStore")}snapshots=new Map;save(t,n){let r=this.snapshots.get(t.id);if(r&&r.version!==t.version)throw new Error(`Optimistic concurrency conflict for workflow ${t.id}`);let o=(t.version??0)+1;this.snapshots.set(t.id,{...t,version:o,context:{...t.context}}),t.version=o}get(t,n){let r=this.snapshots.get(t);return r?{...r,context:{...r.context}}:void 0}list(t){return Array.from(this.snapshots.values()).filter(n=>!t||n.workflowName===t).map(n=>({...n,context:{...n.context}}))}claim(t,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=t,i.expiresAt=new Date(o+n).toISOString();let l=(i.version??0)+1;return i.version=l,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},oo=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new jt}bus;options;static{s(this,"WorkflowEngineImpl")}definitions=new Map;store;register(t){if(this.definitions.has(t.name))throw new Error(`Workflow "${t.name}" is already registered.`);let n=new Set;for(let r of t.steps){if(n.has(r.name))throw new Error(`Workflow "${t.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(t.name,t),t.startOn){let r=t.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(t.name,r.mapEventToPayload(o))})}}async start(t,n,r={}){let o=this.definitions.get(t);if(!o)throw new Error(`Workflow "${t}" is not registered.`);let i=new Date().toISOString(),a={id:r.id??_s(t),version:0,workflowName:t,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:t}),this.executeSnapshot(a,o,r.tx)}async resume(t,n={}){let r=await this.get(t,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(t,n,r){try{let o=n.steps.filter(i=>!t.completedSteps.includes(i.name));for(let i of o)await this.runStep(t,i,r);return t.status="completed",t.currentStep=void 0,t.completedAt=new Date().toISOString(),t.updatedAt=t.completedAt,await this.store.save(t,r),await this.audit("workflow.completed",t,{workflowName:t.workflowName}),{...t,context:{...t.context}}}catch(o){throw await this.compensate(t,n.steps,o,r),t.status="failed",t.currentStep=void 0,t.error=ro(o),t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.failed",t,{workflowName:t.workflowName,error:t.error,failedStep:t.failedStep}),o}}async get(t,n){return this.store.get(t,n)}async list(t){return this.store.list(t)}async runStep(t,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);t.currentStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r);for(let a=1;a<=i;a+=1){t.attempts[n.name]=a,await this.store.save(t,r);let l;try{l=await Kc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(a<i){o.delayMs&&await $c(o.delayMs);continue}throw t.failedStep=n.name,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.failed",t,{step:n.name,attempt:a,error:ro(c)}),c}l&&Object.assign(t.context,l),t.completedSteps.push(n.name),t.currentStep=void 0,t.updatedAt=new Date().toISOString(),await this.store.save(t,r),await this.audit("workflow.step.completed",t,{step:n.name,attempt:a});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(t,n,r,o){t.status="compensating",t.updatedAt=new Date().toISOString(),await this.store.save(t,o);let i=n.filter(a=>t.completedSteps.includes(a.name));for(let a=i.length-1;a>=0;a-=1){let l=i[a];if(l.compensate)try{await Promise.resolve(l.compensate(t.context,this.bus,r)),await this.audit("workflow.compensation.completed",t,{step:l.name})}catch(c){await this.audit("workflow.step.failed",t,{step:l.name,compensation:!0,error:ro(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Bt(e,t){return new oo(e,t)}s(Bt,"createWorkflowEngine");function Ts(e,t,n={}){let r=Bt(t,n),o={name:e.name,steps:e.steps};r.register(o);let i=n.id??_s(e.name),a="idle",l=[];return{id:i,definition:e,get status(){return a},get completedSteps(){return[...l]},async run(c){a="running",l=[];try{let p=await r.start(e.name,c,{id:i});a=p.status==="waiting"?"idle":p.status,l=[...p.completedSteps]}catch(p){let g=await r.get(i);throw a=g?.status==="waiting"?"idle":g?.status??"failed",l=g?.completedSteps??[],p}}}}s(Ts,"createSaga");mt();function Fs(e){return Object.keys(e).sort()}s(Fs,"sortedKeys");function co(e,t,n,r){if(e===t)return;if(e===null||t===null||typeof e!=typeof t){r.push({path:n,left:e,right:t});return}if(typeof e!="object"||typeof t!="object"){e!==t&&r.push({path:n,left:e,right:t});return}if(Array.isArray(e)||Array.isArray(t)){let l=Array.isArray(e)?e:[],c=Array.isArray(t)?t:[],p=Math.max(l.length,c.length);for(let g=0;g<p;g+=1)co(l[g],c[g],`${n}[${g}]`,r);return}let o=e,i=t,a=new Set([...Fs(o),...Fs(i)]);for(let l of[...a].sort())co(o[l],i[l],n?`${n}.${l}`:l,r)}s(co,"walk");function Ms(e){return{schemaVersion:e.schemaVersion,kernelInstanceId:e.kernelInstanceId,components:e.components.map(t=>({id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends],...t.extendedInfo?{extendedInfo:{...t.extendedInfo}}:{}})),...e.decisionTape?{decisionTape:e.decisionTape.map(t=>({xiHash:t.xiHash,event:{kind:t.event.kind,...t.event.payload?{payload:{...t.event.payload}}:{}},residual:{...t.residual}}))}:{}}}s(Ms,"shadowInformationPackage");function uo(e,t){let n=[];return co(e,t,"",n),{equal:n.length===0,diffs:n}}s(uo,"compareInformationPackages");function $s(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(uo(e[n-1],e[n]));return t}s($s,"replayInformationPackages");ir();Jt();ln();ln();async function ur(e,t={}){let n=on({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Js(),Zs));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}s(ur,"startArkRunInspector");ir();ln();mt();Jt();mt();var Ed=new Set(["singleton","transient"]);function Qs(e){let t={id:e.id,lifetime:e.lifetime,uses:[...e.uses],reactsTo:[...e.reactsTo],raises:[...e.raises],sends:[...e.sends]};if(e.extendedInfo){let n=e.extendedInfo;t.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 t}s(Qs,"cloneComponent");function vd(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Ed.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}s(vd,"closedLifetime");function ea(){let e=new Map,t=new Map,n=new Set;function r(a){let l=e.get(a);if(!l)throw new Error(`ArkRun component "${a}" is not registered.`);return l}s(r,"mustRecord");function o(a,l){if(!l.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 l.factory()}finally{n.delete(a)}}s(o,"instantiate");function i(a,l){if(t.has(a))return t.get(a);let c=o(a,l);return t.set(a,c),c}return s(i,"singleton"),{register(a){let l=typeof a?.id=="string"?a.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(e.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=vd(a.lifetime),p=ao({id:l,lifetime:c,uses:a.uses,reactsTo:a.reactsTo,raises:a.raises,sends:a.sends,extendedInfo:a.extendedInfo});if(!p)throw new Error("ArkRun component id must be a non-empty string.");let g=typeof a.factory=="function"?a.factory:void 0;return e.set(l,{component:p,factory:g}),Qs(p)},resolve(a){let l=r(a);return l.component.lifetime==="transient"?o(a,l):i(a,l)},resolveSingleton(a){let l=r(a);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${a}" is transient; resolveSingleton requires lifetime "singleton".`);return i(a,l)},snapshotComponents(){return[...e.values()].map(a=>Qs(a.component))}}}s(ea,"createComponentRegistry");Jt();function Sd(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new Ee(e.source,t.source);return t.source=e.source,t}s(Sd,"stampMetadata");function wd(){}s(wd,"ignoreDetachedFailure");async function vo(e,t,n,r={}){let o=sr({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),i=Sd(r),a=await e.eventBus.dispatch(t,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers});if(o.deliveredVia==="broker"&&e.broker){let l=Promise.resolve(e.broker.send(a));o.awaitHandoff?await l:l.then(void 0,wd)}return o}s(vo,"sendOnArkRunTransport");var So=1e3,ta=0;function Cd(){return ta+=1,`ark-kernel-${Date.now()}-${ta}`}s(Cd,"nextKernelInstanceId");function na(e,t){let n=e.constructor?.name;return typeof n=="string"&&n.length>0?n:t}s(na,"portConstructorId");function cn(e={}){let t=e.strict??!0,n=e.instanceId??Cd(),r=e.profile??it,o=e.maxHistorySize??So,i=mn(),a=xn(),l=e.metadata??Fn(),c=e.auditTrail===void 0,p=e.auditTrail??wn({maxRecords:o}),g=e.eventContracts??En(),h=e.eventBuffer===void 0&&e.outbox===void 0,u=e.eventBuffer??e.outbox??new De,f=e.projections??Xn({auditTrail:p}),m=new _e([An(r),...e.policies??[]]),y=s(()=>{On(i,a,{requireRegisteredTargets:!0})},"syncGraph"),v=e.ephemeral??!0,E=e.broker,A=new rt({intentRegistry:i,dependencyGraph:a,policyEngine:m,strictRegistry:!0,validateIntentNaming:!0,auditTrail:p,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:u,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async D=>{await f.apply(D)}}),b=Bt(A,{auditTrail:p}),w=vn({registry:i,eventBus:A,graph:a}),N=ea(),I=typeof E?.send=="function",T=h?"InMemoryEventBuffer":na(u,"EventBufferStore"),ee=c?"InMemoryAuditStore":na(p,"AuditTrail"),ge=sn({stores:[Ue(T,"outbox"),Ue(ee,"audit"),Ue("InMemoryWorkflowStore","workflow")]}),je={instanceId:n,profile:r,registry:i,graph:a,metadata:l,auditTrail:p,eventContracts:g,eventBuffer:u,outbox:u,projections:f,policyEngine:m,eventBus:A,workflowEngine:b,observability:w,publisher(D){let ue=A.createPublisher(D);return{source:ue.source,publish:ue.publish,send(X,Be,kt={}){return vo({eventBus:A,broker:E,defaultEphemeral:v},X,Be,{...kt,source:ue.source})}}},send(D,ue,X={}){return vo({eventBus:A,broker:E,defaultEphemeral:v},D,ue,X)},register(D){return N.register(D)},resolve(D){return N.resolve(D)},resolveSingleton(D){return N.resolveSingleton(D)},getDependencyInformationPackage(){return ke({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(D){return or({kernelInstanceId:n,components:N.snapshotComponents()},D)},getInspectorSnapshot(D){return dr({kernelInstanceId:n,host:D?.host,port:D?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:w.report(),ephemeralDefault:v,brokerBound:I,hardening:ge})},startInspector(D){return ur({getInspectorSnapshot:s(X=>je.getInspectorSnapshot(X),"getInspectorSnapshot"),requestGraph:s(X=>je.requestGraph(X),"requestGraph"),async listInspectorOutbox(){let[X,Be]=await Promise.all([u.list("pending"),u.list("failed")]);return Ge([...X,...Be],{sampleLimit:re})},async listInspectorWorkflows(){return Ve(await b.list(),{sampleLimit:re})}},D)},syncGraph:y,manifest(){return y(),Jn({registry:i,policyEngine:m,metadata:l,graph:a,profile:r,projections:f,eventContracts:g,observability:w})}};return je}s(cn,"createArkKernel");function wo(e={}){return cn({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}s(wo,"createStrictArkKernel");function Co(e,t={}){let{profileName:n,...r}=t;return{...r,profile:Dn(e,{name:n})}}s(Co,"createOptionsFromConfig");function ra(e,t={}){return cn(Co(e,t))}s(ra,"createArkKernelFromConfig");function oa(e,t={}){return wo(Co(e,t))}s(oa,"createStrictArkKernelFromConfig");function ia(e,t={}){return xo(Co(e,t))}s(ia,"createLenientArkKernelFromConfig");function xo(e={}){return cn({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}s(xo,"createLenientArkKernel");export{jr as ANALYSIS_IR_SCHEMA_VERSION,Po as ARK_ANALYSIS_RESULT_SCHEMA,pn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Lc as ARK_DESIGN_DELTA_SCHEMA_VERSION,Dc as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,io as ARK_RUN_COMPONENT_LIFETIMES,ht as ARK_RUN_EPHEMERAL_DEFAULT,mo as ARK_RUN_GRAPH_DEFAULT_SLICE,Vs as ARK_RUN_GRAPH_NODE_KINDS,js as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,go as ARK_RUN_GRAPH_SCHEMA_VERSION,yo as ARK_RUN_GRAPH_SLICES,Bs as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Qn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,ar as ARK_RUN_INSPECTOR_DEFAULT_HOST,Io as ARK_RUN_INSPECTOR_DEFAULT_PORT,en as ARK_RUN_INSPECTOR_EVENTS_PATH,tn as ARK_RUN_INSPECTOR_GRAPH_PATH,re as ARK_RUN_INSPECTOR_MONITOR_SAMPLE_LIMIT,nn as ARK_RUN_INSPECTOR_OUTBOX_PATH,ko as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Qt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,bo as ARK_RUN_INSPECTOR_SSE_EVENT,Eo as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,rn as ARK_RUN_INSPECTOR_WORKFLOWS_PATH,Zt as ARK_RUN_TRANSPORT_KINDS,le as ArkRunInspectorBindError,Rt as ArkRunInspectorProductionError,So as DEFAULT_MAX_HISTORY_SIZE,zn as DIAGNOSTIC_CATALOG,wc as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,eo as DIAGNOSTIC_DOCS_RELATIVE_PATH,Cc as DIAGNOSTIC_RULE_IDS,wt as EventContractRegistryImpl,Ze as EventContractViolationError,Ct as InMemoryAuditStore,De as InMemoryEventBuffer,oi as InMemoryOutboxStore,Vt as InMemoryReadModelStore,jt as InMemoryWorkflowStore,We as IntentRegistry,Q as InvalidArkRunGraphQueryError,yt as InvalidArkRunSendOptionError,Ye as InvalidIntentNameError,Xe as LayerPolicyContextError,Zn as MANIFEST_SCHEMA_VERSION,Je as ObservedLayerFlowViolationError,qr as POLICY_DELTA_SCHEMA_VERSION,_e as PolicyEngine,be as PolicyViolationError,Vr as RESOLVED_CANDIDATE_FACTS_SCHEMA,Me as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,Ee as SourceMetadataOverrideError,Te as UnknownEventSourceError,qe as UnregisteredIntentError,pt as analyzeArchitectureConvergence,Gn as analyzeChange,Qi as analyzePolicyDelta,Ut as analyzeProject,Gt as analyzeResolvedProject,Ls as appendDecisionTape,Ar as architecturalPolicies,rr as arkRunGraphQueryFromSearchParams,Ie as arkRunInspectorUrl,sn as buildArkRunInspectorHardening,Ge as buildArkRunInspectorOutboxMonitor,dr as buildArkRunInspectorSnapshot,Ve as buildArkRunInspectorWorkflowsMonitor,ke as buildDependencyInformationPackage,kn as buildPublishPolicyContext,Tc as catalogFixForRuleId,Nc as catalogWhyForRuleId,Cr as checkAdapterGovernance,vi as checkContract,Yr as classifyArkPolicyDelta,Ue as classifyArkRunInspectorStoreDurability,nr as closeArkRunGraphQuery,Ao as closedArkRunEphemeral,Ro as closedArkRunTransportKind,Wn as collectAnalysisConfigWarnings,ct as collectForbiddenCapabilityUses,uo as compareInformationPackages,Ni as createAICodeGate,Ei as createAdapter,ma as createAdapterResult,Nn as createArchitectureProfile,Dn as createArchitectureProfileFromArkConfig,cn as createArkKernel,ra as createArkKernelFromConfig,Jn as createArkManifest,ai as createArkTestHarness,wn as createAuditTrail,xn as createDependencyGraph,Ii as createElevenLayerArkConfig,Qo as createEventBus,En as createEventContractRegistry,mn as createIntentRegistry,xo as createLenientArkKernel,ia as createLenientArkKernelFromConfig,Fn as createMetadataRegistry,vn as createObservabilityReporter,Xn as createProjectionRegistry,Gr as createResolvedCandidateFacts,Ts as createSaga,wo as createStrictArkKernel,oa as createStrictArkKernelFromConfig,Bt as createWorkflowEngine,Do as defaultIntentRegistry,An as defineArchitectureProfilePolicy,No as defineIntent,hn as defineLayerPolicy,ze as definePolicy,bi as definePort,Mo as definePublishPolicy,Zr as detectArchitectureCycles,W as deterministicHash,Os as diagnosticDocsFragment,Pc as diagnosticDocsPath,it as elevenLayerProfile,ft as evaluateArchitectureGraph,es as explainViolation,lt as extractSemanticDependencies,ho as formatArkRunGraphMermaid,an as formatArkRunInspectorSseEvent,qn as getDiagnosticCatalogEntry,At as isArkRunInspectorLoopbackHost,lr as isArkRunInspectorProductionEnv,Oc as isCataloguedOrArkRuleFamily,xc as isKnownDiagnosticCode,Rn as isLayerPolicy,Un as loadContract,Se as loadResolvedCandidateFacts,Xr as policyDeltaAcknowledgementMatches,Cs as preflightChange,xs as preflightResolvedChange,$s as replayInformationPackages,or as requestArkRunGraph,on as resolveArkRunInspectorBind,sr as resolveArkRunSendPlan,Ft as resolvedFactsEvidenceRequirementsHash,_c as serializeDiagnosticCatalog,Ms as shadowInformationPackage,$ as stableSerialize,ur as startArkRunInspector,On as syncRegistryToGraph,Rr as toAdapterDiagnostic,Ke as unavailableArkRunInspectorOutboxMonitor,He as unavailableArkRunInspectorWorkflowsMonitor,yn as validateIntentName,gr as version};
|