arkgate 4.8.6 → 4.8.7
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 +27 -4
- package/README.md +4 -3
- package/bin/ark-mcp-runtime.mjs +8 -2
- package/bin/lib/analysis-engine.mjs +5 -5
- package/bin/lib/doctor-human.mjs +9 -0
- package/bin/lib/doctor-plan.mjs +5 -1
- package/bin/lib/html-report.mjs +4 -2
- package/bin/lib/layer-description.mjs +27 -0
- package/bin/lib/prepare-write.mjs +7 -1
- package/dist/{configTypes-dy5PfTqS.d.ts → configTypes-0eHpocR3.d.ts} +4 -0
- package/dist/{diagnosticCatalog-D_DI7qrZ.d.ts → diagnosticCatalog-wDAH08gH.d.ts} +3 -3
- package/dist/eslint/index.d.ts +1 -1
- package/dist/index.cjs +19 -19
- package/dist/index.d.ts +5 -4
- package/dist/index.js +20 -20
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.d.ts +3 -3
- package/dist/nestjs/index.js +1 -1
- package/dist/runtime/index.cjs +10 -10
- package/dist/runtime/index.d.ts +6 -6
- package/dist/runtime/index.js +10 -10
- package/dist/{types-BuM8WNqe.d.ts → types-BK47clMl.d.ts} +1 -1
- package/dist/{types-DrqsOiTY.d.ts → types-CwZ_oz1N.d.ts} +1 -1
- package/docs/README.md +4 -4
- package/docs/configuration.md +23 -2
- package/docs/package-surface.md +6 -3
- package/package.json +1 -1
- package/server.json +2 -2
- package/templates/agent-skills/ark-adopt/SKILL.md +18 -1
- package/templates/agent-skills/ark-place/SKILL.md +17 -4
- package/templates/skills/ark-adopt.md +18 -1
- package/templates/skills/ark-place.md +17 -4
package/dist/runtime/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}function
|
|
1
|
+
var io=Object.defineProperty;var a=(e,t)=>io(e,"name",{value:t,configurable:!0});var it=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var _a=(e,t)=>{for(var n in t)io(e,n,{get:t[n],enumerable:!0})};function Mr(e,t){return e<t?-1:e>t?1:0}function sc(e){return[...new Set(e)].sort(Mr)}function _t(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)typeof n=="string"&&n.length>0&&t.push(n);return sc(t)}function ac(e){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e}function ic(e){return typeof e=="string"&&oc.has(e)?e:"singleton"}function aa(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of Object.keys(e).sort(Mr)){if(n.length===0)continue;let r=ac(e[n]);r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function lc(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=_t(t.tags);r.length>0&&(n.tags=r),typeof t.group=="string"&&t.group.length>0&&(n.group=t.group);let o=aa(t.metadata);return o&&(n.metadata=o),Object.keys(n).length>0?n:void 0}function Kr(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:ic(t.lifetime),uses:_t(t.uses),reactsTo:_t(t.reactsTo),raises:_t(t.raises),sends:_t(t.sends)},o=lc(t.extendedInfo);return o&&(r.extendedInfo=o),r}function dc(e){return aa(e)}function Hr(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,s=typeof o.kind=="string"?o.kind.trim():"";if(!s)return;let i=t.residual;if(i===null||typeof i!="object"||Array.isArray(i))return;let l=i,c=typeof l.kind=="string"&&cc.has(l.kind)?l.kind:void 0;if(!c)return;let g={kind:s},m=dc(o.payload);m&&(g.payload=m);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:g,residual:h}}function pc(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=Hr(n);r&&t.push(r)}return t}function Re(e){let t=typeof e.kernelInstanceId=="string"?e.kernelInstanceId:"",n=Array.isArray(e.components)?e.components:[],r=new Set,o=[];for(let i of n){let l=Kr(i);!l||r.has(l.id)||(r.add(l.id),o.push(l))}o.sort((i,l)=>Mr(i.id,l.id));let s=pc(e.decisionTape);return{schemaVersion:"1.0",kernelInstanceId:t,components:o,...s.length>0?{decisionTape:s}:{}}}function ia(e,t){let n=Hr(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 Dn,$r,sa,oc,cc,tt=it(()=>{"use strict";Dn="1.0",$r=["singleton","transient"],sa=["absorb","escalate_up","hold"],oc=new Set($r);a(Mr,"compare");a(sc,"uniqueSorted");a(_t,"nameList");a(ac,"jsonPrimitive");a(ic,"closedLifetime");a(aa,"sanitizeMetadata");a(lc,"sanitizeArkRunExtendedInfo");a(Kr,"sanitizeArkRunComponent");cc=new Set(sa);a(dc,"sanitizeTapePayload");a(Hr,"sanitizeDecisionTapeRecord");a(pc,"sanitizeDecisionTape");a(Re,"buildDependencyInformationPackage");a(ia,"appendDecisionTape")});function Dt(e,t){return e<t?-1:e>t?1:0}function Vr(e){return[...new Set(e)].sort(Dt)}function pa(){return{tokens:[],ids:[],labels:[],tags:[],groups:[],architectureKinds:[]}}function jr(e){return e.tokens.length+e.ids.length+e.labels.length+e.tags.length+e.groups.length+e.architectureKinds.length>0}function ce(e,t){if(e==null||e==="")return[];if(typeof e=="string")return Vr(e.split(",").map(r=>r.trim()).filter(r=>r.length>0));if(!Array.isArray(e))throw new J(t);let n=[];for(let r of e){if(typeof r!="string")throw new J(t);let o=r.trim();o.length>0&&n.push(o)}return Vr(n)}function Ra(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 Nt(e,t){return e?t.some(n=>Ra(e,n)):!1}function Aa(e){if(e==null||e==="")return Wr;if(typeof e=="string"&&uc.has(e))return e;throw new J("slice")}function ka(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 J("degreesOfSeparation")}function ua(e,t){if(e==null||e==="")return pa();if(typeof e=="string"||Array.isArray(e))return{...pa(),tokens:ce(e,t)};if(typeof e!="object")throw new J(t);let n=e;for(let r of Object.keys(n))if(!gc.has(r))throw new J(t);return{tokens:[],ids:ce(n.ids,t),labels:ce(n.labels,t),tags:ce(n.tags,t),groups:ce(n.groups,t),architectureKinds:ce(n.architectureKinds,t)}}function $n(e={}){if(e==null||e==="")return $n({});if(typeof e!="object"||Array.isArray(e))throw new J("slice","ArkRun graph query must be an object.");let t=e;for(let n of Object.keys(t))if(!fc.has(n))throw new J("slice",`ArkRun graph query key "${n}" is not closed.`);return{slice:Aa(t.slice),nodeIds:ce(t.nodeIds,"nodeIds"),degreesOfSeparation:ka(t.degreesOfSeparation),include:ua(t.include,"include"),exclude:ua(t.exclude,"exclude")}}function Mn(e){let t={};e.slice&&(t.slice=Aa(e.slice));let n=ce(e.nodeIds??void 0,"nodeIds");n.length>0&&(t.nodeIds=n);let r=ka(e.degreesOfSeparation??void 0);r!==null&&(t.degreesOfSeparation=r);let o=ce(e.include??void 0,"include");o.length>0&&(t.include=o);let s=ce(e.exclude??void 0,"exclude");return s.length>0&&(t.exclude=s),t}function mc(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 fa(e,t){if(!jr(t))return!0;let n=mc(e);return t.tokens.some(r=>n.some(o=>Ra(o,r)))||Nt(e.id,t.ids)||Nt(e.label,t.labels)||e.tags?.some(r=>Nt(r,t.tags))||Nt(e.group,t.groups)?!0:Nt(e.architectureKind,t.architectureKinds)}function yc(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;return Re({kernelInstanceId:t.kernelInstanceId,components:t.components})}return Re({})}function hc(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 Ln(e){return{id:e,kind:"interaction"}}function Tt(e,t){let n=e.get(t.id);(!n||n.kind==="interaction"&&t.kind==="component")&&e.set(t.id,t)}function Fn(e,t,n,r,o){let s=`${n}\0${o}\0${r}`;t.has(s)||(t.add(s),e.push({from:n,to:r,kind:o}))}function Rc(e,t){let n=new Map,r=[],o=new Set;for(let s of e){if(Tt(n,hc(s)),t==="technical"){for(let i of s.uses)Tt(n,n.get(i)??Ln(i)),Fn(r,o,s.id,i,"uses");continue}for(let i of s.raises)Tt(n,n.get(i)??Ln(i)),Fn(r,o,s.id,i,"raises");for(let i of s.reactsTo)Tt(n,n.get(i)??Ln(i)),Fn(r,o,i,s.id,"reactsTo");for(let i of s.sends)Tt(n,n.get(i)??Ln(i)),Fn(r,o,s.id,i,"sends")}return{nodes:n,edges:r}}function Ac(e){let t=new Map,n=a((r,o)=>{let s=t.get(r);s?s.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 kc(e,t,n,r){let o=t.filter(l=>e.has(l));if(o.length===0)return new Set;let s=new Set,i=o.map(l=>({id:l,depth:0}));for(;i.length>0;){let l=i.shift();if(!(!l||s.has(l.id))&&(s.add(l.id),!(n!==null&&l.depth>=n)))for(let c of r.get(l.id)??[])!s.has(c)&&e.has(c)&&i.push({id:c,depth:l.depth+1})}return s}function Lt(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return/^[A-Za-z_]/.test(t)?t:`n_${t}`}function ga(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"#quot;").replace(/]/g,"#93;")}function Ic(e){let t=new Set,n=new Map;for(let r of e){let o=Lt(r),s=o,i=2;for(;t.has(s);)s=`${o}_${i}`,i+=1;t.add(s),n.set(r,s)}return n}function zr(e){let t=e.slice==="technical"?"TD":"LR",n=e.nodes.map(l=>l.id),r=Ic(n),o=Vr(e.nodes.map(l=>l.group).filter(l=>!!l)),s=[`flowchart ${t}`],i=a((l,c)=>{let g=r.get(l.id)??Lt(l.id),m=ga(l.label??l.id);s.push(`${c}${g}["${m}"]`)},"emitNode");for(let l of o){let c=Lt(`group_${l}`);s.push(` subgraph ${c}["${ga(l)}"]`);for(let g of e.nodes)g.group===l&&i(g," ");s.push(" end")}for(let l of e.nodes)l.group||i(l," ");for(let l of e.edges){let c=r.get(l.from)??Lt(l.from),g=r.get(l.to)??Lt(l.to);s.push(` ${c} -->|${l.kind}| ${g}`)}return s.join(`
|
|
2
|
+
`)}function vc(e,t,n){let r=new Set(e.keys());if(jr(n.include)&&(r=new Set([...r].filter(l=>{let c=e.get(l);return c!==void 0&&fa(c,n.include)}))),jr(n.exclude))for(let l of[...r]){let c=e.get(l);c&&fa(c,n.exclude)&&r.delete(l)}let o=t.filter(l=>r.has(l.from)&&r.has(l.to));n.nodeIds.length>0&&(r=kc(r,n.nodeIds,n.degreesOfSeparation,Ac(o)));let s=[...r].sort(Dt).map(l=>e.get(l)).filter(l=>!!l),i=o.filter(l=>r.has(l.from)&&r.has(l.to)).sort((l,c)=>Dt(l.from,c.from)||Dt(l.kind,c.kind)||Dt(l.to,c.to));return{nodes:s,edges:i}}function Kn(e={},t={}){let n=yc(e),r=$n(t),o=Rc(n.components,r.slice),s=vc(o.nodes,o.edges,r),i={schemaVersion:Br,kernelInstanceId:n.kernelInstanceId,slice:r.slice,query:r,nodes:s.nodes,edges:s.edges,mermaid:""};return i.mermaid=zr(i),i}var Br,Wr,qr,ma,ya,ha,J,uc,fc,gc,Hn=it(()=>{"use strict";tt();Br="1.0",Wr="process",qr=["process","technical"],ma=["component","interaction"],ya=["raises","reactsTo","sends"],ha=["uses"],J=class extends Error{static{a(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}},uc=new Set(qr),fc=new Set(["slice","nodeIds","degreesOfSeparation","include","exclude"]),gc=new Set(["ids","labels","tags","groups","architectureKinds"]);a(Dt,"compare");a(Vr,"uniqueSorted");a(pa,"emptyMatch");a(jr,"matchHasCriteria");a(ce,"nameList");a(Ra,"globMatch");a(Nt,"anyGlob");a(Aa,"closedSlice");a(ka,"closedDegrees");a(ua,"closedMatch");a($n,"closeArkRunGraphQuery");a(Mn,"arkRunGraphQueryFromSearchParams");a(mc,"nodeFields");a(fa,"nodeMatches");a(yc,"asPackage");a(hc,"componentNode");a(Ln,"interactionNode");a(Tt,"addNode");a(Fn,"addEdge");a(Rc,"buildSlice");a(Ac,"adjacency");a(kc,"neighborhood");a(Lt,"mermaidSafeId");a(ga,"mermaidLabel");a(Ic,"uniqueMermaidIds");a(zr,"formatArkRunGraphMermaid");a(vc,"filterGraph");a(Kn,"requestArkRunGraph")});function Yr(e){if(e===void 0)return"local";if(typeof e=="string"&&Ec.has(e))return e;throw new nt("transport")}function Xr(e){if(e===void 0)return!0;if(e===!0||e===!1)return e;throw new nt("ephemeral")}function Gn(e){let t=Yr(e.transport),n=Xr(e.ephemeral),r=t==="broker"&&e.brokerBound!==!0,o=t==="broker"&&!r?"broker":"local",s=t==="localBlocking";return{transport:t,ephemeral:n,deliveredVia:o,fallbackToLocal:r,notifySubscribers:o==="local",awaitHandlers:s,awaitHandoff:n||s}}var Ft,rt,Ec,nt,$t=it(()=>{"use strict";Ft=["local","localBlocking","broker"],rt=!0,Ec=new Set(Ft),nt=class extends Error{static{a(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}};a(Yr,"closedArkRunTransportKind");a(Xr,"closedArkRunEphemeral");a(Gn,"resolveArkRunSendPlan")});function Vn(e){return e==="production"}function Sc(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 Ia(e){if(e.startsWith("[::ffff:")&&e.endsWith("]"))return e.slice(8,-1);if(e.startsWith("::ffff:"))return e.slice(7)}function st(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();if(t==="localhost"||t==="::1"||t==="[::1]")return!0;let n=Ia(t);if(n)return st(n);let r=Sc(t);return r!==void 0&&r[0]===127}function va(e){if(e===void 0)return Un;if(typeof e!="string")throw new se(String(e));let t=e.trim();if(bc.has(t.toLowerCase())||!st(t))throw new se(t);let n=t.toLowerCase();if(n==="localhost")return Un;if(n==="[::1]")return"::1";let r=Ia(n);return r?va(r):n}function Cc(e){if(e===void 0)return Jr;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>65535)throw new se(`port:${String(e)}`);return e}function Gt(e={}){if(Vn(e.nodeEnv)||Vn(e.processNodeEnv))throw new ot;return{host:va(e.host),port:Cc(e.port)}}function _e(e,t,n){return`http://${e.includes(":")?`[${e}]`:e}:${t}${n}`}function wc(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch{return}}function xc(e){return{kinds:[...Ft],ephemeralDefault:e.ephemeralDefault===!1?!1:!0,brokerBound:e.brokerBound===!0,cloudSdksShipped:!1,fallback:eo}}function jn(e={}){let t=Gt({host:e.host,port:e.port}),n=Re({kernelInstanceId:e.kernelInstanceId,components:e.package&&typeof e.package=="object"&&!Array.isArray(e.package)&&Array.isArray(e.package.components)?e.package.components:[]});return{schemaVersion:Zr,kernelInstanceId:typeof e.kernelInstanceId=="string"?e.kernelInstanceId:n.kernelInstanceId,bind:{host:t.host,port:t.port,loopback:!0},package:{...n,schemaVersion:"1.0"},transport:xc(e),observability:wc(e.observability)??{}}}function Ut(e){return`event: ${Qr}
|
|
3
3
|
data: ${JSON.stringify(e)}
|
|
4
4
|
|
|
5
|
-
`}var Xr,Un,Zr,Mt,Kt,Ht,Jr,Qr,ot,se,Ec,Vt=it(()=>{"use strict";tt();$t();Xr="1.0",Un="127.0.0.1",Zr=0,Mt="/snapshot",Kt="/events",Ht="/graph",Jr="snapshot",Qr="in-process-local",ot=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},se=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},Ec=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(Vn,"isArkRunInspectorProductionEnv");a(bc,"ipv4Octets");a(ka,"unwrapIpv4Mapped");a(st,"isArkRunInspectorLoopbackHost");a(Ia,"closedHost");a(Sc,"closedPort");a(Gt,"resolveArkRunInspectorBind");a(_e,"arkRunInspectorUrl");a(Cc,"jsonClone");a(wc,"closedTransportFacts");a(jn,"buildArkRunInspectorSnapshot");a(Ut,"formatArkRunInspectorSseEvent")});var va={};Pa(va,{listenArkRunInspector:()=>Nc});function xc(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Oc(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function Pc(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,xc()),e.end(JSON.stringify(n))}function _c(e,t){let n=e.address();if(n===null||typeof n=="string")throw new se(t.host);if(!st(n.address))throw new se(n.address);return{host:t.host,port:n.port}}async function Nc(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,i=t.bind,l=a(()=>e.getInspectorSnapshot(i),"snapshot"),c=n.createServer((g,m)=>{let h=Pc(g.url),p=h.pathname;if(g.method==="GET"&&(p==="/"||p===Mt)){Bn(m,200,l());return}if(g.method==="GET"&&p===Ht){try{Bn(m,200,e.requestGraph(Mn({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 J){Bn(m,400,{error:f.message,option:f.option});return}throw f}return}if(g.method==="GET"&&p===Kt){m.writeHead(200,Oc()),m.flushHeaders(),m.write(Ut(l())),r.add(m);let f=s>0?setInterval(()=>{m.write(Ut(l()))},s):void 0;f&&o.add(f);let u=a(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");g.on("close",u),m.on("close",u);return}Bn(m,404,{error:"not found"})});try{await new Promise((g,m)=>{let h=a(p=>m(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{i=_c(c,t.bind),g()}catch(p){m(p instanceof Error?p:new se(t.bind.host))}})})}catch(g){throw await new Promise(m=>{c.close(()=>m())}),g}return{host:i.host,port:i.port,url:_e(i.host,i.port,"/"),snapshotUrl:_e(i.host,i.port,Mt),eventsUrl:_e(i.host,i.port,Kt),graphUrl:_e(i.host,i.port,Ht),close(){for(let g of o)clearInterval(g);o.clear();for(let g of r)g.end();return r.clear(),new Promise((g,m)=>{c.close(h=>{h?m(h):g()})})}}}var Ea=it(()=>{"use strict";Hn();Vt();a(xc,"jsonHeaders");a(Oc,"sseHeaders");a(Pc,"requestUrl");a(Bn,"writeJson");a(_c,"boundAddress");a(Nc,"listenArkRunInspector")});var Zn="4.8.6";var _a=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Na=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Ta=/(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 _a.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Na.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Ta.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(Da,"classifyLayerImportKind");function La(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."}a(La,"layerImportNextAction");function Fa(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a(Fa,"arkRunCallSiteName");function $a(e){let t=Fa(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.`}}a($a,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return La(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 $a(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.`}}a(le,"deterministicNextAction");var Qn="1.5",Ma="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}a(w,"text");function io(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(io,"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("|")}a(co,"adapterFindingTargetKey");function lo(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}`})}a(lo,"adapterFindingOccurrenceTargetKeys");function Ka(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")}`}a(Ka,"adapterFindingRefFromTargetKey");function Ha(e){return`${Ma}#${e}`}a(Ha,"adapterDocsCodePath");function Ga(e,t,n){return le({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}a(Ga,"nextActionForDiagnostic");function Jn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},i=n??co(e),l=Ka(i);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:io(e.line,1),column:io(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ga(r,s,e),findingRef:l,targetKey:i,docsCodePath:Ha(r)}}a(Jn,"toAdapterDiagnostic");function Ua(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:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(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??[],i=e.warnings??[],l=lo(s),c=lo(i),g=[...s.map((h,p)=>Jn(h,"error",l[p])),...i.map((h,p)=>Jn(h,"warning",c[p]))],m={schemaVersion:Qn,completenessReasons:r,diagnostics:g};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}}a(Ua,"createAdapterResult");var Va={$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:Qn},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 Te=class{static{a(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=a(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 po=new Te;function uo(e,t){return po.define(e,t)}a(uo,"defineIntent");function Yt(){return new Te}a(Yt,"createIntentRegistry");var fo=po;var go=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Xt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!go.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${go.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}}a(Xt,"validateIntentName");var Ae=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(t){let n=t.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
5
|
+
`}var Zr,Un,Jr,Mt,Kt,Ht,Qr,eo,ot,se,bc,Vt=it(()=>{"use strict";tt();$t();Zr="1.0",Un="127.0.0.1",Jr=0,Mt="/snapshot",Kt="/events",Ht="/graph",Qr="snapshot",eo="in-process-local",ot=class extends Error{static{a(this,"ArkRunInspectorProductionError")}constructor(){super("ArkRun inspector refuses to start when NODE_ENV=production."),this.name="ArkRunInspectorProductionError"}},se=class extends Error{static{a(this,"ArkRunInspectorBindError")}constructor(t){super(`ArkRun inspector binds loopback only (default 127.0.0.1). Public host "${t}" is rejected.`),this.name="ArkRunInspectorBindError"}},bc=new Set(["","*","0","0.0.0.0","::","::0","[::]","[::0]","::ffff:0.0.0.0","[::ffff:0.0.0.0]"]);a(Vn,"isArkRunInspectorProductionEnv");a(Sc,"ipv4Octets");a(Ia,"unwrapIpv4Mapped");a(st,"isArkRunInspectorLoopbackHost");a(va,"closedHost");a(Cc,"closedPort");a(Gt,"resolveArkRunInspectorBind");a(_e,"arkRunInspectorUrl");a(wc,"jsonClone");a(xc,"closedTransportFacts");a(jn,"buildArkRunInspectorSnapshot");a(Ut,"formatArkRunInspectorSseEvent")});var Ea={};_a(Ea,{listenArkRunInspector:()=>Tc});function Oc(){return{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}}function Pc(){return{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive","x-accel-buffering":"no"}}function _c(e){let t=e&&e.length>0?e:"/";return new URL(t,"http://127.0.0.1")}function Bn(e,t,n){e.writeHead(t,Oc()),e.end(JSON.stringify(n))}function Nc(e,t){let n=e.address();if(n===null||typeof n=="string")throw new se(t.host);if(!st(n.address))throw new se(n.address);return{host:t.host,port:n.port}}async function Tc(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,i=t.bind,l=a(()=>e.getInspectorSnapshot(i),"snapshot"),c=n.createServer((g,m)=>{let h=_c(g.url),p=h.pathname;if(g.method==="GET"&&(p==="/"||p===Mt)){Bn(m,200,l());return}if(g.method==="GET"&&p===Ht){try{Bn(m,200,e.requestGraph(Mn({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 J){Bn(m,400,{error:f.message,option:f.option});return}throw f}return}if(g.method==="GET"&&p===Kt){m.writeHead(200,Pc()),m.flushHeaders(),m.write(Ut(l())),r.add(m);let f=s>0?setInterval(()=>{m.write(Ut(l()))},s):void 0;f&&o.add(f);let u=a(()=>{r.delete(m),f&&(clearInterval(f),o.delete(f))},"drop");g.on("close",u),m.on("close",u);return}Bn(m,404,{error:"not found"})});try{await new Promise((g,m)=>{let h=a(p=>m(p),"onError");c.once("error",h),c.listen({host:t.bind.host,port:t.bind.port},()=>{c.off("error",h);try{i=Nc(c,t.bind),g()}catch(p){m(p instanceof Error?p:new se(t.bind.host))}})})}catch(g){throw await new Promise(m=>{c.close(()=>m())}),g}return{host:i.host,port:i.port,url:_e(i.host,i.port,"/"),snapshotUrl:_e(i.host,i.port,Mt),eventsUrl:_e(i.host,i.port,Kt),graphUrl:_e(i.host,i.port,Ht),close(){for(let g of o)clearInterval(g);o.clear();for(let g of r)g.end();return r.clear(),new Promise((g,m)=>{c.close(h=>{h?m(h):g()})})}}}var ba=it(()=>{"use strict";Hn();Vt();a(Oc,"jsonHeaders");a(Pc,"sseHeaders");a(_c,"requestUrl");a(Bn,"writeJson");a(Nc,"boundAddress");a(Tc,"listenArkRunInspector")});var Zn="4.8.7";var Na=/(^|\/)(constants|types|enums|shared-types|shared\/(?:types|constants)|test-projects)(\/|\.|$)|(?:^|\/)[^/]*(?:constants|types)(?:\.[cm]?[jt]sx?)?$/i,Ta=/(^|\/)(?:kernel(?:\/|$)|events?(?:\/|\.|$)|bootstrap(?:\.[cm]?[jt]sx?)?$|emitter(?:\.[cm]?[jt]sx?)?$)|(?:^|\/)(?:intents?|publish)(?:\/|\.|$)/i,Da=/(use-?cases?|usecases?|application|orchestrat|services?|handlers?)(\/|\.|$)/i;function La(e,t){let n=String(e??"").replace(/\\/g,"/").trim(),r=String(t?.fromLayer??""),o=String(t?.toLayer??"");return Na.test(n)?"pure-shared":r==="PersistenceAdapters"&&(Ta.test(n)||/events?|intents?|kernel|bootstrap/i.test(`${o} ${n}`))?"kernel-emit":Da.test(n)||(r==="DomainModel"||r==="ApplicationOrchestration")&&o==="PersistenceAdapters"?"use-case":"unknown"}a(La,"classifyLayerImportKind");function Fa(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=La(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."}a(Fa,"layerImportNextAction");function $a(e){return typeof e.target=="string"&&e.target.trim().length>0?e.target.trim():void 0}a($a,"arkRunCallSiteName");function Ma(e){let t=$a(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.`}}a(Ma,"arkRunNextAction");function le(e){switch(e.ruleId){case"LAYER_IMPORT_VIOLATION":return Fa(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 Ma(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.`}}a(le,"deterministicNextAction");var Qn="1.5",Ka="docs/diagnostics.md";function w(e){return typeof e=="string"&&e.length>0?e:void 0}a(w,"text");function lo(e,t){return Number.isInteger(e)&&Number(e)>0?Number(e):t}a(lo,"positiveInteger");function po(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("|")}a(po,"adapterFindingTargetKey");function co(e){let t=new Map;return e.map(n=>{let r=po(n),o=(t.get(r)??0)+1;return t.set(r,o),o===1?r:`${r}#${o}`})}a(co,"adapterFindingOccurrenceTargetKeys");function Ha(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")}`}a(Ha,"adapterFindingRefFromTargetKey");function Ga(e){return`${Ka}#${e}`}a(Ga,"adapterDocsCodePath");function Ua(e,t,n){return le({ruleId:e,target:w(t.target)??w(n.target)??void 0,fromLayer:w(t.fromLayer)??void 0,toLayer:w(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:w(t.edgeKind)??void 0,capability:w(t.capability)??w(n.capability)??void 0,arkruleId:w(t.arkruleId)??void 0,arkruleSource:w(t.arkruleSource)??void 0})}a(Ua,"nextActionForDiagnostic");function Jn(e,t="error",n){let r=w(e.ruleId)??w(e.code)??"ARK_UNKNOWN",o=e.severity==="warning"||e.failsStrict===!1||e.typeOnly===!0&&e.peerIsolation!==!0?"warning":t,s={...w(e.target)?{target:w(e.target)}:{},...w(e.fromLayer)?{fromLayer:w(e.fromLayer)}:{},...w(e.toLayer)?{toLayer:w(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}:{},...w(e.capability)?{capability:w(e.capability)}:{},...w(e.edgeKind)?{edgeKind:w(e.edgeKind)}:{},...w(e.arkruleId)?{arkruleId:w(e.arkruleId)}:{},...w(e.arkruleSource)?{arkruleSource:w(e.arkruleSource)}:{}},i=n??po(e),l=Ha(i);return{ruleId:r,severity:o,message:w(e.message)??r,location:{file:w(e.file)??"<unknown>",line:lo(e.line,1),column:lo(e.column,1)},evidence:s,nextAction:w(e.nextAction)??Ua(r,s,e),findingRef:l,targetKey:i,docsCodePath:Ga(r)}}a(Jn,"toAdapterDiagnostic");function Va(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:w(h.code)??"ANALYSIS_EVIDENCE_INCOMPLETE",message:w(h.message)??`Analysis ${t}: required evidence is incomplete.`,...w(h.file)?{file:w(h.file)}:{}})):[{code:t==="unavailable"?"ANALYSIS_UNAVAILABLE":"ANALYSIS_EVIDENCE_INCOMPLETE",message:`Analysis ${t}: required evidence is incomplete.`}],o={...w(e.policyHash)?{policyHash:w(e.policyHash)}:{},...w(e.resolverIdentity)?{resolverIdentity:w(e.resolverIdentity)}:{},...w(e.factsHash)?{factsHash:w(e.factsHash)}:{},...w(e.candidateTreeHash)?{candidateTreeHash:w(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??[],i=e.warnings??[],l=co(s),c=co(i),g=[...s.map((h,p)=>Jn(h,"error",l[p])),...i.map((h,p)=>Jn(h,"warning",c[p]))],m={schemaVersion:Qn,completenessReasons:r,diagnostics:g};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}}a(Va,"createAdapterResult");var ja={$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:Qn},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 Te=class{static{a(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=a(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 uo=new Te;function fo(e,t){return uo.define(e,t)}a(fo,"defineIntent");function Yt(){return new Te}a(Yt,"createIntentRegistry");var go=uo;var mo=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Xt(e){if(!e||typeof e!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!mo.some(n=>e.startsWith(n)))return{valid:!1,reason:`Intent "${e}" must start with one of: ${mo.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}}a(Xt,"validateIntentName");var Ae=class extends Error{static{a(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 be=class{static{a(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 i=s.check(t);if(i!==!0){if(i===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(i))for(let l of i)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:i.message,details:i.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 Ae(n.hardViolations);return n}clear(){this.policies.length=0}};function De(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}}a(De,"definePolicy");function ja(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(ja,"defaultLayerOf");function mo(e,t){return t.resolveLayer?.(e)??ja(e)}a(mo,"resolveLayer");function Ba(e,t,n){return e===n.from&&t===n.to}a(Ba,"matchesRule");function Zt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return De({name:t,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(i=>i.kind==="declared"||i.kind==="produces").map(i=>({from:i.from,to:i.to})),...(r.relationships??[]).filter(i=>i.kind==="dependsOn").map(i=>({from:i.from,to:i.to}))],s=[];for(let i of o){let l=mo(i.from,e),c=mo(i.to,e);for(let g of e.rules)!g.allowed&&Ba(l,c,g)&&s.push({policyName:t,severity:n,message:g.message??`Layer violation: ${i.from} (${l}) must not relate to ${i.to} (${c})`})}return s.length>0?s:!0},"check")})}a(Zt,"defineLayerPolicy");function Jt(e){return e.tags?.includes("layer")??!1}a(Jt,"isLayerPolicy");var er={layerIsolation(){return er.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Zt({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 Qt(e,t={}){return Zt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}a(Qt,"defineArchitectureProfilePolicy");function en(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(en,"buildPublishPolicyContext");function yo(e){return De(e)}a(yo,"definePublishPolicy");var Le=class extends Error{static{a(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}},Fe=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},$e=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Me=class extends Error{static{a(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}},Se=class extends Error{static{a(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}},ke=class extends Error{static{a(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}},Ke=class extends Error{static{a(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 lt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Xt(e);if(!n.valid)throw new Fe(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Le(e)}}a(lt,"assertIntentAllowed");function ho(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Se(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Se(e.intent,e.metadata.source)}}a(ho,"assertSourceAllowed");function ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Me(e.intent,n.issues)}a(ct,"assertContractAllowed");function He(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(He,"isPlainRecord");function Ge(e){return Array.isArray(e)?e.map(Ge):He(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ge(n)])):e}a(Ge,"clonePatchValue");function tr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let i=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=Ge(s);continue}if(He(r[o])&&He(s)){r[o]=tr(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=nr(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(tr,"mergeRecordPatch");function nr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let i=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=Ge(o);return}if(He(r[s])&&He(o)){r[s]=tr(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=nr(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a(nr,"mergeArrayPatch");function Ro(e,t){if(Array.isArray(t)){if(e===void 0)return Ge(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return nr(e,t)}if(e===void 0)return Ge(t);if(!He(e))throw new Error("Object interceptor patch requires an object payload.");return tr(e,t)}a(Ro,"applyPayloadPatch");async function Ao(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:a(c=>{s.push(c)},"intercept")})),s.length===0)continue;let i=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:i}]}};for(let c of s)l={...l,payload:Ro(l.payload,c),metadata:{...l.metadata}};ct(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=i,t.appendTrace({type:"event.intercepted",timestamp:i,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(i){await Wa(o,r,i,t)}}return r}a(Ao,"applyInterceptors");async function Wa(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})}a(Wa,"recordInterceptorError");var ko=new Map;function Io(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Io,"escapeLiteral");function tn(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}a(tn,"normalizeGlobSeparators");function qa(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}a(qa,"bracesBalanced");function pe(e){let t=ko.get(e);if(t)return t;let n=tn(e),r=qa(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=Io(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+=Io(c)}let i=new RegExp(`^${o}$`);return ko.set(e,i),i}a(pe,"globToRegExp");function za(e){return tn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(za,"concreteGlobSegments");function rr(e,t){let n=tn(String(e)),r=za(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let g of r){let m=-1;for(let h=l;h<i.length;h+=1)if(i[h]===g){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}a(rr,"patternSpecificity");function ae(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>pe(i).test(n))){for(let i of s.patterns??[])if(pe(i).test(n)){let l=rr(i,n);l>o&&(o=l,r=s.name)}}return r}a(ae,"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()}`}a(vo,"sliceIdForPath");function Ya(e){let t=new Set;for(let n of e??[]){let o=tn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Ya,"inferSliceFoldersFromPatterns");function Xa(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 Ya(r?.patterns)}a(Xa,"resolveSliceFolders");function Eo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(Eo,"normalizeSegments");function Co(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(Co,"trimTrailingSlashes");var Za=["src","app"];function Ja(e){let t=Co(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Ja,"isBlanketRoot");function bo(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=Eo(n);for(let s of t){if(typeof s!="string"||s.length===0||Ja(s))continue;if(s.includes("*")){let c=Co(s.toLowerCase());if(pe(c).test(r)||pe(`${c}/**`).test(r))return!0;continue}let i=Eo(s);if(i.length===0)continue;let l=Za.includes(o[0])&&i[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+i.length>o.length)continue;let g=!0;for(let m=0;m<i.length;m+=1)if(o[c+m]!==i[m]){g=!1;break}if(g)return!0}}return!1}a(bo,"pathUnderSharedRoot");function So(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}`)}a(So,"sliceMatchesDeclaration");function Qa(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&So(r.from,t)&&So(r.to,n))}a(Qa,"crossSliceEdgeAllowed");function ei(e){if(!e.fromPath||!e.toPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0,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"}}a(ei,"peerIsolationDecision");function wo(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."}}a(wo,"peerIsolationDenyExplanation");function ue(e,t,n,r){return or(e,t,n,r)?.rule}a(ue,"findDeniedEdgeRule");function or(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,i=r?.toPath,l=Xa(o,t,r?.layers),c=s&&i?vo(s,l):void 0,g=s&&i?vo(i,l):void 0,m=ei({fromPath:s,toPath:i,folderCount:l.length,fromSlice:c,toSlice:g,fromShared:!c&&bo(s,o.sharedRoots),toShared:!g&&bo(i,o.sharedRoots),crossSliceAllowed:Qa(o.allowedCrossSlice,c,g)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:g};continue}if(t!==n)return{rule:o}}}a(or,"findDeniedEdgeDecision");async function xo(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 i=ue(r.rules,o,s);if(!i)return;let l=t.mode,c=i.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,g={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:i};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:g}),await t.recordAudit("layer.observedViolation",e,g),l==="hard")throw new Ke(n,e.intent,o,s,c)}a(xo,"assertObservedLayerFlowAllowed");async function Oo(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Ae&&(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))}a(Oo,"enforcePublishPolicy");function ti(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}a(ti,"appendHistory");function dt(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{}}a(dt,"appendTrace");async function nn(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){dt(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)}})}}a(nn,"recordAudit");async function Po(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."};dt(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 nn(e,"event.rawPublish",t,n)}a(Po,"recordRawPublishDiagnostic");async function _o(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return ti(e,o),await e.eventBuffer?.enqueue(t,r),dt(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 nn(e,"event.published",t,{subscribersNotified:n}),o}a(_o,"recordSuccessfulPublish");function sr(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}}a(sr,"enrichMetadata");var No=0;function ni(){return No+=1,`interceptor-${Date.now()}-${No}`}a(ni,"nextInterceptorRegistrationId");var Ue=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(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 be(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Jt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new $e;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=en({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,i=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,g=typeof t!="function";if(g){let p=t,f=r??n??{};c={...p,metadata:sr(p.metadata,f,this.recording.instanceId)}}else{let p=t,f=n,u=r??{},y=p(f);c={...y,metadata:sr(y.metadata,u,this.recording.instanceId)}}g&&this.strictRegistry&&await Po(this.recording,c),lt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),ho(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await Ao(c,{interceptorsForIntent:a(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await xo(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let m=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Oo(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((p,f,u)=>this.safeHook(p,f,u),"safeHook")}),await _o(this.recording,c,s?m.length:0,o.tx);let h=(async()=>{s&&await Promise.all(m.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return i?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return lt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,s={},i)=>{if(s.source&&s.source!==n)throw new ke(n,s.source);await this.publish(r,o,{...s,source:n},i)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;lt(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 i=this.subscriptions.indexOf(o);i>=0&&this.subscriptions.splice(i,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;lt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:ni(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let i=this.interceptorsByIntent.get(o)??[];return i.push(s),this.interceptorsByIntent.set(o,i),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){dt(this.recording,t)}async recordAudit(t,n,r){await nn(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 To(e){return new Ue(e)}a(To,"createEventBus");function ri(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}a(ri,"formatStandardSchemaPath");function oi(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"}a(oi,"actualType");function si(e,t){return e?`${e}.${t}`:t}a(si,"formatPath");function Do(e,t,n,r,o){let s=oi(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(i=>Object.is(i,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}Lo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{Do(i,t.items,`${n}[${l}]`,r,o)})}a(Do,"validateSchemaField");function Lo(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=si(o,s),c=e[s];if(c===void 0){i.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Do(c,i,l,n,r)}}a(Lo,"validateObjectSchema");var pt=class{static{a(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(Lo(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let i of Object.keys(s))r.schema[i]||o.push({intent:t.intent,version:r.version,field:i,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let i=r.standardSchema["~standard"].validate(t.payload);if(i instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(i.issues)for(let l of i.issues)o.push({intent:t.intent,version:r.version,field:ri(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 rn(){return new pt}a(rn,"createEventContractRegistry");var Fo=0;function ai(){return Fo+=1,`outbox-${Date.now()}-${Fo}`}a(ai,"nextOutboxId");function $o(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a($o,"cloneRecord");var Ce=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ai(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),$o(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($o)}async clear(){this.records.clear()}},Mo=Ce;function ar(e){return`${e.from}->${e.to}`}a(ar,"flowKey");function Ko(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}a(Ko,"uniqueFlows");function Ho(e,t){let n=new Set(t.map(ar));return e.filter(r=>!n.has(ar(r)))}a(Ho,"difference");function on(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})),i=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=i.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=Ko([...o,...s]),g=Ko([...i,...l]),m=g.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(g.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],p=t?Array.from(new Set(g.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(g.flatMap(y=>[y.from,y.to])),u=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:g,declaredButUnobserved:Ho(c,g),observedButUndeclared:Ho(g.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:u}}}}a(on,"createObservabilityReporter");function Go(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()}}}a(Go,"createArkTestHarness");var Uo=0;function ii(){return Uo+=1,`audit-${Date.now()}-${Uo}`}a(ii,"createAuditId");function li(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)}a(li,"matchesQuery");var ut=class{constructor(t){this.maxRecords=t}maxRecords;static{a(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=>li(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{a(this,"AuditTrailImpl")}async record(t){let n={id:ii(),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 an(e={}){return new sn(e.store??new ut(e.maxRecords))}a(an,"createAuditTrail");var ln=class{static{a(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 be=class{static{a(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 i=s.check(t);if(i!==!0){if(i===!1){n.push({policyName:s.name,severity:s.severity,message:`Policy "${s.name}" was violated.`});continue}if(Array.isArray(i))for(let l of i)n.push({policyName:s.name,severity:s.severity,message:l.message,details:l.details});else n.push({policyName:s.name,severity:s.severity,message:i.message,details:i.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 Ae(n.hardViolations);return n}clear(){this.policies.length=0}};function De(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}}a(De,"definePolicy");function Ba(e){let t=e.indexOf(".");return t>=0?e.slice(0,t):e}a(Ba,"defaultLayerOf");function yo(e,t){return t.resolveLayer?.(e)??Ba(e)}a(yo,"resolveLayer");function Wa(e,t,n){return e===n.from&&t===n.to}a(Wa,"matchesRule");function Zt(e){let t=e.name??"Layer isolation",n=e.severity??"hard";return De({name:t,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(i=>i.kind==="declared"||i.kind==="produces").map(i=>({from:i.from,to:i.to})),...(r.relationships??[]).filter(i=>i.kind==="dependsOn").map(i=>({from:i.from,to:i.to}))],s=[];for(let i of o){let l=yo(i.from,e),c=yo(i.to,e);for(let g of e.rules)!g.allowed&&Wa(l,c,g)&&s.push({policyName:t,severity:n,message:g.message??`Layer violation: ${i.from} (${l}) must not relate to ${i.to} (${c})`})}return s.length>0?s:!0},"check")})}a(Zt,"defineLayerPolicy");function Jt(e){return e.tags?.includes("layer")??!1}a(Jt,"isLayerPolicy");var er={layerIsolation(){return er.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return Zt({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 Qt(e,t={}){return Zt({name:t.name??`${e.name} layer policy`,severity:t.severity??"hard",rules:e.rules,resolveLayer:e.resolveLayer})}a(Qt,"defineArchitectureProfilePolicy");function en(e){return t=>({event:t,relationships:e.intentRegistry?.getAllRelationships(),edges:e.dependencyGraph?.getEdges()})}a(en,"buildPublishPolicyContext");function ho(e){return De(e)}a(ho,"definePublishPolicy");var Le=class extends Error{static{a(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}},Fe=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(t,n){super(`Invalid intent name "${t}": ${n}`),this.name="InvalidIntentNameError",this.intentName=t,this.reason=n}},$e=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},Me=class extends Error{static{a(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}},Se=class extends Error{static{a(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}},ke=class extends Error{static{a(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}},Ke=class extends Error{static{a(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 lt(e,t){if(!(!t.strictRegistry&&!t.validateIntentNaming)){if(t.validateIntentNaming){let n=Xt(e);if(!n.valid)throw new Fe(e,n.reason)}if(t.strictRegistry&&t.intentRegistry&&!t.intentRegistry.has(e))throw new Le(e)}}a(lt,"assertIntentAllowed");function Ro(e,t){if(t.requireKnownSource){if(!e.metadata.source||e.metadata.source==="unknown")throw new Se(e.intent);if(t.intentRegistry&&!t.intentRegistry.has(e.metadata.source))throw new Se(e.intent,e.metadata.source)}}a(Ro,"assertSourceAllowed");function ct(e,t){if(!t.eventContracts)return;let n=t.eventContracts.validate(e);if(!n.ok&&(t.strictEventContracts||n.contract))throw new Me(e.intent,n.issues)}a(ct,"assertContractAllowed");function He(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(He,"isPlainRecord");function Ge(e){return Array.isArray(e)?e.map(Ge):He(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ge(n)])):e}a(Ge,"clonePatchValue");function tr(e,t,n="payload"){let r={...e};for(let[o,s]of Object.entries(t)){let i=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=Ge(s);continue}if(He(r[o])&&He(s)){r[o]=tr(r[o],s,i);continue}if(Array.isArray(r[o])&&Array.isArray(s)){r[o]=nr(r[o],s,i);continue}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}return r}a(tr,"mergeRecordPatch");function nr(e,t,n="payload"){let r=[...e];return t.forEach((o,s)=>{let i=`${n}[${s}]`;if(s>=r.length||r[s]===void 0){r[s]=Ge(o);return}if(He(r[s])&&He(o)){r[s]=tr(r[s],o,i);return}if(Array.isArray(r[s])&&Array.isArray(o)){r[s]=nr(r[s],o,i);return}throw new Error(`Interceptor patch cannot overwrite existing ${i}.`)}),r}a(nr,"mergeArrayPatch");function Ao(e,t){if(Array.isArray(t)){if(e===void 0)return Ge(t);if(!Array.isArray(e))throw new Error("Array interceptor patch requires an array payload.");return nr(e,t)}if(e===void 0)return Ge(t);if(!He(e))throw new Error("Object interceptor patch requires an object payload.");return tr(e,t)}a(Ao,"applyPayloadPatch");async function ko(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:a(c=>{s.push(c)},"intercept")})),s.length===0)continue;let i=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:i}]}};for(let c of s)l={...l,payload:Ao(l.payload,c),metadata:{...l.metadata}};ct(l,{eventContracts:t.eventContracts,strictEventContracts:t.strictEventContracts}),r=l,o.lastInterceptedAt=i,t.appendTrace({type:"event.intercepted",timestamp:i,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(i){await qa(o,r,i,t)}}return r}a(ko,"applyInterceptors");async function qa(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})}a(qa,"recordInterceptorError");var Io=new Map;function vo(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(vo,"escapeLiteral");function tn(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}a(tn,"normalizeGlobSeparators");function za(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}a(za,"bracesBalanced");function pe(e){let t=Io.get(e);if(t)return t;let n=tn(e),r=za(n),o="",s=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=vo(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+=vo(c)}let i=new RegExp(`^${o}$`);return Io.set(e,i),i}a(pe,"globToRegExp");function Ya(e){return tn(String(e)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(Ya,"concreteGlobSegments");function rr(e,t){let n=tn(String(e)),r=Ya(n),o=n.replace(/\*/g,"").length,s=r.length*1e4+o;if(t==null||t==="")return s;let i=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let g of r){let m=-1;for(let h=l;h<i.length;h+=1)if(i[h]===g){m=h;break}if(m<0)return s;c=m,l=m+1}return(c+1)*1e6+r.length*1e4+o}a(rr,"patternSpecificity");function ae(e,t){let n=String(e).split(/[/\\]/).join("/"),r,o=-1;for(let s of t??[])if(!(s.exclude??[]).some(i=>pe(i).test(n))){for(let i of s.patterns??[])if(pe(i).test(n)){let l=rr(i,n);l>o&&(o=l,r=s.name)}}return r}a(ae,"layerForRelativePath");function Eo(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()}`}a(Eo,"sliceIdForPath");function Xa(e){let t=new Set;for(let n of e??[]){let o=tn(String(n)).split("/").filter(Boolean);for(let s=0;s<o.length;s+=1){let i=o[s];if((i==="**"||i==="*")&&s>0){let l=o[s-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&t.add(l)}}}return[...t]}a(Xa,"inferSliceFoldersFromPatterns");function Za(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 Xa(r?.patterns)}a(Za,"resolveSliceFolders");function bo(e){return String(e).split(/[/\\]/).filter(t=>!!t&&t!==".").map(t=>t.toLowerCase())}a(bo,"normalizeSegments");function wo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}a(wo,"trimTrailingSlashes");var Ja=["src","app"];function Qa(e){let t=wo(e.replace(/^[./]+/,""));return t==="*"||t==="**"}a(Qa,"isBlanketRoot");function So(e,t){if(!e||!t?.length)return!1;let n=String(e).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=bo(n);for(let s of t){if(typeof s!="string"||s.length===0||Qa(s))continue;if(s.includes("*")){let c=wo(s.toLowerCase());if(pe(c).test(r)||pe(`${c}/**`).test(r))return!0;continue}let i=bo(s);if(i.length===0)continue;let l=Ja.includes(o[0])&&i[0]!==o[0]?[0,1]:[0];for(let c of l){if(c+i.length>o.length)continue;let g=!0;for(let m=0;m<i.length;m+=1)if(o[c+m]!==i[m]){g=!1;break}if(g)return!0}}return!1}a(So,"pathUnderSharedRoot");function Co(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}`)}a(Co,"sliceMatchesDeclaration");function ei(e,t,n){return!e?.length||!t||!n?!1:e.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&Co(r.from,t)&&Co(r.to,n))}a(ei,"crossSliceEdgeAllowed");function ti(e){if(!e.fromPath||!e.toPath)return{denied:!0,reason:"missing-path"};if(e.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let t=!!e.fromSlice||e.fromShared===!0,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"}}a(ti,"peerIsolationDecision");function xo(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."}}a(xo,"peerIsolationDenyExplanation");function ue(e,t,n,r){return or(e,t,n,r)?.rule}a(ue,"findDeniedEdgeRule");function or(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,i=r?.toPath,l=Za(o,t,r?.layers),c=s&&i?Eo(s,l):void 0,g=s&&i?Eo(i,l):void 0,m=ti({fromPath:s,toPath:i,folderCount:l.length,fromSlice:c,toSlice:g,fromShared:!c&&So(s,o.sharedRoots),toShared:!g&&So(i,o.sharedRoots),crossSliceAllowed:ei(o.allowedCrossSlice,c,g)});if(m.denied)return{rule:o,peerIsolationReason:m.reason,fromSlice:c,toSlice:g};continue}if(t!==n)return{rule:o}}}a(or,"findDeniedEdgeDecision");async function Oo(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 i=ue(r.rules,o,s);if(!i)return;let l=t.mode,c=i.message??`Observed layer violation: "${n}" (${o}) must not produce "${e.intent}" (${s}).`,g={source:n,intent:e.intent,fromLayer:o,toLayer:s,severity:l,message:c,rule:i};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:g}),await t.recordAudit("layer.observedViolation",e,g),l==="hard")throw new Ke(n,e.intent,o,s,c)}a(Oo,"assertObservedLayerFlowAllowed");async function Po(e,t){let n=t.getPolicyContext(e),r;try{r=t.policyEngine.enforce(n)}catch(o){throw o instanceof Ae&&(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))}a(Po,"enforcePublishPolicy");function ni(e,t){e.history.push(t),e.maxHistorySize!==void 0&&e.history.length>e.maxHistorySize&&e.history.splice(0,e.history.length-e.maxHistorySize)}a(ni,"appendHistory");function dt(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{}}a(dt,"appendTrace");async function nn(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){dt(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)}})}}a(nn,"recordAudit");async function _o(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."};dt(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 nn(e,"event.rawPublish",t,n)}a(_o,"recordRawPublishDiagnostic");async function No(e,t,n,r){let o={event:t,publishedAt:new Date().toISOString(),subscribersNotified:n};return ni(e,o),await e.eventBuffer?.enqueue(t,r),dt(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 nn(e,"event.published",t,{subscribersNotified:n}),o}a(No,"recordSuccessfulPublish");function sr(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}}a(sr,"enrichMetadata");var To=0;function ri(){return To+=1,`interceptor-${Date.now()}-${To}`}a(ri,"nextInterceptorRegistrationId");var Ue=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(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 be(t.policies)),(this.policyEngine?.getPolicies()??t.policies??[]).some(Jt)&&!t.intentRegistry&&!t.dependencyGraph&&!t.getPolicyContext)throw new $e;t.getPolicyContext?this.getPolicyContext=t.getPolicyContext:t.intentRegistry||t.dependencyGraph?this.getPolicyContext=en({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,i=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,g=typeof t!="function";if(g){let p=t,f=r??n??{};c={...p,metadata:sr(p.metadata,f,this.recording.instanceId)}}else{let p=t,f=n,u=r??{},y=p(f);c={...y,metadata:sr(y.metadata,u,this.recording.instanceId)}}g&&this.strictRegistry&&await _o(this.recording,c),lt(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),Ro(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await ko(c,{interceptorsForIntent:a(p=>this.interceptorsByIntent.get(p)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),ct(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await Oo(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let m=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await Po(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(p=>this.appendTrace(p),"appendTrace"),recordAudit:a((p,f,u)=>this.recordAudit(p,f,u),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((p,f,u)=>this.safeHook(p,f,u),"safeHook")}),await No(this.recording,c,s?m.length:0,o.tx);let h=(async()=>{s&&await Promise.all(m.map(p=>this.invokeHandler(p,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})();return i?await h:h.then(void 0,()=>{}),c}createPublisher(t){let n=typeof t=="string"?t:t.name;return lt(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,s={},i)=>{if(s.source&&s.source!==n)throw new ke(n,s.source);await this.publish(r,o,{...s,source:n},i)},"publish")}}subscribe(t,n){let r=typeof t=="string"?t:t.name;lt(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 i=this.subscriptions.indexOf(o);i>=0&&this.subscriptions.splice(i,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;lt(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let s={registrationId:ri(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(s);let i=this.interceptorsByIntent.get(o)??[];return i.push(s),this.interceptorsByIntent.set(o,i),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){dt(this.recording,t)}async recordAudit(t,n,r){await nn(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 Do(e){return new Ue(e)}a(Do,"createEventBus");function oi(e){if(!(!e||e.length===0))return e.map(t=>typeof t=="object"&&t!==null&&"key"in t?String(t.key):String(t)).join(".")}a(oi,"formatStandardSchemaPath");function si(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"}a(si,"actualType");function ai(e,t){return e?`${e}.${t}`:t}a(ai,"formatPath");function Lo(e,t,n,r,o){let s=si(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(i=>Object.is(i,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}Fo(e,t.fields,r,o,n)}t.type==="array"&&t.items&&Array.isArray(e)&&e.forEach((i,l)=>{Lo(i,t.items,`${n}[${l}]`,r,o)})}a(Lo,"validateSchemaField");function Fo(e,t,n,r,o){for(let[s,i]of Object.entries(t)){let l=ai(o,s),c=e[s];if(c===void 0){i.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}Lo(c,i,l,n,r)}}a(Fo,"validateObjectSchema");var pt=class{static{a(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(Fo(s,r.schema,r,o),r.allowAdditionalFields===!1)for(let i of Object.keys(s))r.schema[i]||o.push({intent:t.intent,version:r.version,field:i,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let i=r.standardSchema["~standard"].validate(t.payload);if(i instanceof Promise)o.push({intent:t.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(i.issues)for(let l of i.issues)o.push({intent:t.intent,version:r.version,field:oi(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 rn(){return new pt}a(rn,"createEventContractRegistry");var $o=0;function ii(){return $o+=1,`outbox-${Date.now()}-${$o}`}a(ii,"nextOutboxId");function Mo(e){return{...e,event:{...e.event,metadata:{...e.event.metadata}}}}a(Mo,"cloneRecord");var Ce=class{static{a(this,"InMemoryEventBuffer")}records=new Map;async enqueue(t){let n=new Date().toISOString(),r={id:ii(),event:t,status:"pending",attempts:0,createdAt:n,updatedAt:n};return this.records.set(r.id,r),Mo(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(Mo)}async clear(){this.records.clear()}},Ko=Ce;function ar(e){return`${e.from}->${e.to}`}a(ar,"flowKey");function Ho(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}a(Ho,"uniqueFlows");function Go(e,t){let n=new Set(t.map(ar));return e.filter(r=>!n.has(ar(r)))}a(Go,"difference");function on(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})),i=n?.getHistory().map(y=>({from:y.event.metadata.source,to:y.event.intent}))??[],l=i.length>0||!r?[]:r.getEdges().filter(y=>y.kind==="observed").map(y=>({from:y.from,to:y.to})),c=Ho([...o,...s]),g=Ho([...i,...l]),m=g.filter(y=>!y.from||y.from==="unknown"),h=t?Array.from(new Set(g.map(y=>y.from).filter(y=>y&&y!=="unknown"&&!t.has(y)))):[],p=t?Array.from(new Set(g.map(y=>y.to).filter(y=>!t.has(y)))):[],f=new Set(g.flatMap(y=>[y.from,y.to])),u=t?t.list().map(y=>y.name).filter(y=>!f.has(y)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:g,declaredButUnobserved:Go(c,g),observedButUndeclared:Go(g.filter(y=>y.from!=="unknown"),c),unknownSources:m,unregisteredObservedSources:h,unregisteredObservedIntents:p,registeredButNeverObserved:u}}}}a(on,"createObservabilityReporter");function Uo(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()}}}a(Uo,"createArkTestHarness");var Vo=0;function li(){return Vo+=1,`audit-${Date.now()}-${Vo}`}a(li,"createAuditId");function ci(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)}a(ci,"matchesQuery");var ut=class{constructor(t){this.maxRecords=t}maxRecords;static{a(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=>ci(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{a(this,"AuditTrailImpl")}async record(t){let n={id:li(),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 an(e={}){return new sn(e.store??new ut(e.maxRecords))}a(an,"createAuditTrail");var ln=class{static{a(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
10
|
`);return t.trim()}toLayerMermaid(t){let n=new Map;for(let s of this.nodes.keys()){let i=t.resolveLayer(s)??"Unclassified",l=n.get(i)??[];l.push(s),n.set(i,l)}let r=`flowchart TD
|
|
@@ -15,11 +15,11 @@ ${n}`),this.name="PolicyViolationError",this.violations=t}};var be=class{static{
|
|
|
15
15
|
`;for(let s of o)r+=` ${this.safeId(s)}[${s}]
|
|
16
16
|
`;r+=` end
|
|
17
17
|
`}for(let s of this.edges){let i=s.kind?`|${s.kind}|`:"";r+=` ${this.safeId(s.from)} -->${i} ${this.safeId(s.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 s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.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=[],s=a(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let g=o.indexOf(c),m=o.slice(g).concat(c);n.push(m)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let i=new Set(n.map(l=>l.join("->")));return Array.from(i).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function cn(){return new ln}a(cn,"createDependencyGraph");function dn(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"))}a(dn,"syncRegistryToGraph");var Ve={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},
|
|
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 s=o(this.edges);s&&s.length&&n.push(...s)}catch(s){n.push(`Rule error: ${s.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=[],s=a(l=>{r.add(l),o.push(l);for(let c of t.get(l)||[])if(!r.has(c))s(c);else if(o.includes(c)){let g=o.indexOf(c),m=o.slice(g).concat(c);n.push(m)}o.pop()},"dfs");for(let l of t.keys())r.has(l)||s(l);let i=new Set(n.map(l=>l.join("->")));return Array.from(i).map(l=>l.split("->"))}safeId(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}};function cn(){return new ln}a(cn,"createDependencyGraph");function dn(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"))}a(dn,"syncRegistryToGraph");var Ve={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},jo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...Ve,default:[]},kernelRoots:{...Ve},managedLayers:{...Ve,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Bo={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...Ve,default:[]},managedLayers:{...Ve,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...Ve,default:[]}}};function ft(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ft,"isObject");function Wo(e){let t=new Set;if(!Array.isArray(e.layers))return t;for(let n of e.layers)ft(n)&&typeof n.name=="string"&&n.name.length>0&&t.add(n.name);return t}a(Wo,"declaredLayerNames");function qo(e){if(!ft(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}}a(qo,"defaultedArkRun");function zo(e){if(!ft(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}}a(zo,"defaultedArkOrder");function Yo(e,t){let n=e.arkRun;if(n===void 0||!ft(n))return;let r=Wo(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkRun.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.kernelRoots??n.compositionRoots;(!Array.isArray(s)||s.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"})}}a(Yo,"validateArkRunExtra");function Xo(e,t){let n=e.arkOrder;if(n===void 0||!ft(n))return;let r=Wo(e),o=n.managedLayers;if(Array.isArray(o)&&o.forEach((s,i)=>{typeof s=="string"&&s.length>0&&!r.has(s)&&t.push({path:`$.arkOrder.managedLayers[${i}]`,message:`layer ${JSON.stringify(s)} is not declared in layers[]`})}),n.mode==="enforced"){let s=n.planeRoots;(!Array.isArray(s)||s.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"})}}a(Xo,"validateArkOrderExtra");var re="1.3",un="https://unpkg.com/arkgate@2/schemas/ark.config.schema.json",Zo=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],di=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function pi(){let e=[];for(let t of Zo)for(let n of Zo)t===n||di.has(`${t}->${n}`)||e.push({from:t,to:n,allowed:!1});return e}a(pi,"createDefaultRules");var fn=pi(),ir=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],ne={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Jo={$schema:"https://json-schema.org/draft/2020-12/schema",$id:un,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:un,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:re,default:re},name:{type:"string",minLength:1},include:{...ne,minItems:1,default:["src"]},exclude:{...ne,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:fn,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...ne,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:{...ne,default:[]}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...ne,minItems:1},exclude:ne,intentPrefixes:ne,description:{type:"string",minLength:1},forbiddenGlobals:ne,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:{...ne,minItems:1},sharedRoots:{...ne,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; 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:{...ne,minItems:1},maxFiles:{type:"integer",minimum:1},coverageRoots:{...ne,minItems:1}}},arkRun:jo,arkOrder:Bo}},fe=class extends Error{static{a(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 i}a(rs,"createAdapter");function os(e,t=[]){let n=t.filter(r=>!ss(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(os,"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}".`}]}}a(cr,"checkAdapterGovernance");function ss(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(ss,"hasMember");var pr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),fr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gr=Object.freeze(Object.keys(fr).sort()),dr=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"}),ur=Object.freeze({process:Object.freeze(["process","node:process"])});function mt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=dr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=dr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:dr[e.slice(0,s)]??null}a(mt,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(ur[n]?.includes(e))return n;return null}a(Ie,"forbiddenGlobalForModuleSpecifier");function Rn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=fr[r];if(o)return o}return null}a(Rn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...pr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>pr.includes(r));return[...new Set(n)].sort()}a(We,"effectiveCapabilityDeny");function yt(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}a(yt,"ambientCoveredByForbiddenGlobals");function An(e){let t=new Set,n=new Set,r=Object.keys(fr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of ur[o]??[])t.add(`import-exact:${i}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of ur.process)t.add(`import-exact:${s}`);for(let s of r)Rn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(An,"loweredLayerCoverage");function qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(qe,"literalText");function ls(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(ls,"lineOf");function as(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))}a(as,"isTypeOnlyReference");function cs(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()}a(cs,"singleFileChecker");function mr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(mr,"symbolAt");function yr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):mr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(yr,"localDeclaration");function ze(e,t){let n,r=[],o=a((i,l,c,g=!1)=>r.push({specifier:c,kind:l,line:ls(t,i),typeOnly:g,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",qe(e,i.moduleSpecifier),as(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",qe(e,i.moduleSpecifier),as(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",qe(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!yr(e,n??(n=cs(e,t)),t,i.expression);(l||g)&&o(i,g?"require":"dynamic-import",qe(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(ze,"extractSemanticDependencies");function ki(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=qe(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}}a(ki,"staticAccessPath");function Ii(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}a(Ii,"runtimeIdentifierReference");function is(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}}a(is,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=cs(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations)e.isIdentifier(f.name)&&i.add(f.name.text);let l=a(p=>{let f=ki(e,p);if(!f)return;let u=mr(o,f.root),y=u?s.get(u):void 0;return y?[...y,...f.segments.slice(1)]:yr(e,o,t,f.root)||i.has(f.root.text)?void 0:f.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let u=l(f.initializer),y=mr(o,f.name);!u||!y||s.set(y,u)}let c=[],g=new Set,m=a((p,f)=>{let u=ls(t,f),y=`${p}:${f.getStart(t)}`;g.has(y)||(g.add(y),c.push({name:p,line:u,node:f}))},"flag"),h=a(p=>{let f=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!f){let u=l(p),y=u?is(r,u):void 0;y&&m(y,p)}else e.isIdentifier(p)&&r.has(p.text)&&Ii(e,p)&&!yr(e,o,t,p)&&m(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let u=l(p.initializer);if(u)for(let y of p.name.elements){if(!e.isIdentifier(y.name))continue;let E=y.propertyName?qe(e,y.propertyName)??y.propertyName.text:y.name.text,b=is(r,[...u,E]);b&&m(b,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}a(Ye,"collectForbiddenCapabilityUses");function hr(e,t,n){let r=[];for(let o of n?.dependencies??ze(e,t)){if(o.typeOnly||!o.specifier)continue;let s=mt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,gr)){let s=Rn(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))}a(hr,"collectCapabilityUses");var Rr={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."},Ar=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 kr(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}a(kr,"resolveIntentLayer");function we(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(we,"looksLikeArkIntent");function ht(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&we(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Rr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Rr.PUBLISH_MISSING_SOURCE}),t}a(ht,"classifyPublishFacts");function U(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(U,"violation");function Xe(e,t){return e.slice(0,t).split(`
|
|
22
|
-
`).length}a(Xe,"lineOf");function vi(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}a(vi,"extractQuotedStrings");function Ei(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]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(Ei,"extractModuleSpecifiers");function bi(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(bi,"extractQuotedStringsAst");function Si(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))}a(Si,"hasInfrastructureToken");function Ci(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(Ci,"isKnownInfrastructurePackage");function wi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(wi,"layerHasInfrastructureRole");function At(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(At,"tsStringLiteralText");function xi(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(xi,"tsPropertyName");function ds(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:xi(e,r.name)===n)}a(ds,"tsObjectProperty");function kt(e,t,n){return ds(e,t,n)!==void 0}a(kt,"tsObjectHasProperty");function Rt(e,t,n){let r=ds(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Rt,"tsObjectPropertyValue");function Oi(e,t){let n=Rt(e,t,"metadata");return kt(e,n,"source")}a(Oi,"tsObjectHasMetadataSource");function ps(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?ps(e,t.name):!1:!1}a(ps,"tsLooksLikeIntentCreatorExpression");function Pi(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"}a(Pi,"tsIsPublishCall");function _i(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=At(e,n);return r!==void 0&&we(r)||kt(e,n,"intent")||ps(e,n)}a(_i,"tsIsArkPublishCandidate");function Ni(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Oi(e,n)||kt(e,r,"source")||kt(e,o,"source")}a(Ni,"tsPublishHasSource");function Ti(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Rt(e,n,"metadata");return At(e,Rt(e,s,"source"))??At(e,Rt(e,r,"source"))??At(e,Rt(e,o,"source"))}a(Ti,"tsPublishSourceLiteral");function Di(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],g=a(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=a(h=>{if(Pi(e,h)){let p=h.arguments[0],f=At(e,p);for(let y of ht({publishCall:!0,rawIntentName:f,objectHasIntent:kt(e,p,"intent"),arkPublishCandidate:_i(e,h),hasSource:Ni(e,h)}))c.push(U(y.ruleId,y.message,{line:g(h),filePath:i}));let u=Ti(e,h);if(r&&l&&u&&we(u)){let y=r.resolveLayer(u);y&&y!==l&&c.push(U("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${y}, but the target file is classified as ${l}.`,{line:g(h),filePath:i,target:u,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}a(Di,"analyzePublishAst");function us(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,i){let l=[],c=i,g=c?.filePath,m=c?.layer,h=e.typescript,p=h?h.createSourceFile(g??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,f=p?ze(e.typescript,p):void 0,u=f?f.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(p),kind:A.kind,typeOnly:A.typeOnly})):Ei(s),y=e.typescript?bi(e.typescript,s):vi(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(g))for(let A of f?.filter(({unresolved:v})=>v)??[]){let v=A.kind==="require";l.push(U(v?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${v?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:g}))}let E=m!==void 0&&(r.has(m)||wi(m)),b=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 v=A.exec(s);A.lastIndex=0,v&&l.push(U("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:v.index===void 0?void 0:Xe(s,v.index),filePath:g,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else s.includes(A)&&l.push(U("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:Xe(s,s.indexOf(A)),filePath:g}));for(let A of u){let v=e.resolveImportTarget?.(A.value,g)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,g)}:void 0),P=typeof g=="string"?e.resolveImportTarget?.(g)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,j=v?.layer;if(j&&m){let k=ue(e.architectureProfile?.rules,m,j,{fromPath:P?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(k){if(A.typeOnly&&!k.peerIsolation)continue;let _=!!k.peerIsolation;l.push(U("LAYER_IMPORT_VIOLATION",k.message??(_?`Layer "${m}" must not import across slices into "${j}".`:`Layer "${m}" must not import "${j}".`),{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,fromLayer:m,toLayer:j,suggestion:_?"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:_,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}E||A.typeOnly||!Si(A.value)&&!Ci(A.value)||l.push(U("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let v=A.check({source:s,context:i});if(v!==!0)if(Array.isArray(v))for(let P of v)l.push(U("POLICY_VIOLATION",P.message,{filePath:g,suggestion:`Fix violation of policy "${A.name}".`}));else v===!1?l.push(U("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(U("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let A of y)we(A.value)&&!t.has(A.value)&&l.push(U("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:Xe(s,A.index),filePath:g,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let A of y){if(!we(A.value))continue;let v=e.architectureProfile.resolveLayer(A.value);if(!v)continue;let P=ue(e.architectureProfile.rules,m,v);P&&l.push(U("LAYER_REFERENCE_VIOLATION",P.message??`Layer "${m}" must not reference "${v}" through "${A.value}".`,{line:Xe(s,A.index),filePath:g,target:A.value,fromLayer:m,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:P}}))}if(e.extensions)for(let A of e.extensions)try{let v=A.analyze(s,i);l.push(...v)}catch(v){l.push(U("EXTENSION_ERROR",`Extension "${A.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&m&&e.forbiddenGlobals?.[m]?.length)try{let A=e.forbiddenGlobals[m];l.push(...Ye(e.typescript,p,A).map(v=>U("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${v.name}".`,{line:v.line,filePath:g,target:v.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 v of f??[]){if(v.typeOnly||!v.specifier)continue;let P=Ie(v.specifier,A);P&&l.push(U("FORBIDDEN_GLOBAL",`${m} must not use module "${v.specifier}" because it is the import form of forbidden global "${P}".`,{line:v.line,filePath:g,source:v.specifier,target:v.specifier,fromLayer:m,details:{importKind:v.kind,forbiddenGlobal:P},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&p&&m&&e.capabilityWalls?.[m]?.length)try{let A=new Set(e.capabilityWalls[m]),v=e.forbiddenGlobals?.[m]??[];for(let P of hr(e.typescript,p))A.has(P.capability)&&(P.source==="ambient-global"&&yt(P.symbol,v)||P.source==="import-based"&&Ie(P.symbol,v)||l.push(U("CAPABILITY_VIOLATION",P.source==="import-based"?`${m} denies the ${P.capability} capability; found import of "${P.symbol}".`:`${m} denies the ${P.capability} capability; found ambient "${P.symbol}".`,{line:P.line,filePath:g,target:P.symbol,capability:P.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...Di(e.typescript,s,i,e.architectureProfile))}catch(A){l.push(U("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}}}}a(us,"createAICodeGate");function B(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")}`}a(B,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}a(F,"stableSerialize");var xe="1.2";var fs=["network","filesystem","clock","randomness","environment","process","persistence"];function V(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}a(V,"compareCanonical");function W(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(W,"sortedUnique");function It(e){let t={schemaVersion:"1.2",include:W(e.include??[]),exclude:W(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:W(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:W(n.patterns??[]),exclude:W(n.exclude??[]),forbiddenGlobals:W(n.forbiddenGlobals??[]),intentPrefixes:W(n.intentPrefixes??[]),capabilityDeny:W(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(V),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:W(e.arkRun.compositionRoots),managedLayers:W(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return B(F(t))}a(It,"resolvedFactsEvidenceRequirementsHash");function Li(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(V),n=e.files.map(k=>({...k,typeOnlyExportNames:W(k.typeOnlyExportNames)})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:W(k.namedBindings)}:{}})).sort(V),o=e.capabilityUses.map(k=>({...k})).sort(V),s=e.ambientUses.map(k=>({...k})).sort(V),i=e.publishCalls.map(k=>({...k})).sort(V),l=e.intentReferences.map(k=>({...k})).sort(V),c=e.safetyUses.map(k=>({...k})).sort(V),g=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(_=>({..._}))})).sort(V),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(V),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(V),p=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(V),f=(e.arkRunDeclarations??[]).map(k=>({...k,uses:W(k.uses),reactsTo:W(k.reactsTo),raises:W(k.raises),sends:W(k.sends)})).sort(V),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(V),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(V),E=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(V),b=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(V),A=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(V),v=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(V),P=e.files.map(({path:k,contentHash:_})=>({path:k,contentHash:_})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),j=B(F(P));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:j,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:g,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:f,arkOrderPlaneCalls:u,arkOrderGenericUpdates:y,arkOrderRootHits:E,arkOrderXiFieldWrites:b,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:v}}a(Li,"canonicalResolvedFactsInput");function gs(e){let t=Li(e);return{...t,factsHash:B(F(t))}}a(gs,"createCanonicalResolvedCandidateFacts");function Ir(e){return gs(ys(D(e,"$"),!1))}a(Ir,"createResolvedCandidateFacts");function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(D,"asRecord");function $(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"}.`)}a($,"assertOnlyKeys");function T(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}a(T,"requiredText");function ge(e,t,n){if(e[t]!==void 0)return T(e,t,n)}a(ge,"optionalText");function M(e,t,n){let r=T(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 i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(M,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(K,"requiredBoolean");function ms(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)}a(ms,"requiredInteger");function Y(e,t,n){let r=ms(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(Y,"requiredPositiveInteger");function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(H,"requiredArray");function me(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}a(me,"enumValue");function Ze(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]}a(Ze,"parseStringArray");function Fi(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)}}a(Fi,"assertUnique");function ys(e,t){$(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=me(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=me(e,"completeness",["complete","partial","unavailable"],"$"),o=H(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=D(S,R);$(d,["code","message","file"],R);let N=d.file===void 0?void 0:M(d,"file",R);return{code:T(d,"code",R),message:T(d,"message",R),...N?{file:N}:{}}});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=H(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=D(S,R);return $(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:M(d,"path",R),contentHash:T(d,"contentHash",R),parseStatus:me(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:ms(d,"parseDiagnosticCount",R),exportsOnlyTypes:K(d,"exportsOnlyTypes",R),typeOnlyExportNames:Ze(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:K(d,"hasTopLevelSideEffects",R)}}),i=H(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=D(S,R);$(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=ge(d,"specifier",R),L=ge(d,"target",R),te=me(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(te==="resolved-project"&&!L)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(te!=="resolved-project"&&L)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(te!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:M(d,"from",R),...N?{specifier:N}:{},kind:me(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:K(d,"typeOnly",R),line:Y(d,"line",R),resolution:te,...L?{target:M(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:Ze(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:K(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:K(d,"portProofEligible",R)}:{}}}),l=H(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol","capability","source"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R),capability:me(d,"capability",fs,R),source:me(d,"source",["ambient-global","import-based"],R)}}),c=H(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R)}}),g=H(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=D(S,R);$(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=ge(d,"rawIntentName",R),L=ge(d,"sourceIntent",R);return{file:M(d,"file",R),line:Y(d,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:K(d,"objectHasIntent",R),arkPublishCandidate:K(d,"arkPublishCandidate",R),hasSource:K(d,"hasSource",R),...L?{sourceIntent:L}:{}}}),m=H(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=D(S,R);return $(d,["file","line","intent"],R),{file:M(d,"file",R),line:Y(d,"line",R),intent:T(d,"intent",R)}}),h=H(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=D(S,R);$(d,["file","line","kind","symbol"],R);let N=ge(d,"symbol",R),L=me(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(L==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(L!=="in-memory-store"&&N)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:M(d,"file",R),line:Y(d,"line",R),kind:L,...N?{symbol:N}:{}}});Fi(s,S=>S.path,"$.files");let p=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 i)if(!p.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:H(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=D(S,R);$(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=ge(d,"receiver",R),L=ge(d,"nameLiteral",R);return{file:M(d,"file",R),line:Y(d,"line",R),kind:me(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(d,"callee",R),viaImport:K(d,"viaImport",R),...N?{receiver:N}:{},...L?{nameLiteral:L}:{}}}),E=(e.arkRunManagedNews===void 0?[]:H(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=D(S,R);$(d,["file","line","typeName","importedFrom"],R);let N=ge(d,"importedFrom",R);return{file:M(d,"file",R),line:Y(d,"line",R),typeName:T(d,"typeName",R),...N?{importedFrom:N}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:H(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasKernelFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasKernelFactory:K(d,"hasKernelFactory",R)}}),v=e.arkRunDeclarations===void 0?[]:H(e,"arkRunDeclarations","$"),j=(e.arkOrderPlaneCalls===void 0?[]:H(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=D(S,R);return $(d,["file","line","callee"],R),{file:M(d,"file",R),line:Y(d,"line",R),callee:T(d,"callee",R)}}),_=(e.arkOrderGenericUpdates===void 0?[]:H(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=D(S,R);return $(d,["file","line","method"],R),{file:M(d,"file",R),line:Y(d,"line",R),method:T(d,"method",R)}}),de=(e.arkOrderRootHits===void 0?[]:H(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasPlaneFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasPlaneFactory:K(d,"hasPlaneFactory",R)}}),Ne=(e.arkOrderXiFieldWrites===void 0?[]:H(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=D(S,R);return $(d,["file","line","key"],R),{file:M(d,"file",R),line:Y(d,"line",R),key:T(d,"key",R)}}),Wt=(e.arkOrderIngestWritesXi===void 0?[]:H(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=D(S,R);return $(d,["file","line"],R),{file:M(d,"file",R),line:Y(d,"line",R)}}),zn=(e.arkOrderReleaseKeyCounts===void 0?[]:H(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=D(S,R);return $(d,["file","line","keyCount"],R),{file:M(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),at=v.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=D(S,R);return $(d,["file","line","uses","reactsTo","raises","sends"],R),{file:M(d,"file",R),line:Y(d,"line",R),uses:Ze(d.uses,`${R}.uses`),reactsTo:Ze(d.reactsTo,`${R}.reactsTo`),raises:Ze(d.raises,`${R}.raises`),sends:Ze(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",g],["$.intentReferences",m],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",at],["$.arkOrderPlaneCalls",j],["$.arkOrderGenericUpdates",_],["$.arkOrderRootHits",de],["$.arkOrderXiFieldWrites",Ne],["$.arkOrderIngestWritesXi",Wt],["$.arkOrderReleaseKeyCounts",zn]])for(let R of C)if(!p.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Ee=ge(e,"projectPackageName","$"),Yn=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=D(S,R);$(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=H(d,"mutatingMethods",R).map((L,te)=>{let zt=`${R}.mutatingMethods[${te}]`,Xn=D(L,zt);return $(Xn,["name","referencesGuardOrPublish"],zt),{name:T(Xn,"name",zt),referencesGuardOrPublish:K(Xn,"referencesGuardOrPublish",zt)}});return{file:M(d,"file",R),className:T(d,"className",R),exported:K(d,"exported",R),hasPublicMutableFields:K(d,"hasPublicMutableFields",R),hasPublicSetters:K(d,"hasPublicSetters",R),hasPublicConstructor:K(d,"hasPublicConstructor",R),hasStaticFactory:K(d,"hasStaticFactory",R),mutatingMethods:N,...d.dataOnly===void 0?{}:{dataOnly:K(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...Ee?{projectPackageName:Ee}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:g,intentReferences:m,safetyUses:h,classShapes:Yn,arkRunKernelCalls:u,arkRunManagedNews:E,arkRunCompositionRootHits:A,arkRunDeclarations:at,arkOrderPlaneCalls:j,arkOrderGenericUpdates:_,arkOrderRootHits:de,arkOrderXiFieldWrites:Ne,arkOrderIngestWritesXi:Wt,arkOrderReleaseKeyCounts:zn}}a(ys,"parseResolvedFactsInput");function ve(e){let t=D(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=gs(ys(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}a(ve,"loadResolvedCandidateFacts");var $i=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},X={type:"integer",minimum:1},G={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:x,message:x,file:G}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:G,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},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:G,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:X,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:G,namedBindings:{type:"array",items:x},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:G,line:X,symbol:x,capability:{enum:$i},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:G,line:X,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:G,line:X,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:G,line:X,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:G,line:X,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},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:G,className:x,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:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:G,line:X,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:G,line:X,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:G,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:G,line:X,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:G,line:X,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:G,line:X,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:G,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:G,line:X,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:G,line:X}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:G,line:X,keyCount:{type:"integer",minimum:1}}}},factsHash:x},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 Er="1.0";function Q(e){return`${e.from}->${e.to}`}a(Q,"dependencyKey");function vt(e,t,n,r="dependency"){return{id:`${e}:${r}:${Q(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Q(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Q(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Q(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Q(t)} from the candidate, then preflight again.`}:{}}}a(vt,"dependencyFinding");function Je(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[Q(p),p])),s=new Map(e.baseDependencies.map(p=>[Q(p),p])),i=new Map(e.candidateDependencies.map(p=>[Q(p),p]));for(let p of[...n.values()].sort((f,u)=>f.path.localeCompare(u.path))){let f=r.get(p.path);f?f.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((f,u)=>f.path.localeCompare(u.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((f,u)=>Q(f).localeCompare(Q(u)))){if(i.has(Q(p))){t.push(vt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let f={from:p.to,to:p.from};i.has(Q(f))?(l.add(Q(f)),t.push(vt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(vt("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,f]of[...i].sort(([u],[y])=>u.localeCompare(y)))s.has(p)||o.has(p)||l.has(p)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,f]of[...s].sort(([u],[y])=>u.localeCompare(y)))i.has(p)||g.has(f.from)||g.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("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((p,f)=>m[p.classification]-m[f.classification]||(p.subject===f.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(f.id));let h={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.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}}a(Je,"analyzeArchitectureConvergence");var hs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Mi=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var Rs={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},ju={$schema:"https://json-schema.org/draft/2020-12/schema",$id:hs,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:hs},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:[...Mi]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:Rs,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:Rs}}}};function Et(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(Et,"emptyEffectiveArkRules");function As(e){let{stewards:t,...n}=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}))}}}a(As,"effectiveContractPolicyPayload");function ks(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}.`}a(ks,"formatCoverageDiscards");function Ki(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}/`)})}a(Ki,"isUnderCoverageRoot");function Hi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}a(Hi,"titleMatchesInvariant");function Gi(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}a(Gi,"symbolPresent");function Is(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,i=ks(s),l=ks(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",g=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),m=g.length>0,h=g.join(", "),p=[],f=[];for(let u of t){let y=[],E=u.coverage?.test!==!1,b=u.coverage?.symbol,A,v;if(!r&&E){let _;for(let z of n){let de=e.fileContents[z];if(!(!de||!Hi(de,u.id))){if(!m||Ki(z,g)){A=z,v=m?!1:void 0;break}_??=z}}A===void 0&&_!==void 0&&(A=_,v=!0),A!==void 0&&y.push("test-title")}b&&Gi(e.fileContents,b)&&y.push("symbol");let j=(u.coverage?.test===!0||!!b||u.coverage===void 0)&&y.length>0||u.coverage?.test===!1&&!b?!0:y.length>0,k=r&&E&&y.length===0;if(p.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:j&&!k,evidence:y,partial:k,description:u.description,...A!==void 0?{testEvidenceFile:A}:{},...v!==void 0?{outsideDeclaredRoots:v}:{}}),v===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.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:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!j||k){let _=u.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(k?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${u.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 ${u.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.`)+(k&&o?l:i),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:_?"error":"warning",failsStrict:_,kind:z})}}return{coverage:p,violations:f,partial:p.some(u=>u.partial)}}a(Is,"evaluateInvariantCoverage");function vs(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."}}a(vs,"canPromoteInvariant");var Cr="1.0";function O(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}})}a(O,"addFinding");function q(e){return[...new Set(e??[])].sort()}a(q,"sortedUnique");function ie(e,t,n,r,o){let s=q(n),i=q(r),l=new Set(s),c=new Set(i),g=i.filter(h=>!l.has(h)),m=s.filter(h=>!c.has(h));g.length===0&&m.length===0||(g.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),m.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ie,"compareStringSets");function bt(e,t,n,r,o,s,i){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(bt,"compareBoolean");function kn(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()}}a(kn,"keyed");function Ui(e,t,n){let r=kn(t,s=>s.name),o=kn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(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 i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(i&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;ie(e,`${c}.patterns`,i.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."}),ie(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=An(i),m=An(l);ie(e,`${c}.forbiddenGlobals`,g.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."}),ie(e,`${c}.capabilities`,g.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(i.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&O(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(i.intentPrefixes),after:q(l.intentPrefixes)}),bt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),bt(e,`${c}.optional`,i.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.")}}a(Ui,"compareLayers");function Vi(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=kn(t,r),s=kn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(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 i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),g=`$.rules[${i}]`;if(!l&&c){c.allowed===!1&&O(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&O(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${g}.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 p=l.from===l.to&&c.from===c.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:p?h?"strengthening":"weakening":"judgment-required",message:p?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")&&O(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!m&&!h)&&(bs(e,`${g}.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."),bs(e,`${g}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(Es)),q((c.allowedCrossSlice??[]).map(Es)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}a(Vi,"compareRules");function Es(e){return JSON.stringify([e.from,e.to])}a(Es,"crossSliceKey");function bs(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),g=l.length>0&&c.length>0;O(e,{kind:g?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:g?"judgment-required":l.length>0?"weakening":"strengthening",message:g?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(bs,"compareDeclaredExceptions");function ji(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&O(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])bt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(ji,"compareSafety");function br(e){return e.mode==="enforced"?"enforced":"advisory"}a(br,"arkRunMode");function Sr(e){return e.mode==="enforced"?"enforced":"advisory"}a(Sr,"arkOrderMode");function Bi(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Sr(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Sr(r),l=Sr(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(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:i,after:l})}ie(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."}),ie(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."})}a(Bi,"compareArkOrder");function Wi(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${br(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=br(r),l=br(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(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:i,after:l})}ie(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."}),ie(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."}),bt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(Wi,"compareArkRun");function qi(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"}a(qi,"overallClassification");function Ss(e,t){return`${e}::${t}`}a(Ss,"ruleKey");function Cs(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Ss(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Ss(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(Cs,"indexEffectiveRules");function zi(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},g=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of g){let f=l[p],u=c[p],y=`$.arkRules[${p}]`;if(f===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:u});continue}if(f!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:f});continue}f!==u&&O(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:f,after:u})}let m=Cs(r),h=Cs(o);for(let p of[...new Set([...m.structure.keys(),...h.structure.keys()])].sort()){let f=m.structure.get(p),u=h.structure.get(p),y=`$.arkRules.structure[${p}]`;if(!f&&u){O(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!u)){if(f.mode!==u.mode){let E=f.mode==="advisory"&&u.mode==="enforced";O(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}f.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:f.sensor,after:u.sensor})}}for(let p of[...new Set([...m.invariants.keys(),...h.invariants.keys()])].sort()){let f=m.invariants.get(p),u=h.invariants.get(p),y=`$.arkRules.invariants[${p}]`;if(!f&&u){O(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!u)&&f.mode!==u.mode)if(f.mode==="advisory"&&u.mode==="enforced"){let b=i?.get(u.id),A=vs(b);A.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}}a(zi,"compareArkRules");function wr(e,t,n){let r=[];ie(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(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."}),ie(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."}),bt(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",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(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}),Ui(r,e.layers,t.layers),Vi(r,e.rules,t.rules),ji(r,e,t),zi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),Wi(r,e,t),Bi(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:Cr,classification:qi(r),findings:r}}a(wr,"classifyArkPolicyDelta");function xr(e,t){if(!e||e.schemaVersion!==Cr||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])}a(xr,"policyDeltaAcknowledgementMatches");function Oe(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("/")}a(Oe,"normalizePath");function ws(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(ws,"isIdentifierStart");function In(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(In,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ee,"skipWhitespace");function St(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}}a(St,"readString");function oe(e,t,n){return e.startsWith(t,n)&&!In(e[n-1])&&!In(e[n+t.length])}a(oe,"isWordAt");function xs(e,t){let n=ee(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ee(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!oe(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||oe(e,"as",o)||!ws(e[o]))return!1;for(n=o;n<e.length&&In(e[n]);)n+=1;if(n=ee(e,n),oe(e,"as",n)){if(n=ee(e,n+2),!ws(e[n]))return!1;for(;n<e.length&&In(e[n]);)n+=1}r=!0}return!1}a(xs,"bracedNamedBindingsAreTypeOnly");function Yi(e,t){if(t=ee(e,t+6),e[t]==="(")return St(e,ee(e,t+1));let n=!1;if(oe(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!oe(e,"from",o)&&(n=!0)}else xs(e,t)&&(n=!0);let r=Os(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(Yi,"specifierAfterImport");function Xi(e,t){t=t+6;let n=ee(e,t),r=!1;if(oe(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else xs(e,n)&&(r=!0);let o=Os(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Xi,"specifierAfterExport");function Os(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(oe(e,"from",t))return St(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return St(e,t);if(t>0&&(oe(e,"import",t)||oe(e,"export",t)))return}}a(Os,"specifierInStaticStatement");function Zi(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}a(Zi,"skipTemplateLiteral");function Ji(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ee(e,t+7);if(e[r]!=="(")return;r=ee(e,r+1);let o=St(e,r);return o?{...o,requireCall:!0}:void 0}a(Ji,"specifierAfterRequire");function Qi(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 s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=
|
|
20
|
+
`)}`),this.name="ArkConfigValidationError",this.source=t,this.issues=n}};function Qo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(Qo,"isObject");function pn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}a(pn,"propertyPath");function je(e){return e===null?"null":Array.isArray(e)?"array":typeof e}a(je,"valueType");function ui(e,t){let n="#/$defs/";if(e.startsWith(n))return t.$defs[e.slice(n.length)]}a(ui,"resolveSchemaRef");function gt(e,t,n,r,o){if(t.$ref){let s=ui(t.$ref,r);if(!s){o.push({path:n,message:`schema reference ${t.$ref} cannot be resolved`});return}gt(e,s,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(s=>Object.is(s,e))){o.push({path:n,message:`must be one of ${t.enum.map(String).join(", ")}`});return}if(t.type==="object"){if(!Qo(e)){o.push({path:n,message:`must be an object; received ${je(e)}`});return}let s=t.properties??{};for(let i of t.required??[])e[i]===void 0&&o.push({path:pn(n,i),message:"is required"});if(t.additionalProperties===!1)for(let i of Object.keys(e))i in s||o.push({path:pn(n,i),message:"unknown field"});else if(t.additionalProperties!==void 0&&t.additionalProperties!==!0&&typeof t.additionalProperties=="object"){let i=t.additionalProperties;for(let l of Object.keys(e))l in s||gt(e[l],i,pn(n,l),r,o)}for(let[i,l]of Object.entries(s))e[i]!==void 0&>(e[i],l,pn(n,i),r,o);return}if(t.type==="array"){if(!Array.isArray(e)){o.push({path:n,message:`must be an array; received ${je(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 s=e.map(i=>JSON.stringify(i));new Set(s).size!==s.length&&o.push({path:n,message:"must not contain duplicate items"})}t.items&&e.forEach((s,i)=>gt(s,t.items,`${n}[${i}]`,r,o));return}if(t.type==="string"){if(typeof e!="string"){o.push({path:n,message:`must be a string; received ${je(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 ${je(e)}`});return}if(t.type==="integer"){if(!Number.isInteger(e)){o.push({path:n,message:`must be an integer; received ${je(e)}`});return}t.minimum!==void 0&&e<t.minimum&&o.push({path:n,message:`must be at least ${t.minimum}`})}}a(gt,"validateNode");function fi(e){let t={...e,$schema:e.$schema===void 0?un:e.$schema,schemaVersion:e.schemaVersion===void 0?re:e.schemaVersion,include:e.include===void 0?["src"]:e.include,layers:e.layers===void 0?[]:e.layers,rules:e.rules===void 0?fn.map(n=>({...n})):e.rules};return e.arkRun!==void 0&&(t.arkRun=qo(e.arkRun)),e.arkOrder!==void 0&&(t.arkOrder=zo(e.arkOrder)),t}a(fi,"defaultedConfig");function gi(e){return e===re?null:e==="unversioned"?"unversioned":e==="1.0"||e==="1.1"||e==="1.2"?e:null}a(gi,"migratedFromOf");function mi(){let e=new Set([re]);for(let t of ir)t.from!=="unversioned"&&e.add(t.from),e.add(t.to);return e}a(mi,"knownInputVersions");function yi(e,t="ark.config.json"){if(!Qo(e))throw new fe(t,[{path:"$",message:`must be an object; received ${je(e)}`}]);let n=mi(),r=e.schemaVersion===void 0?"unversioned":typeof e.schemaVersion=="string"?e.schemaVersion:null;if(r===null)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(e.schemaVersion)}; expected ${re}`}]);if(r!=="unversioned"&&!n.has(r))throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);let o=r,s={...e},i=0;for(;o!==re&&i<ir.length+1;){i+=1;let l=ir.find(c=>c.from===o);if(!l)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${re}`}]);o=l.to,s.schemaVersion=o}if(o!==re)throw new fe(t,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${re}`}]);return{candidate:fi(s),migratedFrom:gi(r)}}a(yi,"migrateArkConfig");function lr(e,t="ark.config.json"){let{candidate:n,migratedFrom:r}=yi(e,t),o=[];if(gt(n,Jo,"$",Jo,o),Yo(n,o),Xo(n,o),o.length>0)throw new fe(t,o);return{config:n,migratedFrom:r}}a(lr,"loadArkConfigContract");function es(e,t="ark.config.json"){let n;try{n=JSON.parse(e)}catch(r){throw new fe(t,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return lr(n,t)}a(es,"parseArkConfigJson");function ts(e){let t={$schema:typeof e.$schema=="string"&&e.$schema.length>0?e.$schema:un,schemaVersion:re};for(let[n,r]of Object.entries(e))n!=="$schema"&&n!=="schemaVersion"&&(t[n]=r);return t}a(ts,"withArkConfigMetadata");function hi(e){return e.endsWith(".")?e:`${e}.`}a(hi,"normalizePrefix");function Ri(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}a(Ri,"byLongestPrefix");function gn(e){let t=e.layers.map(o=>({...o,prefixes:o.prefixes.map(hi)})),n=[...t].sort(Ri),r=[...e.rules??[]];return{name:e.name,layers:t,rules:r,resolveLayer(o){return t.find(s=>s.match?.(o))?.name??n.find(s=>s.prefixes.some(i=>o.startsWith(i)))?.name}}}a(gn,"createArchitectureProfile");function mn(e,t={}){return gn({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??[]})}a(mn,"createArchitectureProfileFromArkConfig");var Ai=[{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}],Be=gn({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:Ai,rules:fn.map(e=>({...e}))}),ki={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 ns(e={}){let t=e.rootDir??"src",n=e.optionalLayers??!0,r=t==="."?"":`${t}/`;return ts({include:e.include??[t],layers:Be.layers.map(o=>({name:o.name,patterns:(ki[o.name]??[o.name]).map(s=>`${r}${s}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Be.rules]})}a(ns,"createElevenLayerArkConfig");var yn=class{static{a(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 hn(){return new yn}a(hn,"createMetadataRegistry");function rs(e,t={}){return{name:e,ownerLayer:t.ownerLayer,intent:t.intent,allowedAdapters:t.allowedAdapters?[...t.allowedAdapters]:void 0}}a(rs,"definePort");function os(e,t,n,r={}){let o=Array.isArray(n)?{...r,requiredKeys:n}:{...n??{}},s=o.requiredKeys;if(s&&s.length>0){let c=s.filter(g=>!as(t,g));if(c.length>0)throw new Error(`Adapter for port "${e.name}" is missing required members: ${c.join(", ")}`)}let i={name:o.name,layer:o.layer,intent:o.intent,port:e,impl:t},l=cr(i);if(!l.ok)throw new Error(l.issues.map(c=>c.message).join(`
|
|
21
|
+
`));return i}a(os,"createAdapter");function ss(e,t=[]){let n=t.filter(r=>!as(e,r));return n.length===0?{ok:!0}:{ok:!1,missing:n}}a(ss,"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}".`}]}}a(cr,"checkAdapterGovernance");function as(e,t){return e!=null&&(typeof e=="object"||typeof e=="function")&&t in e}a(as,"hasMember");var pr=Object.freeze(["network","filesystem","clock","randomness","environment","process","persistence"]),fr=Object.freeze({fetch:"network",XMLHttpRequest:"network",Date:"clock","Date.now":"clock","Math.random":"randomness","process.env":"environment",process:"process"}),gr=Object.freeze(Object.keys(fr).sort()),dr=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"}),ur=Object.freeze({process:Object.freeze(["process","node:process"])});function mt(e){if(!e||e.startsWith(".")||e.startsWith("/"))return null;let t=dr[e];if(t)return t;let n=e.indexOf("/");if(n<0)return null;let r=e.slice(0,n),o=dr[r];if(o)return o;let s=e.indexOf("/",n+1);return s<0?null:dr[e.slice(0,s)]??null}a(mt,"capabilityForModuleSpecifier");function Ie(e,t){for(let n of t)if(ur[n]?.includes(e))return n;return null}a(Ie,"forbiddenGlobalForModuleSpecifier");function Rn(e){let t=e.split(".");for(let n=t.length;n>=1;n-=1){let r=t.slice(0,n).join("."),o=fr[r];if(o)return o}return null}a(Rn,"capabilityForAmbientName");function We(e){if(e?.pure===!0)return[...pr].sort();let n=(e?.capabilities?.deny??[]).filter(r=>pr.includes(r));return[...new Set(n)].sort()}a(We,"effectiveCapabilityDeny");function yt(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}a(yt,"ambientCoveredByForbiddenGlobals");function An(e){let t=new Set,n=new Set,r=Object.keys(fr);for(let o of e?.forbiddenGlobals??[]){let s=r.filter(i=>i===o||i.startsWith(`${o}.`));if(s.length===0)n.add(o);else for(let i of s)t.add(`ambient:${i}`);for(let i of ur[o]??[])t.add(`import-exact:${i}`)}for(let o of We(e)){if(t.add(`import:${o}`),o==="process")for(let s of ur.process)t.add(`import-exact:${s}`);for(let s of r)Rn(s)===o&&t.add(`ambient:${s}`)}return{atoms:[...t].sort(),rawGlobals:[...n].sort()}}a(An,"loweredLayerCoverage");function qe(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(qe,"literalText");function cs(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line+1}a(cs,"lineOf");function is(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))}a(is,"isTypeOnlyReference");function ds(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()}a(ds,"singleFileChecker");function mr(e,t){try{return e.getSymbolAtLocation(t)}catch{return}}a(mr,"symbolAt");function yr(e,t,n,r){let o=r.parent&&e.isShorthandPropertyAssignment(r.parent)&&r.parent.name===r,s;try{s=o?t.getShorthandAssignmentValueSymbol(r.parent):mr(t,r)}catch{s=void 0}return!!s?.declarations?.some(i=>i.getSourceFile().fileName===n.fileName)}a(yr,"localDeclaration");function ze(e,t){let n,r=[],o=a((i,l,c,g=!1)=>r.push({specifier:c,kind:l,line:cs(t,i),typeOnly:g,unresolved:c===void 0,node:i}),"add"),s=a(i=>{if(e.isImportDeclaration(i))o(i,"import",qe(e,i.moduleSpecifier),is(e,i));else if(e.isExportDeclaration(i)&&i.moduleSpecifier)o(i,"export",qe(e,i.moduleSpecifier),is(e,i));else if(e.isImportEqualsDeclaration(i)&&e.isExternalModuleReference(i.moduleReference))o(i,"require",qe(e,i.moduleReference.expression),i.isTypeOnly===!0);else if(e.isCallExpression(i)){let l=i.expression.kind===e.SyntaxKind.ImportKeyword,g=e.isIdentifier(i.expression)&&i.expression.text==="require"&&!yr(e,n??(n=ds(e,t)),t,i.expression);(l||g)&&o(i,g?"require":"dynamic-import",qe(e,i.arguments[0]))}e.forEachChild(i,s)},"visit");return s(t),r}a(ze,"extractSemanticDependencies");function Ii(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=qe(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}}a(Ii,"staticAccessPath");function vi(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}a(vi,"runtimeIdentifierReference");function ls(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}}a(ls,"bestForbiddenMatch");function Ye(e,t,n){if(n.length===0)return[];let r=new Set(n),o=ds(e,t),s=new Map,i=new Set;for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations)e.isIdentifier(f.name)&&i.add(f.name.text);let l=a(p=>{let f=Ii(e,p);if(!f)return;let u=mr(o,f.root),y=u?s.get(u):void 0;return y?[...y,...f.segments.slice(1)]:yr(e,o,t,f.root)||i.has(f.root.text)?void 0:f.segments},"resolvePath");for(let p of t.statements)if(e.isVariableStatement(p))for(let f of p.declarationList.declarations){if(!f.initializer||!e.isIdentifier(f.name))continue;let u=l(f.initializer),y=mr(o,f.name);!u||!y||s.set(y,u)}let c=[],g=new Set,m=a((p,f)=>{let u=cs(t,f),y=`${p}:${f.getStart(t)}`;g.has(y)||(g.add(y),c.push({name:p,line:u,node:f}))},"flag"),h=a(p=>{let f=p.parent&&(e.isPropertyAccessExpression(p.parent)||e.isElementAccessExpression(p.parent))&&p.parent.expression===p;if((e.isPropertyAccessExpression(p)||e.isElementAccessExpression(p))&&!f){let u=l(p),y=u?ls(r,u):void 0;y&&m(y,p)}else e.isIdentifier(p)&&r.has(p.text)&&vi(e,p)&&!yr(e,o,t,p)&&m(p.text,p);if(e.isVariableDeclaration(p)&&e.isObjectBindingPattern(p.name)&&p.initializer){let u=l(p.initializer);if(u)for(let y of p.name.elements){if(!e.isIdentifier(y.name))continue;let E=y.propertyName?qe(e,y.propertyName)??y.propertyName.text:y.name.text,b=ls(r,[...u,E]);b&&m(b,p.initializer)}}e.forEachChild(p,h)},"visit");return h(t),c}a(Ye,"collectForbiddenCapabilityUses");function hr(e,t,n){let r=[];for(let o of n?.dependencies??ze(e,t)){if(o.typeOnly||!o.specifier)continue;let s=mt(o.specifier);s&&r.push({capability:s,symbol:o.specifier,line:o.line,source:"import-based"})}for(let o of n?.ambientUses??Ye(e,t,gr)){let s=Rn(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))}a(hr,"collectCapabilityUses");var Rr={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."},Ar=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 kr(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}a(kr,"resolveIntentLayer");function we(e){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(e)}a(we,"looksLikeArkIntent");function ht(e){if(!e.publishCall)return[];let t=[];return(e.rawIntentName!==void 0&&we(e.rawIntentName)||e.objectHasIntent)&&t.push({ruleId:"RAW_EVENT_PUBLISH",message:Rr.RAW_EVENT_PUBLISH}),e.arkPublishCandidate&&!e.hasSource&&t.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Rr.PUBLISH_MISSING_SOURCE}),t}a(ht,"classifyPublishFacts");function U(e,t,n){return{ruleId:e,code:e,message:t,...n}}a(U,"violation");function Xe(e,t){return e.slice(0,t).split(`
|
|
22
|
+
`).length}a(Xe,"lineOf");function Ei(e){let t=[],n=/['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g,r;for(;(r=n.exec(e))!==null;)t.push({value:r[1],index:r.index});return t}a(Ei,"extractQuotedStrings");function bi(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]),i=o[0],l=r.kind==="import"&&/\bimport\s+type\b/.test(i)||r.kind==="export"&&/\bexport\s+type\b/.test(i);t.push({value:o[1],index:s,kind:r.kind,typeOnly:l})}}return t.sort((r,o)=>r.index-o.index)}a(bi,"extractModuleSpecifiers");function Si(e,t){let n=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),r=[],o=a(s=>{e.isStringLiteralLike(s)&&r.push({value:s.text,index:s.getStart(n)}),e.forEachChild(s,o)},"visit");return o(n),r}a(Si,"extractQuotedStringsAst");function Ci(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))}a(Ci,"hasInfrastructureToken");function wi(e){let t=e.toLowerCase();return["sequelize","prisma","typeorm","mongoose","knex"].some(n=>t===n||t.startsWith(`${n}/`))}a(wi,"isKnownInfrastructurePackage");function xi(e){let t=e.toLowerCase();return["adapter","infra","persistence","repository","repositories","integration","database"].some(n=>t.includes(n))}a(xi,"layerHasInfrastructureRole");function At(e,t){return t&&e.isStringLiteralLike(t)?t.text:void 0}a(At,"tsStringLiteralText");function Oi(e,t){if(t&&(e.isIdentifier(t)||e.isStringLiteralLike(t)))return t.text}a(Oi,"tsPropertyName");function ps(e,t,n){if(!(!t||!e.isObjectLiteralExpression(t)))return t.properties.find(r=>!e.isPropertyAssignment(r)&&!e.isShorthandPropertyAssignment(r)?!1:Oi(e,r.name)===n)}a(ps,"tsObjectProperty");function kt(e,t,n){return ps(e,t,n)!==void 0}a(kt,"tsObjectHasProperty");function Rt(e,t,n){let r=ps(e,t,n);return r&&e.isPropertyAssignment(r)?r.initializer:void 0}a(Rt,"tsObjectPropertyValue");function Pi(e,t){let n=Rt(e,t,"metadata");return kt(e,n,"source")}a(Pi,"tsObjectHasMetadataSource");function us(e,t){return t?e.isIdentifier(t)?/^[A-Z]/.test(t.text):e.isPropertyAccessExpression(t)?us(e,t.name):!1:!1}a(us,"tsLooksLikeIntentCreatorExpression");function _i(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"}a(_i,"tsIsPublishCall");function Ni(e,t){if(!e.isCallExpression(t))return!1;let n=t.arguments[0],r=At(e,n);return r!==void 0&&we(r)||kt(e,n,"intent")||us(e,n)}a(Ni,"tsIsArkPublishCandidate");function Ti(e,t){if(!e.isCallExpression(t))return!1;let[n,r,o]=t.arguments;return Pi(e,n)||kt(e,r,"source")||kt(e,o,"source")}a(Ti,"tsPublishHasSource");function Di(e,t){if(!e.isCallExpression(t))return;let[n,r,o]=t.arguments,s=Rt(e,n,"metadata");return At(e,Rt(e,s,"source"))??At(e,Rt(e,r,"source"))??At(e,Rt(e,o,"source"))}a(Di,"tsPublishSourceLiteral");function Li(e,t,n,r){let o=e.createSourceFile("generated.ts",t,e.ScriptTarget.Latest,!0),s=n,i=s?.filePath,l=s?.layer,c=[],g=a(h=>o.getLineAndCharacterOfPosition(h.getStart(o)).line+1,"lineForNode"),m=a(h=>{if(_i(e,h)){let p=h.arguments[0],f=At(e,p);for(let y of ht({publishCall:!0,rawIntentName:f,objectHasIntent:kt(e,p,"intent"),arkPublishCandidate:Ni(e,h),hasSource:Ti(e,h)}))c.push(U(y.ruleId,y.message,{line:g(h),filePath:i}));let u=Di(e,h);if(r&&l&&u&&we(u)){let y=r.resolveLayer(u);y&&y!==l&&c.push(U("PUBLISH_SOURCE_LAYER_MISMATCH",`Publish source "${u}" resolves to ${y}, but the target file is classified as ${l}.`,{line:g(h),filePath:i,target:u,fromLayer:l,toLayer:y}))}}e.forEachChild(h,m)},"visit");return m(o),c}a(Li,"analyzePublishAst");function fs(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,i){let l=[],c=i,g=c?.filePath,m=c?.layer,h=e.typescript,p=h?h.createSourceFile(g??"generated.ts",s,h.ScriptTarget.Latest,!0):void 0,f=p?ze(e.typescript,p):void 0,u=f?f.filter(A=>A.specifier!==void 0).map(A=>({value:A.specifier,index:A.node.getStart(p),kind:A.kind,typeOnly:A.typeOnly})):bi(s),y=e.typescript?Si(e.typescript,s):Ei(s);if(e.typescript&&!e.allowNonLiteralDynamicImport?.(g))for(let A of f?.filter(({unresolved:v})=>v)??[]){let v=A.kind==="require";l.push(U(v?"DYNAMIC_REQUIRE_NOT_ALLOWLISTED":"DYNAMIC_IMPORT_NOT_ALLOWLISTED",`Non-literal ${v?"require call":"dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,{line:A.line,filePath:g}))}let E=m!==void 0&&(r.has(m)||xi(m)),b=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 v=A.exec(s);A.lastIndex=0,v&&l.push(U("FORBIDDEN_PATTERN",`Forbidden pattern matched: ${A}`,{line:v.index===void 0?void 0:Xe(s,v.index),filePath:g,suggestion:"Remove infrastructure imports from domain/application layers."+b}))}else s.includes(A)&&l.push(U("FORBIDDEN_SUBSTRING",`Forbidden substring: ${A}`,{line:Xe(s,s.indexOf(A)),filePath:g}));for(let A of u){let v=e.resolveImportTarget?.(A.value,g)??(e.resolveImportLayer?{layer:e.resolveImportLayer(A.value,g)}:void 0),P=typeof g=="string"?e.resolveImportTarget?.(g)??(e.resolveImportLayer?{layer:m,relPath:void 0}:void 0):void 0,j=v?.layer;if(j&&m){let k=ue(e.architectureProfile?.rules,m,j,{fromPath:P?.relPath,toPath:v?.relPath,layers:e.architectureLayers});if(k){if(A.typeOnly&&!k.peerIsolation)continue;let _=!!k.peerIsolation;l.push(U("LAYER_IMPORT_VIOLATION",k.message??(_?`Layer "${m}" must not import across slices into "${j}".`:`Layer "${m}" must not import "${j}".`),{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,fromLayer:m,toLayer:j,suggestion:_?"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:_,...A.typeOnly?{typeOnly:!0}:{}}}));continue}continue}E||A.typeOnly||!Ci(A.value)&&!wi(A.value)||l.push(U("FORBIDDEN_IMPORT",`Forbidden ${A.kind} target: "${A.value}".`,{line:Xe(s,A.index),source:A.value,target:A.value,filePath:g,suggestion:"Route infrastructure access through an allowed adapter or port boundary."+b,details:{importKind:A.kind}}))}if(e.policies)for(let A of e.policies){let v=A.check({source:s,context:i});if(v!==!0)if(Array.isArray(v))for(let P of v)l.push(U("POLICY_VIOLATION",P.message,{filePath:g,suggestion:`Fix violation of policy "${A.name}".`}));else v===!1?l.push(U("POLICY_VIOLATION",`Policy ${A.name} failed on generated code`)):l.push(U("POLICY_VIOLATION",v.message))}if(o&&t.size>0)for(let A of y)we(A.value)&&!t.has(A.value)&&l.push(U("UNKNOWN_INTENT",`Unknown intent reference: "${A.value}"`,{line:Xe(s,A.index),filePath:g,target:A.value,suggestion:`Register intent "${A.value}" via defineIntent() or remove the reference.`}));if(e.architectureProfile&&m)for(let A of y){if(!we(A.value))continue;let v=e.architectureProfile.resolveLayer(A.value);if(!v)continue;let P=ue(e.architectureProfile.rules,m,v);P&&l.push(U("LAYER_REFERENCE_VIOLATION",P.message??`Layer "${m}" must not reference "${v}" through "${A.value}".`,{line:Xe(s,A.index),filePath:g,target:A.value,fromLayer:m,toLayer:v,suggestion:"Route the dependency through an allowed intent, port, or event.",details:{rule:P}}))}if(e.extensions)for(let A of e.extensions)try{let v=A.analyze(s,i);l.push(...v)}catch(v){l.push(U("EXTENSION_ERROR",`Extension "${A.name}" failed: ${v instanceof Error?v.message:String(v)}`))}if(e.typescript&&p&&m&&e.forbiddenGlobals?.[m]?.length)try{let A=e.forbiddenGlobals[m];l.push(...Ye(e.typescript,p,A).map(v=>U("FORBIDDEN_GLOBAL",`${m} must not use the ambient global "${v.name}".`,{line:v.line,filePath:g,target:v.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 v of f??[]){if(v.typeOnly||!v.specifier)continue;let P=Ie(v.specifier,A);P&&l.push(U("FORBIDDEN_GLOBAL",`${m} must not use module "${v.specifier}" because it is the import form of forbidden global "${P}".`,{line:v.line,filePath:g,source:v.specifier,target:v.specifier,fromLayer:m,details:{importKind:v.kind,forbiddenGlobal:P},suggestion:"Inject the capability through a port instead of importing the ambient global module form."}))}}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript&&p&&m&&e.capabilityWalls?.[m]?.length)try{let A=new Set(e.capabilityWalls[m]),v=e.forbiddenGlobals?.[m]??[];for(let P of hr(e.typescript,p))A.has(P.capability)&&(P.source==="ambient-global"&&yt(P.symbol,v)||P.source==="import-based"&&Ie(P.symbol,v)||l.push(U("CAPABILITY_VIOLATION",P.source==="import-based"?`${m} denies the ${P.capability} capability; found import of "${P.symbol}".`:`${m} denies the ${P.capability} capability; found ambient "${P.symbol}".`,{line:P.line,filePath:g,target:P.symbol,capability:P.capability,fromLayer:m,suggestion:"Define a small port (ClockPort, HttpPort, StoragePort) and bind the implementation in an adapter layer."})))}catch(A){l.push(U("AST_ANALYZER_ERROR",`TypeScript AST analyzer failed: ${A instanceof Error?A.message:String(A)}`))}if(e.typescript)try{l.push(...Li(e.typescript,s,i,e.architectureProfile))}catch(A){l.push(U("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}}}}a(fs,"createAICodeGate");function B(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")}`}a(B,"deterministicHash");function F(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(F).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${F(t[n])}`).join(",")}}`}a(F,"stableSerialize");var xe="1.2";var gs=["network","filesystem","clock","randomness","environment","process","persistence"];function V(e,t){let n=F(e),r=F(t);return n<r?-1:n>r?1:0}a(V,"compareCanonical");function W(e){return[...new Set(e)].sort((t,n)=>t<n?-1:t>n?1:0)}a(W,"sortedUnique");function It(e){let t={schemaVersion:"1.2",include:W(e.include??[]),exclude:W(e.exclude??[]),excludeGenerated:e.excludeGenerated!==!1,dynamicImportAllowlist:W(e.dynamicImportAllowlist??[]),layers:e.layers.map(n=>({name:n.name,patterns:W(n.patterns??[]),exclude:W(n.exclude??[]),forbiddenGlobals:W(n.forbiddenGlobals??[]),intentPrefixes:W(n.intentPrefixes??[]),capabilityDeny:W(n.capabilities?.deny??[]),pure:n.pure===!0})).sort(V),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:W(e.arkRun.compositionRoots),managedLayers:W(e.arkRun.managedLayers),requireDeclarations:e.arkRun.requireDeclarations===!0}}:{}};return B(F(t))}a(It,"resolvedFactsEvidenceRequirementsHash");function Fi(e){let t=e.completenessReasons.map(k=>({code:k.code,message:k.message,...k.file?{file:k.file}:{}})).sort(V),n=e.files.map(k=>({...k,typeOnlyExportNames:W(k.typeOnlyExportNames)})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),r=e.dependencies.map(k=>({...k,...k.namedBindings?{namedBindings:W(k.namedBindings)}:{}})).sort(V),o=e.capabilityUses.map(k=>({...k})).sort(V),s=e.ambientUses.map(k=>({...k})).sort(V),i=e.publishCalls.map(k=>({...k})).sort(V),l=e.intentReferences.map(k=>({...k})).sort(V),c=e.safetyUses.map(k=>({...k})).sort(V),g=(e.classShapes??[]).map(k=>({...k,mutatingMethods:[...k.mutatingMethods??[]].map(_=>({..._}))})).sort(V),m=(e.arkRunKernelCalls??[]).map(k=>({...k})).sort(V),h=(e.arkRunManagedNews??[]).map(k=>({...k})).sort(V),p=(e.arkRunCompositionRootHits??[]).map(k=>({...k})).sort(V),f=(e.arkRunDeclarations??[]).map(k=>({...k,uses:W(k.uses),reactsTo:W(k.reactsTo),raises:W(k.raises),sends:W(k.sends)})).sort(V),u=(e.arkOrderPlaneCalls??[]).map(k=>({...k})).sort(V),y=(e.arkOrderGenericUpdates??[]).map(k=>({...k})).sort(V),E=(e.arkOrderRootHits??[]).map(k=>({...k})).sort(V),b=(e.arkOrderXiFieldWrites??[]).map(k=>({...k})).sort(V),A=(e.arkOrderIngestWritesXi??[]).map(k=>({...k})).sort(V),v=(e.arkOrderReleaseKeyCounts??[]).map(k=>({...k})).sort(V),P=e.files.map(({path:k,contentHash:_})=>({path:k,contentHash:_})).sort((k,_)=>k.path<_.path?-1:k.path>_.path?1:0),j=B(F(P));return{schemaVersion:"1.2",completeness:e.completeness,completenessReasons:t,resolverIdentity:e.resolverIdentity,compilerIdentity:e.compilerIdentity,compilerOptionsHash:e.compilerOptionsHash,tsconfigHash:e.tsconfigHash,candidateTreeHash:j,evidenceRequirementsHash:e.evidenceRequirementsHash,...e.projectPackageName?{projectPackageName:e.projectPackageName}:{},files:n,dependencies:r,capabilityUses:o,ambientUses:s,publishCalls:i,intentReferences:l,safetyUses:c,classShapes:g,arkRunKernelCalls:m,arkRunManagedNews:h,arkRunCompositionRootHits:p,arkRunDeclarations:f,arkOrderPlaneCalls:u,arkOrderGenericUpdates:y,arkOrderRootHits:E,arkOrderXiFieldWrites:b,arkOrderIngestWritesXi:A,arkOrderReleaseKeyCounts:v}}a(Fi,"canonicalResolvedFactsInput");function ms(e){let t=Fi(e);return{...t,factsHash:B(F(t))}}a(ms,"createCanonicalResolvedCandidateFacts");function Ir(e){return ms(hs(D(e,"$"),!1))}a(Ir,"createResolvedCandidateFacts");function D(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object.`);return e}a(D,"asRecord");function $(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"}.`)}a($,"assertOnlyKeys");function T(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}a(T,"requiredText");function ge(e,t,n){if(e[t]!==void 0)return T(e,t,n)}a(ge,"optionalText");function M(e,t,n){let r=T(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 i=s.join("/");if(!i||i!==r)throw new Error(`${n}.${t} must be a canonical project-relative path.`);return i}a(M,"requiredProjectPath");function K(e,t,n){if(typeof e[t]!="boolean")throw new Error(`${n}.${t} must be a boolean.`);return e[t]}a(K,"requiredBoolean");function ys(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)}a(ys,"requiredInteger");function Y(e,t,n){let r=ys(e,t,n);if(r===0)throw new Error(`${n}.${t} must be a positive integer.`);return r}a(Y,"requiredPositiveInteger");function H(e,t,n){let r=e[t];if(!Array.isArray(r))throw new Error(`${n}.${t} must be an array.`);return r}a(H,"requiredArray");function me(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}a(me,"enumValue");function Ze(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]}a(Ze,"parseStringArray");function $i(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)}}a($i,"assertUnique");function hs(e,t){$(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=me(e,"schemaVersion",["1.0","1.1","1.2"],"$"),r=me(e,"completeness",["complete","partial","unavailable"],"$"),o=H(e,"completenessReasons","$").map((S,C)=>{let R=`$.completenessReasons[${C}]`,d=D(S,R);$(d,["code","message","file"],R);let N=d.file===void 0?void 0:M(d,"file",R);return{code:T(d,"code",R),message:T(d,"message",R),...N?{file:N}:{}}});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=H(e,"files","$").map((S,C)=>{let R=`$.files[${C}]`,d=D(S,R);return $(d,["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],R),{path:M(d,"path",R),contentHash:T(d,"contentHash",R),parseStatus:me(d,"parseStatus",["parsed","invalid"],R),parseDiagnosticCount:ys(d,"parseDiagnosticCount",R),exportsOnlyTypes:K(d,"exportsOnlyTypes",R),typeOnlyExportNames:Ze(d.typeOnlyExportNames,`${R}.typeOnlyExportNames`),hasTopLevelSideEffects:K(d,"hasTopLevelSideEffects",R)}}),i=H(e,"dependencies","$").map((S,C)=>{let R=`$.dependencies[${C}]`,d=D(S,R);$(d,["from","specifier","kind","typeOnly","line","resolution","target","namedBindings","targetTypeOnlyExports","sourcePureTypeModule","namedBindingsTypeOnly","portProofEligible"],R);let N=ge(d,"specifier",R),L=ge(d,"target",R),te=me(d,"resolution",["resolved-project","resolved-external","unresolved","dynamic"],R);if(te==="resolved-project"&&!L)throw new Error(`${R}.target is required for resolved-project dependencies.`);if(te!=="resolved-project"&&L)throw new Error(`${R}.target is only allowed for resolved-project dependencies.`);if(te!=="dynamic"&&!N)throw new Error(`${R}.specifier is required unless resolution is dynamic.`);return{from:M(d,"from",R),...N?{specifier:N}:{},kind:me(d,"kind",["import","export","dynamic-import","require"],R),typeOnly:K(d,"typeOnly",R),line:Y(d,"line",R),resolution:te,...L?{target:M(d,"target",R)}:{},...d.namedBindings!==void 0?{namedBindings:Ze(d.namedBindings,`${R}.namedBindings`)}:{},...d.targetTypeOnlyExports!==void 0?{targetTypeOnlyExports:K(d,"targetTypeOnlyExports",R)}:{},...d.sourcePureTypeModule!==void 0?{sourcePureTypeModule:K(d,"sourcePureTypeModule",R)}:{},...d.namedBindingsTypeOnly!==void 0?{namedBindingsTypeOnly:K(d,"namedBindingsTypeOnly",R)}:{},...d.portProofEligible!==void 0?{portProofEligible:K(d,"portProofEligible",R)}:{}}}),l=H(e,"capabilityUses","$").map((S,C)=>{let R=`$.capabilityUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol","capability","source"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R),capability:me(d,"capability",gs,R),source:me(d,"source",["ambient-global","import-based"],R)}}),c=H(e,"ambientUses","$").map((S,C)=>{let R=`$.ambientUses[${C}]`,d=D(S,R);return $(d,["file","line","symbol"],R),{file:M(d,"file",R),line:Y(d,"line",R),symbol:T(d,"symbol",R)}}),g=H(e,"publishCalls","$").map((S,C)=>{let R=`$.publishCalls[${C}]`,d=D(S,R);$(d,["file","line","rawIntentName","objectHasIntent","arkPublishCandidate","hasSource","sourceIntent"],R);let N=ge(d,"rawIntentName",R),L=ge(d,"sourceIntent",R);return{file:M(d,"file",R),line:Y(d,"line",R),...N?{rawIntentName:N}:{},objectHasIntent:K(d,"objectHasIntent",R),arkPublishCandidate:K(d,"arkPublishCandidate",R),hasSource:K(d,"hasSource",R),...L?{sourceIntent:L}:{}}}),m=H(e,"intentReferences","$").map((S,C)=>{let R=`$.intentReferences[${C}]`,d=D(S,R);return $(d,["file","line","intent"],R),{file:M(d,"file",R),line:Y(d,"line",R),intent:T(d,"intent",R)}}),h=H(e,"safetyUses","$").map((S,C)=>{let R=`$.safetyUses[${C}]`,d=D(S,R);$(d,["file","line","kind","symbol"],R);let N=ge(d,"symbol",R),L=me(d,"kind",["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"],R);if(L==="in-memory-store"&&!N)throw new Error(`${R}.symbol is required for in-memory-store facts.`);if(L!=="in-memory-store"&&N)throw new Error(`${R}.symbol is only allowed for in-memory-store facts.`);return{file:M(d,"file",R),line:Y(d,"line",R),kind:L,...N?{symbol:N}:{}}});$i(s,S=>S.path,"$.files");let p=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 i)if(!p.has(S.from))throw new Error(`$.dependencies references missing source file ${S.from}.`);let u=(e.arkRunKernelCalls===void 0?[]:H(e,"arkRunKernelCalls","$")).map((S,C)=>{let R=`$.arkRunKernelCalls[${C}]`,d=D(S,R);$(d,["file","line","kind","callee","viaImport","receiver","nameLiteral"],R);let N=ge(d,"receiver",R),L=ge(d,"nameLiteral",R);return{file:M(d,"file",R),line:Y(d,"line",R),kind:me(d,"kind",["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"],R),callee:T(d,"callee",R),viaImport:K(d,"viaImport",R),...N?{receiver:N}:{},...L?{nameLiteral:L}:{}}}),E=(e.arkRunManagedNews===void 0?[]:H(e,"arkRunManagedNews","$")).map((S,C)=>{let R=`$.arkRunManagedNews[${C}]`,d=D(S,R);$(d,["file","line","typeName","importedFrom"],R);let N=ge(d,"importedFrom",R);return{file:M(d,"file",R),line:Y(d,"line",R),typeName:T(d,"typeName",R),...N?{importedFrom:N}:{}}}),A=(e.arkRunCompositionRootHits===void 0?[]:H(e,"arkRunCompositionRootHits","$")).map((S,C)=>{let R=`$.arkRunCompositionRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasKernelFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasKernelFactory:K(d,"hasKernelFactory",R)}}),v=e.arkRunDeclarations===void 0?[]:H(e,"arkRunDeclarations","$"),j=(e.arkOrderPlaneCalls===void 0?[]:H(e,"arkOrderPlaneCalls","$")).map((S,C)=>{let R=`$.arkOrderPlaneCalls[${C}]`,d=D(S,R);return $(d,["file","line","callee"],R),{file:M(d,"file",R),line:Y(d,"line",R),callee:T(d,"callee",R)}}),_=(e.arkOrderGenericUpdates===void 0?[]:H(e,"arkOrderGenericUpdates","$")).map((S,C)=>{let R=`$.arkOrderGenericUpdates[${C}]`,d=D(S,R);return $(d,["file","line","method"],R),{file:M(d,"file",R),line:Y(d,"line",R),method:T(d,"method",R)}}),de=(e.arkOrderRootHits===void 0?[]:H(e,"arkOrderRootHits","$")).map((S,C)=>{let R=`$.arkOrderRootHits[${C}]`,d=D(S,R);return $(d,["file","matchedRoot","hasPlaneFactory"],R),{file:M(d,"file",R),matchedRoot:T(d,"matchedRoot",R),hasPlaneFactory:K(d,"hasPlaneFactory",R)}}),Ne=(e.arkOrderXiFieldWrites===void 0?[]:H(e,"arkOrderXiFieldWrites","$")).map((S,C)=>{let R=`$.arkOrderXiFieldWrites[${C}]`,d=D(S,R);return $(d,["file","line","key"],R),{file:M(d,"file",R),line:Y(d,"line",R),key:T(d,"key",R)}}),Wt=(e.arkOrderIngestWritesXi===void 0?[]:H(e,"arkOrderIngestWritesXi","$")).map((S,C)=>{let R=`$.arkOrderIngestWritesXi[${C}]`,d=D(S,R);return $(d,["file","line"],R),{file:M(d,"file",R),line:Y(d,"line",R)}}),zn=(e.arkOrderReleaseKeyCounts===void 0?[]:H(e,"arkOrderReleaseKeyCounts","$")).map((S,C)=>{let R=`$.arkOrderReleaseKeyCounts[${C}]`,d=D(S,R);return $(d,["file","line","keyCount"],R),{file:M(d,"file",R),line:Y(d,"line",R),keyCount:Y(d,"keyCount",R)}}),at=v.map((S,C)=>{let R=`$.arkRunDeclarations[${C}]`,d=D(S,R);return $(d,["file","line","uses","reactsTo","raises","sends"],R),{file:M(d,"file",R),line:Y(d,"line",R),uses:Ze(d.uses,`${R}.uses`),reactsTo:Ze(d.reactsTo,`${R}.reactsTo`),raises:Ze(d.raises,`${R}.raises`),sends:Ze(d.sends,`${R}.sends`)}});for(let[S,C]of[["$.capabilityUses",l],["$.ambientUses",c],["$.publishCalls",g],["$.intentReferences",m],["$.safetyUses",h],["$.arkRunKernelCalls",u],["$.arkRunManagedNews",E],["$.arkRunCompositionRootHits",A],["$.arkRunDeclarations",at],["$.arkOrderPlaneCalls",j],["$.arkOrderGenericUpdates",_],["$.arkOrderRootHits",de],["$.arkOrderXiFieldWrites",Ne],["$.arkOrderIngestWritesXi",Wt],["$.arkOrderReleaseKeyCounts",zn]])for(let R of C)if(!p.has(R.file))throw new Error(`${S} references missing file ${R.file}.`);let Ee=ge(e,"projectPackageName","$"),Yn=(e.classShapes===void 0?[]:H(e,"classShapes","$")).map((S,C)=>{let R=`$.classShapes[${C}]`,d=D(S,R);$(d,["file","className","exported","hasPublicMutableFields","hasPublicSetters","hasPublicConstructor","hasStaticFactory","mutatingMethods","dataOnly"],R);let N=H(d,"mutatingMethods",R).map((L,te)=>{let zt=`${R}.mutatingMethods[${te}]`,Xn=D(L,zt);return $(Xn,["name","referencesGuardOrPublish"],zt),{name:T(Xn,"name",zt),referencesGuardOrPublish:K(Xn,"referencesGuardOrPublish",zt)}});return{file:M(d,"file",R),className:T(d,"className",R),exported:K(d,"exported",R),hasPublicMutableFields:K(d,"hasPublicMutableFields",R),hasPublicSetters:K(d,"hasPublicSetters",R),hasPublicConstructor:K(d,"hasPublicConstructor",R),hasStaticFactory:K(d,"hasStaticFactory",R),mutatingMethods:N,...d.dataOnly===void 0?{}:{dataOnly:K(d,"dataOnly",R)}}});return{schemaVersion:n,completeness:r,completenessReasons:o,resolverIdentity:T(e,"resolverIdentity","$"),compilerIdentity:T(e,"compilerIdentity","$"),compilerOptionsHash:T(e,"compilerOptionsHash","$"),tsconfigHash:T(e,"tsconfigHash","$"),evidenceRequirementsHash:T(e,"evidenceRequirementsHash","$"),...Ee?{projectPackageName:Ee}:{},files:s,dependencies:i,capabilityUses:l,ambientUses:c,publishCalls:g,intentReferences:m,safetyUses:h,classShapes:Yn,arkRunKernelCalls:u,arkRunManagedNews:E,arkRunCompositionRootHits:A,arkRunDeclarations:at,arkOrderPlaneCalls:j,arkOrderGenericUpdates:_,arkOrderRootHits:de,arkOrderXiFieldWrites:Ne,arkOrderIngestWritesXi:Wt,arkOrderReleaseKeyCounts:zn}}a(hs,"parseResolvedFactsInput");function ve(e){let t=D(e,"$"),n=T(t,"factsHash","$"),r=T(t,"candidateTreeHash","$"),o=ms(hs(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}a(ve,"loadResolvedCandidateFacts");var Mi=["network","filesystem","clock","randomness","environment","process","persistence"],x={type:"string",minLength:1},X={type:"integer",minimum:1},G={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:x,message:x,file:G}}},resolverIdentity:x,compilerIdentity:x,compilerOptionsHash:x,tsconfigHash:x,candidateTreeHash:x,evidenceRequirementsHash:x,projectPackageName:x,files:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["path","contentHash","parseStatus","parseDiagnosticCount","exportsOnlyTypes","typeOnlyExportNames","hasTopLevelSideEffects"],properties:{path:G,contentHash:x,parseStatus:{enum:["parsed","invalid"]},parseDiagnosticCount:{type:"integer",minimum:0},exportsOnlyTypes:{type:"boolean"},typeOnlyExportNames:{type:"array",items:x},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:G,specifier:x,kind:{enum:["import","export","dynamic-import","require"]},typeOnly:{type:"boolean"},line:X,resolution:{enum:["resolved-project","resolved-external","unresolved","dynamic"]},target:G,namedBindings:{type:"array",items:x},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:G,line:X,symbol:x,capability:{enum:Mi},source:{enum:["ambient-global","import-based"]}}}},ambientUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","symbol"],properties:{file:G,line:X,symbol:x}}},publishCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","objectHasIntent","arkPublishCandidate","hasSource"],properties:{file:G,line:X,rawIntentName:x,objectHasIntent:{type:"boolean"},arkPublishCandidate:{type:"boolean"},hasSource:{type:"boolean"},sourceIntent:x}}},intentReferences:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","intent"],properties:{file:G,line:X,intent:x}}},safetyUses:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind"],properties:{file:G,line:X,kind:{enum:["ts-suppression","any-cast","dynamic-import","dynamic-require","in-memory-store"]},symbol:x},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:G,className:x,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:x,referencesGuardOrPublish:{type:"boolean"}}}}}}},arkRunKernelCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","kind","callee","viaImport"],properties:{file:G,line:X,kind:{enum:["factory","publisher","publish","raise","send","subscribe","register-handler","resolve","resolve-singleton"]},callee:x,viaImport:{type:"boolean"},receiver:x,nameLiteral:x}}},arkRunManagedNews:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","typeName"],properties:{file:G,line:X,typeName:x,importedFrom:x}}},arkRunCompositionRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasKernelFactory"],properties:{file:G,matchedRoot:x,hasKernelFactory:{type:"boolean"}}}},arkRunDeclarations:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","uses","reactsTo","raises","sends"],properties:{file:G,line:X,uses:{type:"array",items:x},reactsTo:{type:"array",items:x},raises:{type:"array",items:x},sends:{type:"array",items:x}}}},arkOrderPlaneCalls:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","callee"],properties:{file:G,line:X,callee:x}}},arkOrderGenericUpdates:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","method"],properties:{file:G,line:X,method:x}}},arkOrderRootHits:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","matchedRoot","hasPlaneFactory"],properties:{file:G,matchedRoot:x,hasPlaneFactory:{type:"boolean"}}}},arkOrderXiFieldWrites:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","key"],properties:{file:G,line:X,key:x}}},arkOrderIngestWritesXi:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line"],properties:{file:G,line:X}}},arkOrderReleaseKeyCounts:{type:"array",items:{type:"object",additionalProperties:!1,required:["file","line","keyCount"],properties:{file:G,line:X,keyCount:{type:"integer",minimum:1}}}},factsHash:x},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 Er="1.0";function Q(e){return`${e.from}->${e.to}`}a(Q,"dependencyKey");function vt(e,t,n,r="dependency"){return{id:`${e}:${r}:${Q(t)}`,classification:e,subject:"dependency",from:t.from,to:t.to,message:n,...e==="missing"?{nextAction:`Add the planned dependency ${Q(t)} to the candidate, then preflight again.`}:e==="contradictory"?{nextAction:`Replace the reverse dependency with ${Q(t)}, then preflight again.`}:e==="unplanned"?{nextAction:r==="dependency-removed"?`Restore the removed dependency ${Q(t)} in the candidate, then preflight again.`:`Remove the unplanned dependency ${Q(t)} from the candidate, then preflight again.`}:{}}}a(vt,"dependencyFinding");function Je(e){let t=[],n=new Map(e.changeMap.map.files.map(p=>[p.path,p])),r=new Map(e.changes.map(p=>[p.path,p])),o=new Map(e.changeMap.map.dependencies.map(p=>[Q(p),p])),s=new Map(e.baseDependencies.map(p=>[Q(p),p])),i=new Map(e.candidateDependencies.map(p=>[Q(p),p]));for(let p of[...n.values()].sort((f,u)=>f.path.localeCompare(u.path))){let f=r.get(p.path);f?f.operation!==p.operation?t.push({id:`contradictory:file:${p.path}`,classification:"contradictory",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} was planned as ${p.operation} but the actual operation is ${f.operation}.`,nextAction:`Change ${p.path} to the planned ${p.operation} operation, then preflight again.`}):t.push({id:`satisfied:file:${p.path}`,classification:"satisfied",subject:"file",path:p.path,expectedOperation:p.operation,actualOperation:f.operation,message:`${p.path} matches the planned ${p.operation} operation.`}):t.push({id:`missing:file:${p.path}`,classification:"missing",subject:"file",path:p.path,expectedOperation:p.operation,message:`${p.path} was planned as ${p.operation} but is absent from the actual change.`,nextAction:`${p.operation[0].toUpperCase()}${p.operation.slice(1)} ${p.path} in the complete change set, then preflight again.`})}for(let p of[...r.values()].sort((f,u)=>f.path.localeCompare(u.path)))n.has(p.path)||t.push({id:`unplanned:file:${p.path}`,classification:"unplanned",subject:"file",path:p.path,actualOperation:p.operation,message:`${p.path} has an unplanned ${p.operation} operation.`,nextAction:`Remove ${p.path} from the change set, then preflight again.`});let l=new Set;for(let p of[...o.values()].sort((f,u)=>Q(f).localeCompare(Q(u)))){if(i.has(Q(p))){t.push(vt("satisfied",p,`${p.from} -> ${p.to} exists in the candidate architecture.`));continue}let f={from:p.to,to:p.from};i.has(Q(f))?(l.add(Q(f)),t.push(vt("contradictory",p,`${p.from} -> ${p.to} was planned, but the candidate contains the reverse edge.`))):t.push(vt("missing",p,`${p.from} -> ${p.to} is absent from the candidate architecture.`))}let c=new Set([...n.keys(),...r.keys()]);for(let[p,f]of[...i].sort(([u],[y])=>u.localeCompare(y)))s.has(p)||o.has(p)||l.has(p)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("unplanned",f,`${f.from} -> ${f.to} was added without a matching planned dependency.`,"dependency-added"),actualOperation:"added"});let g=new Set(e.changeMap.map.files.filter(p=>p.operation==="delete").map(p=>p.path));for(let[p,f]of[...s].sort(([u],[y])=>u.localeCompare(y)))i.has(p)||g.has(f.from)||g.has(f.to)||!c.has(f.from)&&!c.has(f.to)||t.push({...vt("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((p,f)=>m[p.classification]-m[f.classification]||(p.subject===f.subject?0:p.subject==="file"?-1:1)||p.id.localeCompare(f.id));let h={satisfied:t.filter(p=>p.classification==="satisfied").length,missing:t.filter(p=>p.classification==="missing").length,contradictory:t.filter(p=>p.classification==="contradictory").length,unplanned:t.filter(p=>p.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}}a(Je,"analyzeArchitectureConvergence");var Rs="https://unpkg.com/arkgate/schemas/ark.arkrules.schema.json",Ki=["aggregate-private-state","always-valid-factory","domain-event-on-mutation","orchestration-only","thin-adapter","writes-via-aggregate","no-anemic-model","invariant-coverage"];var As={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Bu={$schema:"https://json-schema.org/draft/2020-12/schema",$id:Rs,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:Rs},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:[...Ki]},mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},appliesTo:As,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:As}}}};function Et(){return{schemaVersion:"1.0",byLayer:{},structure:[],invariants:[]}}a(Et,"emptyEffectiveArkRules");function br(e){return{...e,layers:e.layers.map(t=>{let{description:n,...r}=t;return r})}}a(br,"omitLayerDescriptions");function ks(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}))}}}a(ks,"effectiveContractPolicyPayload");function Is(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}.`}a(Is,"formatCoverageDiscards");function Hi(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}/`)})}a(Hi,"isUnderCoverageRoot");function Gi(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:describe|it|test|context)\\s*\\(\\s*['"\`][^'"\`]*${n}[^'"\`]*['"\`]`,"i").test(e)||e.includes(t)}a(Gi,"titleMatchesInvariant");function Ui(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}a(Ui,"symbolPresent");function vs(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,i=Is(s),l=Is(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",g=(e.coverageRoots??[]).filter(u=>typeof u=="string"&&u.length>0),m=g.length>0,h=g.join(", "),p=[],f=[];for(let u of t){let y=[],E=u.coverage?.test!==!1,b=u.coverage?.symbol,A,v;if(!r&&E){let _;for(let z of n){let de=e.fileContents[z];if(!(!de||!Gi(de,u.id))){if(!m||Hi(z,g)){A=z,v=m?!1:void 0;break}_??=z}}A===void 0&&_!==void 0&&(A=_,v=!0),A!==void 0&&y.push("test-title")}b&&Ui(e.fileContents,b)&&y.push("symbol");let j=(u.coverage?.test===!0||!!b||u.coverage===void 0)&&y.length>0||u.coverage?.test===!1&&!b?!0:y.length>0,k=r&&E&&y.length===0;if(p.push({invariantId:u.id,layer:u.provenance.layer,sourceFile:u.provenance.sourceFile,mode:u.mode,covered:j&&!k,evidence:y,partial:k,description:u.description,...A!==void 0?{testEvidenceFile:A}:{},...v!==void 0?{outsideDeclaredRoots:v}:{}}),v===!0&&A!==void 0&&f.push({ruleId:"INVARIANT_COVERAGE_OUTSIDE_ROOTS",message:`Invariant ${u.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:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:"warning",failsStrict:!1}),!j||k){let _=u.mode==="enforced"&&!k,z=r||n.length===0?"never-had-tests":"tests-disappeared";f.push({ruleId:"INVARIANT_UNCOVERED",message:(k?o?`Invariant ${u.id} coverage cannot be proven (${c}); reporting partial, not covered.`:`Invariant ${u.id} coverage cannot be proven (test globs missing or empty); reporting partial, not covered (never-had-tests).`:z==="tests-disappeared"?`Invariant ${u.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 ${u.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.`)+(k&&o?l:i),file:u.provenance.sourceFile,line:1,arkruleId:u.id,arkruleSource:u.provenance.sourceFile,fromLayer:u.provenance.layer,severity:_?"error":"warning",failsStrict:_,kind:z})}}return{coverage:p,violations:f,partial:p.some(u=>u.partial)}}a(vs,"evaluateInvariantCoverage");function Es(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."}}a(Es,"canPromoteInvariant");var wr="1.0";function O(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}})}a(O,"addFinding");function q(e){return[...new Set(e??[])].sort()}a(q,"sortedUnique");function ie(e,t,n,r,o){let s=q(n),i=q(r),l=new Set(s),c=new Set(i),g=i.filter(h=>!l.has(h)),m=s.filter(h=>!c.has(h));g.length===0&&m.length===0||(g.length>0&&O(e,{kind:"added",path:t,classification:o.added,message:o.addedMessage,before:s,after:i}),m.length>0&&O(e,{kind:"removed",path:t,classification:o.removed,message:o.removedMessage,before:s,after:i}))}a(ie,"compareStringSets");function bt(e,t,n,r,o,s,i){if(n===r)return;O(e,{kind:r?"enabled":"disabled",path:t,classification:r?o:o==="strengthening"?"weakening":"strengthening",message:r?s:i,before:n,after:r})}a(bt,"compareBoolean");function kn(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()}}a(kn,"keyed");function Vi(e,t,n){let r=kn(t,s=>s.name),o=kn(n,s=>s.name);(r.duplicates.length>0||o.duplicates.length>0)&&O(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 i=r.values.get(s),l=o.values.get(s),c=`$.layers[${s}]`;if(!i&&l){O(e,{kind:"layer-added",path:c,classification:"judgment-required",message:"A layer was added; verify overlap, ownership, and rule coverage.",after:l});continue}if(i&&!l){O(e,{kind:"layer-removed",path:c,classification:"weakening",message:"Removing a layer can leave its source paths ungoverned.",before:i});continue}if(!i||!l)continue;ie(e,`${c}.patterns`,i.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."}),ie(e,`${c}.exclude`,i.exclude,l.exclude,{added:"weakening",removed:"strengthening",addedMessage:"Additional paths are excluded from this layer.",removedMessage:"Fewer paths are excluded from this layer."});let g=An(i),m=An(l);ie(e,`${c}.forbiddenGlobals`,g.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."}),ie(e,`${c}.capabilities`,g.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(i.intentPrefixes).join("\0")!==q(l.intentPrefixes).join("\0")&&O(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(i.intentPrefixes),after:q(l.intentPrefixes)}),bt(e,`${c}.mayImportInfrastructure`,i.mayImportInfrastructure===!0,l.mayImportInfrastructure===!0,"weakening","The layer may now import infrastructure directly.","Direct infrastructure imports are no longer allowed for this layer."),bt(e,`${c}.optional`,i.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.")}}a(Vi,"compareLayers");function ji(e,t,n){let r=a(i=>`${i.from}->${i.to}`,"keyOf"),o=kn(t,r),s=kn(n,r);(o.duplicates.length>0||s.duplicates.length>0)&&O(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 i of[...new Set([...o.values.keys(),...s.values.keys()])].sort()){let l=o.values.get(i),c=s.values.get(i),g=`$.rules[${i}]`;if(!l&&c){c.allowed===!1&&O(e,{kind:"deny-added",path:g,classification:"strengthening",message:"A denied dependency edge was added.",after:c});continue}if(l&&!c){l.allowed===!1&&O(e,{kind:"deny-removed",path:g,classification:"weakening",message:"A denied dependency edge was removed.",before:l});continue}if(!l||!c)continue;l.allowed!==c.allowed&&O(e,{kind:c.allowed?"deny-disabled":"deny-enabled",path:`${g}.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 p=l.from===l.to&&c.from===c.to;O(e,{kind:h?"peer-isolation-enabled":"peer-isolation-disabled",path:`${g}.peerIsolation`,classification:p?h?"strengthening":"weakening":"judgment-required",message:p?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")&&O(e,{kind:"slice-folders-changed",path:`${g}.sliceFolders`,classification:"judgment-required",message:"Slice ownership folders changed and can reclassify existing dependencies.",before:q(l.sliceFolders),after:q(c.sliceFolders)}),!(!m&&!h)&&(Ss(e,`${g}.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."),Ss(e,`${g}.allowedCrossSlice`,"cross-slice-allowance",q((l.allowedCrossSlice??[]).map(bs)),q((c.allowedCrossSlice??[]).map(bs)),"Directed cross-slice edges are now allowed by declaration.","Directed cross-slice edges are no longer declared and deny again."))}}a(ji,"compareRules");function bs(e){return JSON.stringify([e.from,e.to])}a(bs,"crossSliceKey");function Ss(e,t,n,r,o,s,i){if(JSON.stringify(r)===JSON.stringify(o))return;let l=o.filter(m=>!r.includes(m)),c=r.filter(m=>!o.includes(m)),g=l.length>0&&c.length>0;O(e,{kind:g?`${n}-changed`:l.length>0?`${n}-added`:`${n}-removed`,path:t,classification:g?"judgment-required":l.length>0?"weakening":"strengthening",message:g?`${s} Entries were added and removed in the same change.`:l.length>0?s:i,before:r,after:o})}a(Ss,"compareDeclaredExceptions");function Bi(e,t,n){let r=t.safety??{},o=n.safety??{};for(let s of["maxTsSuppressions","maxAnyCasts"]){let i=r[s]??0,l=o[s]??0;i!==l&&O(e,{kind:l>i?"threshold-raised":"threshold-lowered",path:`$.safety.${s}`,classification:l>i?"weakening":"strengthening",message:l>i?"The safety threshold allows more violations.":"The safety threshold allows fewer violations.",before:i,after:l})}for(let s of["allowInMemory","allowDisabledPeerIsolation"])bt(e,`$.safety.${s}`,r[s]===!0,o[s]===!0,"weakening","A safety exception was enabled.","A safety exception was disabled.")}a(Bi,"compareSafety");function Sr(e){return e.mode==="enforced"?"enforced":"advisory"}a(Sr,"arkRunMode");function Cr(e){return e.mode==="enforced"?"enforced":"advisory"}a(Cr,"arkOrderMode");function Wi(e,t,n){let r=t.arkOrder,o=n.arkOrder,s="$.arkOrder";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkorder-added",path:s,classification:"strengthening",message:`ArkOrder extra was added (${Cr(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkorder-removed",path:s,classification:"weakening",message:"ArkOrder extra was removed.",before:r});return}if(!r||!o)return;let i=Cr(r),l=Cr(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(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:i,after:l})}ie(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."}),ie(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."})}a(Wi,"compareArkOrder");function qi(e,t,n){let r=t.arkRun,o=n.arkRun,s="$.arkRun";if(!r&&!o)return;if(!r&&o){O(e,{kind:"arkrun-added",path:s,classification:"strengthening",message:`ArkRun extra was added (${Sr(o)}).`,after:o});return}if(r&&!o){O(e,{kind:"arkrun-removed",path:s,classification:"weakening",message:"ArkRun extra was removed.",before:r});return}if(!r||!o)return;let i=Sr(r),l=Sr(o);if(i!==l){let c=i==="advisory"&&l==="enforced";O(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:i,after:l})}ie(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."}),ie(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."}),bt(e,`${s}.requireDeclarations`,r.requireDeclarations!==!1,o.requireDeclarations!==!1,"strengthening","ArkRun now requires interaction declarations.","ArkRun no longer requires interaction declarations.")}a(qi,"compareArkRun");function zi(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"}a(zi,"overallClassification");function Cs(e,t){return`${e}::${t}`}a(Cs,"ruleKey");function ws(e){let t=new Map,n=new Map;if(!e)return{structure:t,invariants:n};for(let r of e.structure)t.set(Cs(r.provenance.layer,r.id),r);for(let r of e.invariants)n.set(Cs(r.provenance.layer,r.id),r);return{structure:t,invariants:n}}a(ws,"indexEffectiveRules");function Yi(e,t,n,r,o,s){let i=new Map((s??[]).map(p=>[p.invariantId,p])),l=t.arkRules??{},c=n.arkRules??{},g=[...new Set([...Object.keys(l),...Object.keys(c)])].sort();for(let p of g){let f=l[p],u=c[p],y=`$.arkRules[${p}]`;if(f===void 0&&u!==void 0){O(e,{kind:"arkrules-ref-added",path:y,classification:"strengthening",message:`ArkRules reference for layer ${p} was added.`,after:u});continue}if(f!==void 0&&u===void 0){O(e,{kind:"arkrules-ref-removed",path:y,classification:"weakening",message:`ArkRules reference for layer ${p} was removed.`,before:f});continue}f!==u&&O(e,{kind:"arkrules-ref-path-changed",path:y,classification:"judgment-required",message:`ArkRules file path for layer ${p} changed; verify the effective rules still match intent.`,before:f,after:u})}let m=ws(r),h=ws(o);for(let p of[...new Set([...m.structure.keys(),...h.structure.keys()])].sort()){let f=m.structure.get(p),u=h.structure.get(p),y=`$.arkRules.structure[${p}]`;if(!f&&u){O(e,{kind:"arkrule-structure-added",path:y,classification:"strengthening",message:`Structure ArkRule ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-structure-removed",path:y,classification:"weakening",message:`Structure ArkRule ${f.id} was removed.`,before:f});continue}if(!(!f||!u)){if(f.mode!==u.mode){let E=f.mode==="advisory"&&u.mode==="enforced";O(e,{kind:E?"arkrule-promoted":"arkrule-demoted",path:`${y}.mode`,classification:E?"strengthening":"weakening",message:E?`Structure ArkRule ${u.id} was promoted to enforced.`:`Structure ArkRule ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}f.sensor!==u.sensor&&O(e,{kind:"arkrule-sensor-changed",path:`${y}.sensor`,classification:"judgment-required",message:`Structure ArkRule ${u.id} changed sensor identity.`,before:f.sensor,after:u.sensor})}}for(let p of[...new Set([...m.invariants.keys(),...h.invariants.keys()])].sort()){let f=m.invariants.get(p),u=h.invariants.get(p),y=`$.arkRules.invariants[${p}]`;if(!f&&u){O(e,{kind:"arkrule-invariant-added",path:y,classification:"strengthening",message:`Invariant ${u.id} was added (${u.mode}).`,after:u});continue}if(f&&!u){O(e,{kind:"arkrule-invariant-removed",path:y,classification:"weakening",message:`Invariant ${f.id} was removed.`,before:f});continue}if(!(!f||!u)&&f.mode!==u.mode)if(f.mode==="advisory"&&u.mode==="enforced"){let b=i?.get(u.id),A=Es(b);A.ok?O(e,{kind:"arkrule-invariant-promoted",path:`${y}.mode`,classification:"strengthening",message:`Invariant ${u.id} was promoted to enforced (coverage evidence present).`,before:f.mode,after:u.mode}):O(e,{kind:"arkrule-invariant-promote-refused",path:`${y}.mode`,classification:"judgment-required",message:`Invariant ${u.id} cannot be promoted to enforced: ${A.reason}`,before:f.mode,after:u.mode})}else O(e,{kind:"arkrule-invariant-demoted",path:`${y}.mode`,classification:"weakening",message:`Invariant ${u.id} was demoted to advisory.`,before:f.mode,after:u.mode})}}a(Yi,"compareArkRules");function xr(e,t,n){let r=[];ie(r,"$.include",e.include,t.include,{added:"strengthening",removed:"weakening",addedMessage:"Additional project roots are governed.",removedMessage:"Project roots were removed from governance."}),ie(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."}),ie(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."}),bt(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",i=t.cyclePolicy??"strict";if(s!==i){let l=o[i]===o[s]?"judgment-required":o[i]>o[s]?"strengthening":"weakening";O(r,{kind:"cycle-policy-changed",path:"$.cyclePolicy",classification:l,message:"The cycle enforcement level changed.",before:s,after:i})}return(e.frameworkOverlay??null)!==(t.frameworkOverlay??null)&&O(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}),Vi(r,e.layers,t.layers),ji(r,e.rules,t.rules),Bi(r,e,t),Yi(r,e,t,n?.baseArkRules,n?.candidateArkRules,n?.candidateInvariantCoverage),qi(r,e,t),Wi(r,e,t),r.sort((l,c)=>l.path.localeCompare(c.path)||l.id.localeCompare(c.id)),{schemaVersion:wr,classification:zi(r),findings:r}}a(xr,"classifyArkPolicyDelta");function Or(e,t){if(!e||e.schemaVersion!==wr||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])}a(Or,"policyDeltaAcknowledgementMatches");function Oe(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("/")}a(Oe,"normalizePath");function xs(e){return e!==void 0&&/[A-Za-z_$]/.test(e)}a(xs,"isIdentifierStart");function In(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}a(In,"isIdentifierCharacter");function ee(e,t){for(;t<e.length&&/\s/.test(e[t]);)t+=1;return t}a(ee,"skipWhitespace");function St(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}}a(St,"readString");function oe(e,t,n){return e.startsWith(t,n)&&!In(e[n-1])&&!In(e[n+t.length])}a(oe,"isWordAt");function Os(e,t){let n=ee(e,t);if(e[n]!=="{")return!1;n+=1;let r=!1;for(;n<e.length;){if(n=ee(e,n),e[n]==="}")return r;if(e[n]===","){n+=1;continue}if(!oe(e,"type",n))return!1;let o=ee(e,n+4);if(o>=e.length||e[o]===","||e[o]==="}"||oe(e,"as",o)||!xs(e[o]))return!1;for(n=o;n<e.length&&In(e[n]);)n+=1;if(n=ee(e,n),oe(e,"as",n)){if(n=ee(e,n+2),!xs(e[n]))return!1;for(;n<e.length&&In(e[n]);)n+=1}r=!0}return!1}a(Os,"bracedNamedBindingsAreTypeOnly");function Xi(e,t){if(t=ee(e,t+6),e[t]==="(")return St(e,ee(e,t+1));let n=!1;if(oe(e,"type",t)){let o=ee(e,t+4);e[o]!==","&&!oe(e,"from",o)&&(n=!0)}else Os(e,t)&&(n=!0);let r=Ps(e,t,!0);return r&&n?{...r,typeOnly:!0}:r}a(Xi,"specifierAfterImport");function Zi(e,t){t=t+6;let n=ee(e,t),r=!1;if(oe(e,"type",n)){let s=ee(e,n+4);(e[s]==="{"||e[s]==="*")&&(r=!0)}else Os(e,n)&&(r=!0);let o=Ps(e,t,!1);return o&&r?{...o,typeOnly:!0}:o}a(Zi,"specifierAfterExport");function Ps(e,t,n){for(;t<e.length;t+=1){if(e[t]===";")return;if(oe(e,"from",t))return St(e,ee(e,t+4));if(n&&(e[t]==="'"||e[t]==='"'))return St(e,t);if(t>0&&(oe(e,"import",t)||oe(e,"export",t)))return}}a(Ps,"specifierInStaticStatement");function Ji(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}a(Ji,"skipTemplateLiteral");function Qi(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;if(e[n]===".")return;let r=ee(e,t+7);if(e[r]!=="(")return;r=ee(e,r+1);let o=St(e,r);return o?{...o,requireCall:!0}:void 0}a(Qi,"specifierAfterRequire");function el(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 s=e.indexOf("*/",n+2);if(s<0)break;n=s+1;continue}if(r==="`"){n=Ji(e,n);continue}if(r==="'"||r==='"'){let s=St(e,n);s&&(n=s.offset+s.excerpt.length-1);continue}let o=r==="i"&&oe(e,"import",n)?Xi(e,n):r==="e"&&oe(e,"export",n)?Zi(e,n):r==="r"&&oe(e,"require",n)?Qi(e,n):void 0;o&&(t.push(o),n=o.offset+o.excerpt.length-1)}return t}a(el,"moduleSpecifiers");function _s(e,t){let n=[],r=[];for(let o of el(e.content)){let s=o.value;if(!s.startsWith(".")){if(o.typeOnly)continue;let g=mt(s);if(!g)continue;let m=e.content.slice(0,o.offset).split(`
|
|
24
24
|
`).length;r.push({file:e.path,symbol:s,capability:g,evidence:{kind:"import",file:e.path,line:m,excerpt:o.excerpt}});continue}let i=e.content.slice(0,o.offset).split(`
|
|
25
|
-
`).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=el(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}}a(Ps,"moduleFactsFor");function el(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 i=n.get(s);if(i)return i}}a(el,"resolveSpecifier");function _s(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ue(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}a(_s,"violationsFor");var tl={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 nl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(nl,"hasActiveArkRules");function rl(e,t){return nl(e,t)?B(F(As({config:e,arkRules:t,warnings:[]}))):B(F(e))}a(rl,"policyHashFor");function vn(e,t,n){let r=typeof e=="string"?Qo(e,t):lr(e,t),o=n?.arkRules??Et();return{...r,arkRules:o,policyHash:rl(r.config,o)}}a(vn,"loadContract");function Ns(e){let t=vn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=vn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=wr(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,i=s&&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:s,acknowledged:i,valid:!s||i}}a(Ns,"analyzePolicyDelta");function Ct(e){let t=e.files.map(h=>{let p=Oe(h.path);return{path:p,content:h.content,contentHash:B(h.content),layer:ae(p,e.contract.config.layers)??null}}).sort((h,p)=>h.path.localeCompare(p.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let p=Ps(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=_s(r,e.contract.config),i=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(We(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let f=i.get(p),u=Ie(h.symbol,f?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${h.symbol}" because it is the import form of forbidden global "${u}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(p)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} 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",g=c==="complete"?[]:[{...tl}],m={schemaVersion:Er,policyHash:e.contract.policyHash,compilerOptionsHash:B(F(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:g,valid:c==="complete"&&s.length===0,ir:m}}a(Ct,"analyzeProject");function En(e){let t=new Map(e.files.map(n=>[Oe(n.path),n]));for(let n of e.changes){let r=Oe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ct({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(En,"analyzeChange");function Ts(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}`}a(Ts,"explainViolation");function Or(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(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 g=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),g.push(m)}while(m!==c);g.length>1&&i.push(g.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,g)=>c[0]<g[0]?-1:c[0]>g[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"}))}a(Or,"detectArchitectureCycles");function Qe(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 i=or(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i)continue;let l=i.rule,c=!!l.peerIsolation,g=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?wo(i.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:i.fromSlice,toSlice:i.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:g?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...g?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Or(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.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}}a(Qe,"evaluateArchitectureGraph");var ol=["no-anemic-model"];function Ds(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Ds,"escapeGlobLiteral");function sl(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+=Ds(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Ds(o)}return new RegExp(`^${n}$`)}a(sl,"globToRegExp");function et(e,t){return!t||t.length===0?!0:t.some(n=>sl(n).test(e))}a(et,"matchesAppliesTo");function al(e){return ol.includes(e)}a(al,"isTier2");function Ls(e){return e.mode==="enforced"&&!al(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Ls,"severityFor");function Pe(e,t,n,r=1){let{severity:o,failsStrict:s}=Ls(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}}a(Pe,"baseViolation");function bn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(bn,"isInRuleLayer");function Sn(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!bn(r.file,e,n)))}a(Sn,"shapesForRule");function il(e,t,n){let r=[];for(let o of Sn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Pe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(il,"evaluateAggregatePrivateState");function ll(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Pe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(ll,"evaluateAlwaysValidFactory");function cl(e,t,n){let r=[];for(let o of Sn(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(Pe(e,o.file,`Mutating method ${o.className}.${s.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}a(cl,"evaluateDomainEventOnMutation");function dl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Pe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(dl,"evaluateOrchestrationOnly");function pl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Pe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(pl,"evaluateThinAdapter");function ul(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Pe(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}a(ul,"evaluateWritesViaAggregate");function fl(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.dataOnly===!0){let s=Pe(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}a(fl,"evaluateNoAnemicModel");function Fs(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(...il(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...ll(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...cl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...dl(n,e));break;case"thin-adapter":t.push(...pl(n,e));break;case"writes-via-aggregate":t.push(...ul(n,e));break;case"no-anemic-model":t.push(...fl(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))}a(Fs,"evaluateArkRuleSensors");function $s(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=>et(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Ls(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:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>et(l,o.appliesTo)))continue;let i=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:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a($s,"collectEmptyAppliesToFindings");var gl=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,ml=/\.(?: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,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*=)/,hl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Rl=/\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*=/,Al=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function kl(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Rl.source,"g"))??[],r=t.match(new RegExp(Al.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,i=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,l=gl.test(t),c=yl.test(t)||hl.test(t),g=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=l&&g||c&&g||l&&m&&(o>=4||n.length>=1)||c&&l,p=l&&ml.test(t);return!i&&!h&&!p?null:{...i?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}a(kl,"deriveArkRuleFileHints");function Ms(e){let t={};for(let[n,r]of Object.entries(e)){let o=kl(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}a(Ms,"buildArkRuleFileHints");function Il(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}}a(Il,"normalizeExtraMergeTeethClassification");function Cn(e){let t=Il(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}a(Cn,"extraMergeTeethAllowed");function Ks(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}}a(Ks,"classifyResolvedLayerCoverage");var vl=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var wf=new Set(vl);function Hs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(Hs,"isArkRunKernelModuleSpecifier");var El=["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"],Pr=new Set(El);function Gs(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(Pr.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(Pr.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:Pr.has(e.slice(0,r))}a(Gs,"isArkRunTransportBypassSpecifier");var bl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],$f=new Set(bl);var Us={"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"},Sl="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Bs(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.")})}a(Bs,"isDomainRoleLayer");function Cl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(Cl,"compareFindings");function ye(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Us[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:le({ruleId:Us[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ye,"finding");function wl(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(wl,"bagForFile");function Vs(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(Vs,"emitKinds");function js(e){return e==="subscribe"||e==="register-handler"}a(js,"handleKinds");function xl(e){return e==="resolve"||e==="resolve-singleton"}a(xl,"dependKinds");function Ol(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ye(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 i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((g,m)=>g.file.localeCompare(m.file));if(l.length===0){r.push(ye(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(g=>g.hasKernelFactory))continue;let c=l[0];r.push(ye(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Ol,"evaluateMissingRoot");function Pl(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!Hs(c))continue;let g=r(l.from);g&&Bs(g,s.get(g)??[])&&i.push(ye(e,"arkrun-kernel-in-domain",l.from,l.line,`${g} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:g,target:c},o))}return i}a(Pl,"evaluateKernelInDomain");function _l(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.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)),g=[];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 p=o(m.file);!p||!i.has(p)||Bs(p,l.get(p)??[])||g.push(ye(e,"arkrun-direct-new",m.file,m.line,`${p} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:m.typeName},s))}return g}a(_l,"evaluateDirectNew");function Nl(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!Vs(c.kind)&&!js(c.kind)&&!xl(c.kind))continue;let g=r(c.file);if(!g||!l.has(g))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:Sl,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=wl(n,c.file);if(Vs(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:g,target:c.nameLiteral},o));continue}if(js(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:g,target:c.nameLiteral},o));continue}m.uses.has(c.nameLiteral)||s.push(ye(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:g,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Nl,"evaluateUndeclared");function Tl(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!Gs(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(ye(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Tl,"evaluateTransportBypass");function Ws(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=Nl(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Ol(t,e.compositionRootHits,n),...Pl(t,e.layers,e.dependencies,e.layerForFile,n),..._l(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Tl(t,e.dependencies,e.layerForFile,n)].sort(Cl),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,g=`${l.code}\0${l.file??""}\0${l.message}`;return c<g?-1:c>g?1:0});return{findings:o,completenessReasons:s}}a(Ws,"evaluateArkRunSensors");function qs(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(qs,"isArkOrderModuleSpecifier");var zs={"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 Dl(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.")})}a(Dl,"isDomainRoleLayer");function he(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:zs[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:le({ruleId:zs[t],fromLayer:s?.fromLayer,target:s?.target})}}a(he,"finding");function Ys(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(he(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 g of e.planeRootHits){let m=c.get(g.matchedRoot)??[];m.push(g),c.set(g.matchedRoot,m)}for(let g of o){let m=c.get(g)??[];if(m.length===0){r.push(he(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(g)} matched no governed files and has no createOrderPlane factory.`,{target:g},n));continue}m.some(h=>h.hasPlaneFactory)||r.push(he(t,"arkorder-missing-plane",m[0].file,1,`ArkOrder plane root ${JSON.stringify(g)} has no createOrderPlane factory.`,{target:g},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let g=c.specifier;if(!g||!qs(g))continue;let m=e.layerForFile(c.from);m&&Dl(m,s.get(m)??[])&&r.push(he(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:g},n))}for(let c of e.genericUpdates)r.push(he(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 i=t.xiKeys??[];i.length>t.maxXiKeys&&r.push(he(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${i.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(i.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(he(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(he(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 i.length===0?[]:e.xiFieldWrites??[]){let g=e.layerForFile(c.file);!g||!l.has(g)||r.push(he(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:g,target:c.key},n))}return r.sort((c,g)=>c.file.localeCompare(g.file)||c.ruleId.localeCompare(g.ruleId)||c.line-g.line),{findings:r,completenessReasons:[]}}a(Ys,"evaluateArkOrderSensors");function Z(e,t,n={}){return{ruleId:e,message:t,...n}}a(Z,"configWarning");function wn(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(Z("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(Z("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[f];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(Z("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);i.length===0&&s.push(Z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,m=new Set;for(let f of i){if(!f.name){s.push(Z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(f.name)&&m.add(f.name),g.add(f.name),f.forbiddenGlobals!==void 0&&(!Array.isArray(f.forbiddenGlobals)||f.forbiddenGlobals.some(y=>typeof y!="string"))&&s.push(Z("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 u=Array.isArray(f.patterns)?f.patterns:[];if(u.length===0){s.push(Z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of u){let E;try{E=pe(y)}catch(A){s.push(Z("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 b=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>E.test(A))&&!b&&s.push(Z("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(Z("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(Z("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(Z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(i.length>1)for(let f of r){let u=-1,y=[];for(let E of i)for(let b of E.patterns??[]){if(!pe(b).test(f))continue;let A=rr(b,f);A>u?(u=A,y=[E.name]):A===u&&!y.includes(E.name)&&y.push(E.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(Z("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 p=r.filter(f=>!ae(f,i));return p.length>0&&s.push(Z("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)})),s}a(wn,"collectAnalysisConfigWarnings");function Ll(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}a(Ll,"matchesAny");function Fl(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??[],i=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:E})=>({file:y,line:E})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:E})=>({file:y,line:E})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Ll(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),g=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:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:g,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];p.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 u=c.filter(y=>y.kind==="require");if(u.length>0){let y=u[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let y=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(g.length>0){let y=g[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${g.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&&p.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:p}}a(Fl,"evaluateSafety");function $l(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a($l,"ambientForbiddenGlobal");function Xs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return kr(e,n.length>0?n:Ar.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Xs,"intentLayer");function Ml(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!$l(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],g=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"&&yt(s.symbol,c))){if(s.source==="import-based"){let m=Ie(s.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...g?{edgeKind:g}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}We(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...g?{edgeKind:g}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of ht({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:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=Xs(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=Xs(s.intent,e.contract);if(!l)continue;let c=ue(e.contract.config.rules,i,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,message:c.message??`${i} must not reference ${l} intent ${s.intent}.`})}return r}a(Ml,"contentViolations");function Kl(e){let{facts:t}=e,n=It(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,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),i=t.files.map(d=>({...d,layer:ae(d.path,e.contract.config.layers)??null})),l=new Map(i.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let N=d.target?l.get(d.target)??ae(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,...N?{toLayer:N}:{}}:{},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}:{}}}),g=wn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(d=>d.path)}),m=Fl(e,t),h=e.contract.arkRules??Et(),p=i.map(d=>d.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ms(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...Fs({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),fileHints:u}),...$s(h,p)],E=y.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:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),b=y.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==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),v=(h.invariants?.length??0)>0?Is({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},P=v.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.`})),j=v.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).`})),k=Ks(i),_=Ws({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:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,de=_.findings.filter(()=>z==="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}:{}})),Bt=_.findings.filter(()=>z!=="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})),Ne=Ys({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:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),qn=e.contract.config.arkOrder?.mode,Wt=Ne.findings.filter(()=>qn==="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}:{}})),so=Ne.findings.filter(()=>qn!=="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})),at=[...v.partial&&v.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."}]:[],..._.completenessReasons,...Ne.completenessReasons],Ee=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Ml(e,t,l),...E,...P,...de,...Wt],edges:c,warnings:[...g,...m.warnings,...b,...j,...Bt,...so],safety:m.report}),qt=o==="complete"&&at.length>0?"partial":o,Yn=qt==="complete"?s:[...s,...at].sort((d,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),S=Ee.violations.filter(d=>d.failsStrict!==!1),C=qt==="complete"&&S.length===0,R=C&&Ee.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:qt,completenessReasons:Yn,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:i,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Ee.violations,warnings:Ee.warnings}}}a(Kl,"analyzeCanonicalResolvedProject");function wt(e){return Kl({contract:e.contract,facts:ve(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}a(wt,"analyzeResolvedProject");function Zs(e){return B(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Zs,"analysisTreeHash");function Js(e){let t=Ct(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let y=u.path.replace(/\\/g,"/"),E=Oe(u.path);if(!E||E===".."||E.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(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in u&&u.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:E,delete:!0}:{path:E,content:"content"in u?u.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 i=En({...e,changes:r}),l=new Map(i.ir.files.map(u=>[u.path,u])),c=i.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let y=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:u.message}}),g=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(u=>u.path),contentViolations:c,edges:i.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(u=>{let y=Oe(u.path),E=n.get(y),b=l.get(y);return{path:y,operation:"delete"in u&&u.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((u,y)=>u.path.localeCompare(y.path)),h=[...s,...g.violations].map(u=>({...u,nextAction:le(u)})),p=h.filter(u=>u.failsStrict!==!1),f=e.changeMap?Je({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:i.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Zs(t.ir.files),candidateTreeHash:Zs(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:g.warnings}}a(Js,"preflightChange");function Hl(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}a(Hl,"canonicalChangePath");function Gl(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}.`}))}a(Gl,"identityViolations");function Ul(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}:{}}}a(Ul,"preparedChange");function Qs(e){let t=ve(e.baseFacts),n=ve(e.candidateFacts),r=wt({contract:e.contract,facts:t}),o=wt({contract:e.contract,facts:n}),s=new Map(t.files.map(f=>[f.path,f])),i=new Map(n.files.map(f=>[f.path,f])),l=Gl(t,n),c=new Map,g=[];for(let f of e.changes){let u=Hl(f.path);if(!u){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(u)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}c.set(u,f);let y=s.get(u),E=i.get(u);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let b="content"in f?f.content:"",A=B(b);E?E.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:A,candidateContentHash:E.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}g.push(Ul(f,u,s,i))}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(),...i.keys()])){if(c.has(f))continue;let u=s.get(f),y=i.get(f);u&&y&&F(u)===F(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?Je({changeMap:e.changeMap,changes:g,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:le(f)})),p=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.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:g.sort((f,u)=>f.path<u.path?-1:f.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}a(Qs,"preflightResolvedChange");var _r="docs/diagnostics.md",Vl="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var xn=Object.freeze([I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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."),I("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}),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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."),I("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}),I("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.")]),Nr=new Map(xn.map(e=>[e.ruleId,e])),jl=Object.freeze(xn.map(e=>e.ruleId));function Bl(e){return typeof e=="string"&&e.length>0&&Nr.has(e)}a(Bl,"isKnownDiagnosticCode");function Wl(e){return typeof e!="string"||e.length===0?!1:Nr.has(e)?!0:e.startsWith("ARKRULE_")}a(Wl,"isCataloguedOrArkRuleFamily");function On(e){if(!(typeof e!="string"||e.length===0))return Nr.get(e)}a(On,"getDiagnosticCatalogEntry");function ea(e){return`#${On(e)?.docsAnchor??e}`}a(ea,"diagnosticDocsFragment");function ql(e){return`${_r}${ea(e)}`}a(ql,"diagnosticDocsPath");function zl(){return{schemaVersion:"1.0",docsPath:_r,codes:xn}}a(zl,"serializeDiagnosticCatalog");function Yl(e){return On(e)?.fix}a(Yl,"catalogFixForRuleId");function Xl(e){return On(e)?.why}a(Xl,"catalogWhyForRuleId");var Zl="1.1";var Jl="1.0";var xt=class{static{a(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 Ql(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(Ql,"initialState");var Pn=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new xt,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)??Ql(r),s=await r.project(t,o);await this.store.save(r.name,s);let i=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(i?.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 _n(e){return new Pn(e)}a(_n,"createProjectionRegistry");var Nn="1.0";function ec(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(ec,"policyId");var Tr=class{constructor(t){this.data=t}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Tn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,i=e.projections,l=e.eventContracts,c=e.observability,g=t?t.list().map(b=>({name:b.name,dependencies:t.getDependencies(b.name),productions:t.getProductions(b.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(b=>({id:ec(b.name),name:b.name,severity:b.severity,tags:b.tags?[...b.tags]:void 0,owner:b.owner,version:b.version,rationale:b.rationale,enforcementMode:b.enforcementMode,deprecated:b.deprecated,replacedBy:b.replacedBy,description:b.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},u=p.filter(b=>(b.emits?.length??0)>0||(b.consumes?.length??0)>0).map(b=>({entity:b.name,emits:b.emits,consumes:b.consumes})),y=i?i.list().map(b=>({name:b.name,sourceIntents:b.sourceIntents,checkpoint:i.getCheckpoint(b.name)})):[],E={schemaVersion:"1.0",version:Zn,exportedAt:new Date().toISOString(),intents:g,relationships:m,policies:h,entities:p,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:u}};return new Tr(E)}a(Tn,"createArkManifest");var ta=0;function na(e){return ta+=1,`${e}-${Date.now()}-${ta}`}a(na,"createWorkflowId");function Dr(e){return e instanceof Error?e.message:String(e)}a(Dr,"errorMessage");function tc(e){return new Promise(t=>{setTimeout(t,e)})}a(tc,"sleep");async function nc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((i,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)}}a(nc,"withTimeout");var Ot=class{static{a(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 i=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||i){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()}},Lr=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Ot}bus;options;static{a(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(),i={id:r.id??na(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(i,r.tx),await this.audit("workflow.started",i,{workflowName:t}),this.executeSnapshot(i,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=Dr(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 i=1;i<=s;i+=1){t.attempts[n.name]=i,await this.store.save(t,r);let l;try{l=await nc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await tc(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:i,error:Dr(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:i});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(i=>t.completedSteps.includes(i.name));for(let i=s.length-1;i>=0;i-=1){let l=s[i];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:Dr(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Pt(e,t){return new Lr(e,t)}a(Pt,"createWorkflowEngine");function ra(e,t,n={}){let r=Pt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??na(e.name),i="idle",l=[];return{id:s,definition:e,get status(){return i},get completedSteps(){return[...l]},async run(c){i="running",l=[];try{let g=await r.start(e.name,c,{id:s});i=g.status==="waiting"?"idle":g.status,l=[...g.completedSteps]}catch(g){let m=await r.get(s);throw i=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],g}}}}a(ra,"createSaga");tt();function ia(e){return Object.keys(e).sort()}a(ia,"sortedKeys");function Hr(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:[],g=Math.max(l.length,c.length);for(let m=0;m<g;m+=1)Hr(l[m],c[m],`${n}[${m}]`,r);return}let o=e,s=t,i=new Set([...ia(o),...ia(s)]);for(let l of[...i].sort())Hr(o[l],s[l],n?`${n}.${l}`:l,r)}a(Hr,"walk");function la(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}}))}:{}}}a(la,"shadowInformationPackage");function Gr(e,t){let n=[];return Hr(e,t,"",n),{equal:n.length===0,diffs:n}}a(Gr,"compareInformationPackages");function ca(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Gr(e[n-1],e[n]));return t}a(ca,"replayInformationPackages");Hn();$t();Vt();Vt();async function Wn(e,t={}){let n=Gt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(Ea(),va));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(Wn,"startArkRunInspector");Hn();Vt();tt();$t();tt();var Tc=new Set(["singleton","transient"]);function ba(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}a(ba,"cloneComponent");function Dc(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Tc.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Dc,"closedLifetime");function Sa(){let e=new Map,t=new Map,n=new Set;function r(i){let l=e.get(i);if(!l)throw new Error(`ArkRun component "${i}" is not registered.`);return l}a(r,"mustRecord");function o(i,l){if(!l.factory)throw new Error(`ArkRun component "${i}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(i))throw new Error(`ArkRun component "${i}" has a circular resolve.`);n.add(i);try{return l.factory()}finally{n.delete(i)}}a(o,"instantiate");function s(i,l){if(t.has(i))return t.get(i);let c=o(i,l);return t.set(i,c),c}return a(s,"singleton"),{register(i){let l=typeof i?.id=="string"?i.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=Dc(i.lifetime),g=Mr({id:l,lifetime:c,uses:i.uses,reactsTo:i.reactsTo,raises:i.raises,sends:i.sends,extendedInfo:i.extendedInfo});if(!g)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof i.factory=="function"?i.factory:void 0;return e.set(l,{component:g,factory:m}),ba(g)},resolve(i){let l=r(i);return l.component.lifetime==="transient"?o(i,l):s(i,l)},resolveSingleton(i){let l=r(i);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${i}" is transient; resolveSingleton requires lifetime "singleton".`);return s(i,l)},snapshotComponents(){return[...e.values()].map(i=>ba(i.component))}}}a(Sa,"createComponentRegistry");$t();function Lc(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new ke(e.source,t.source);return t.source=e.source,t}a(Lc,"stampMetadata");function Fc(){}a(Fc,"ignoreDetachedFailure");async function eo(e,t,n,r={}){let o=Gn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Lc(r),i=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(i));o.awaitHandoff?await l:l.then(void 0,Fc)}return o}a(eo,"sendOnArkRunTransport");var to=1e3,Ca=0;function $c(){return Ca+=1,`ark-kernel-${Date.now()}-${Ca}`}a($c,"nextKernelInstanceId");function jt(e={}){let t=e.strict??!0,n=e.instanceId??$c(),r=e.profile??Be,o=e.maxHistorySize??to,s=Yt(),i=cn(),l=e.metadata??hn(),c=e.auditTrail??an({maxRecords:o}),g=e.eventContracts??rn(),m=e.eventBuffer??e.outbox??new Ce,h=e.projections??_n({auditTrail:c}),p=new be([Qt(r),...e.policies??[]]),f=a(()=>{dn(s,i,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,y=e.broker,E=new Ue({intentRegistry:s,dependencyGraph:i,policyEngine:p,strictRegistry:!0,validateIntentNaming:!0,auditTrail:c,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:m,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async k=>{await h.apply(k)}}),b=Pt(E,{auditTrail:c}),A=on({registry:s,eventBus:E,graph:i}),v=Sa(),P=typeof y?.send=="function",j={instanceId:n,profile:r,registry:s,graph:i,metadata:l,auditTrail:c,eventContracts:g,eventBuffer:m,outbox:m,projections:h,policyEngine:p,eventBus:E,workflowEngine:b,observability:A,publisher(k){let _=E.createPublisher(k);return{source:_.source,publish:_.publish,send(z,de,Bt={}){return eo({eventBus:E,broker:y,defaultEphemeral:u},z,de,{...Bt,source:_.source})}}},send(k,_,z={}){return eo({eventBus:E,broker:y,defaultEphemeral:u},k,_,z)},register(k){return v.register(k)},resolve(k){return v.resolve(k)},resolveSingleton(k){return v.resolveSingleton(k)},getDependencyInformationPackage(){return Re({kernelInstanceId:n,components:v.snapshotComponents()})},requestGraph(k){return Kn({kernelInstanceId:n,components:v.snapshotComponents()},k)},getInspectorSnapshot(k){return jn({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:v.snapshotComponents()},observability:A.report(),ephemeralDefault:u,brokerBound:P})},startInspector(k){return Wn(j,k)},syncGraph:f,manifest(){return f(),Tn({registry:s,policyEngine:p,metadata:l,graph:i,profile:r,projections:h,eventContracts:g,observability:A})}};return j}a(jt,"createArkKernel");function no(e={}){return jt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(no,"createStrictArkKernel");function ro(e,t={}){let{profileName:n,...r}=t;return{...r,profile:mn(e,{name:n})}}a(ro,"createOptionsFromConfig");function wa(e,t={}){return jt(ro(e,t))}a(wa,"createArkKernelFromConfig");function xa(e,t={}){return no(ro(e,t))}a(xa,"createStrictArkKernelFromConfig");function Oa(e,t={}){return oo(ro(e,t))}a(Oa,"createLenientArkKernelFromConfig");function oo(e={}){return jt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(oo,"createLenientArkKernel");export{Er as ANALYSIS_IR_SCHEMA_VERSION,Va as ARK_ANALYSIS_RESULT_SCHEMA,Qn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Jl as ARK_DESIGN_DELTA_SCHEMA_VERSION,Zl as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,Fr as ARK_RUN_COMPONENT_LIFETIMES,rt as ARK_RUN_EPHEMERAL_DEFAULT,Br as ARK_RUN_GRAPH_DEFAULT_SLICE,ga as ARK_RUN_GRAPH_NODE_KINDS,ma as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,jr as ARK_RUN_GRAPH_SCHEMA_VERSION,Wr as ARK_RUN_GRAPH_SLICES,ya as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Dn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,Un as ARK_RUN_INSPECTOR_DEFAULT_HOST,Zr as ARK_RUN_INSPECTOR_DEFAULT_PORT,Kt as ARK_RUN_INSPECTOR_EVENTS_PATH,Ht as ARK_RUN_INSPECTOR_GRAPH_PATH,Xr as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Mt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Jr as ARK_RUN_INSPECTOR_SSE_EVENT,Qr as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,Ft as ARK_RUN_TRANSPORT_KINDS,se as ArkRunInspectorBindError,ot as ArkRunInspectorProductionError,to as DEFAULT_MAX_HISTORY_SIZE,xn as DIAGNOSTIC_CATALOG,Vl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,_r as DIAGNOSTIC_DOCS_RELATIVE_PATH,jl as DIAGNOSTIC_RULE_IDS,pt as EventContractRegistryImpl,Me as EventContractViolationError,ut as InMemoryAuditStore,Ce as InMemoryEventBuffer,Mo as InMemoryOutboxStore,xt as InMemoryReadModelStore,Ot as InMemoryWorkflowStore,Te as IntentRegistry,J as InvalidArkRunGraphQueryError,nt as InvalidArkRunSendOptionError,Fe as InvalidIntentNameError,$e as LayerPolicyContextError,Nn as MANIFEST_SCHEMA_VERSION,Ke as ObservedLayerFlowViolationError,Cr as POLICY_DELTA_SCHEMA_VERSION,be as PolicyEngine,Ae as PolicyViolationError,vr as RESOLVED_CANDIDATE_FACTS_SCHEMA,xe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ke as SourceMetadataOverrideError,Se as UnknownEventSourceError,Le as UnregisteredIntentError,Je as analyzeArchitectureConvergence,En as analyzeChange,Ns as analyzePolicyDelta,Ct as analyzeProject,wt as analyzeResolvedProject,aa as appendDecisionTape,er as architecturalPolicies,Mn as arkRunGraphQueryFromSearchParams,_e as arkRunInspectorUrl,jn as buildArkRunInspectorSnapshot,Re as buildDependencyInformationPackage,en as buildPublishPolicyContext,Yl as catalogFixForRuleId,Xl as catalogWhyForRuleId,cr as checkAdapterGovernance,os as checkContract,wr as classifyArkPolicyDelta,$n as closeArkRunGraphQuery,Yr as closedArkRunEphemeral,zr as closedArkRunTransportKind,wn as collectAnalysisConfigWarnings,Ye as collectForbiddenCapabilityUses,Gr as compareInformationPackages,us as createAICodeGate,rs as createAdapter,Ua as createAdapterResult,gn as createArchitectureProfile,mn as createArchitectureProfileFromArkConfig,jt as createArkKernel,wa as createArkKernelFromConfig,Tn as createArkManifest,Go as createArkTestHarness,an as createAuditTrail,cn as createDependencyGraph,ts as createElevenLayerArkConfig,To as createEventBus,rn as createEventContractRegistry,Yt as createIntentRegistry,oo as createLenientArkKernel,Oa as createLenientArkKernelFromConfig,hn as createMetadataRegistry,on as createObservabilityReporter,_n as createProjectionRegistry,Ir as createResolvedCandidateFacts,ra as createSaga,no as createStrictArkKernel,xa as createStrictArkKernelFromConfig,Pt as createWorkflowEngine,fo as defaultIntentRegistry,Qt as defineArchitectureProfilePolicy,uo as defineIntent,Zt as defineLayerPolicy,De as definePolicy,ns as definePort,yo as definePublishPolicy,Or as detectArchitectureCycles,B as deterministicHash,ea as diagnosticDocsFragment,ql as diagnosticDocsPath,Be as elevenLayerProfile,Qe as evaluateArchitectureGraph,Ts as explainViolation,ze as extractSemanticDependencies,qr as formatArkRunGraphMermaid,Ut as formatArkRunInspectorSseEvent,On as getDiagnosticCatalogEntry,st as isArkRunInspectorLoopbackHost,Vn as isArkRunInspectorProductionEnv,Wl as isCataloguedOrArkRuleFamily,Bl as isKnownDiagnosticCode,Jt as isLayerPolicy,vn as loadContract,ve as loadResolvedCandidateFacts,xr as policyDeltaAcknowledgementMatches,Js as preflightChange,Qs as preflightResolvedChange,ca as replayInformationPackages,Kn as requestArkRunGraph,Gt as resolveArkRunInspectorBind,Gn as resolveArkRunSendPlan,It as resolvedFactsEvidenceRequirementsHash,zl as serializeDiagnosticCatalog,la as shadowInformationPackage,F as stableSerialize,Wn as startArkRunInspector,dn as syncRegistryToGraph,Jn as toAdapterDiagnostic,Xt as validateIntentName,Zn as version};
|
|
25
|
+
`).length,l={kind:"import",file:e.path,line:i,excerpt:o.excerpt},c=tl(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}}a(_s,"moduleFactsFor");function tl(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 i=n.get(s);if(i)return i}}a(tl,"resolveSpecifier");function Ns(e,t){let n=[];for(let r of e){if(!r.to||!r.fromLayer||!r.toLayer)continue;let o=ue(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}a(Ns,"violationsFor");var nl={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 rl(e,t){return e.arkRules!==void 0&&Object.keys(e.arkRules).length>0||t.structure.length>0||t.invariants.length>0}a(rl,"hasActiveArkRules");function ol(e,t){return rl(e,t)?B(F(ks({config:e,arkRules:t,warnings:[]}))):B(F(br(e)))}a(ol,"policyHashFor");function vn(e,t,n){let r=typeof e=="string"?es(e,t):lr(e,t),o=n?.arkRules??Et();return{...r,arkRules:o,policyHash:ol(r.config,o)}}a(vn,"loadContract");function Ts(e){let t=vn(e.baseConfig,e.baseSource??"base ark.config.json",{arkRules:e.baseArkRules}),n=vn(e.candidateConfig,e.candidateSource??"candidate ark.config.json",{arkRules:e.candidateArkRules}),r=xr(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,i=s&&Or(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:i,valid:!s||i}}a(Ts,"analyzePolicyDelta");function Ct(e){let t=e.files.map(h=>{let p=Oe(h.path);return{path:p,content:h.content,contentHash:B(h.content),layer:ae(p,e.contract.config.layers)??null}}).sort((h,p)=>h.path.localeCompare(p.path)),n=new Map(t.map(h=>[h.path,h])),r=[],o=[];for(let h of t){let p=_s(h,n);r.push(...p.edges),o.push(...p.capabilityUses)}let s=Ns(r,e.contract.config),i=new Map(e.contract.config.layers.map(h=>[h.name,h])),l=new Map(e.contract.config.layers.map(h=>[h.name,new Set(We(h))]));for(let h of o){let p=n.get(h.file)?.layer;if(!p)continue;let f=i.get(p),u=Ie(h.symbol,f?.forbiddenGlobals??[]);if(u){s.push({ruleId:"FORBIDDEN_GLOBAL",message:`${p} must not use module "${h.symbol}" because it is the import form of forbidden global "${u}".`,symbol:h.symbol,evidence:h.evidence});continue}l.get(p)?.has(h.capability)&&s.push({ruleId:"CAPABILITY_VIOLATION",message:`${p} 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",g=c==="complete"?[]:[{...nl}],m={schemaVersion:Er,policyHash:e.contract.policyHash,compilerOptionsHash:B(F(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:g,valid:c==="complete"&&s.length===0,ir:m}}a(Ct,"analyzeProject");function En(e){let t=new Map(e.files.map(n=>[Oe(n.path),n]));for(let n of e.changes){let r=Oe(n.path);"delete"in n&&n.delete?t.delete(r):"content"in n&&t.set(r,{path:r,content:n.content})}return Ct({contract:e.contract,files:[...t.values()],compilerOptions:e.compilerOptions})}a(En,"analyzeChange");function Ds(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}`}a(Ds,"explainViolation");function Pr(e){let t=0,n=new Map,r=new Map,o=new Set,s=[],i=[],l=a(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 g=[],m;do{if(m=s.pop(),m===void 0)break;o.delete(m),g.push(m)}while(m!==c);g.length>1&&i.push(g.sort())},"connect");for(let c of[...e.keys()].sort())n.has(c)||l(c);return i.sort((c,g)=>c[0]<g[0]?-1:c[0]>g[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"}))}a(Pr,"detectArchitectureCycles");function Qe(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 i=or(e.rules,s.fromLayer,s.toLayer,{fromPath:s.from,toPath:s.to,layers:e.config.layers});if(!i)continue;let l=i.rule,c=!!l.peerIsolation,g=!c&&!!(s.typeOnly||s.namedBindingsTypeOnly),m=c?xo(i.peerIsolationReason??"cross-slice",{fromPath:s.from,toPath:s.to,fromSlice:i.fromSlice,toSlice:i.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:g?`${h} (type-only \u2014 type placement debt; prefer SharedTypes / owning layer; not runtime coupling)`:h,...g?{failsStrict:!1,severity:"warning"}:{}})}let o=String(e.config.cyclePolicy??"strict").toLowerCase();if(o!=="off"){let s=Pr(r);o==="soft"||o==="framework-soft"?n.push(...s.map(i=>({...i,message:`${i.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}}a(Qe,"evaluateArchitectureGraph");var sl=["no-anemic-model"];function Ls(e){return/[.*+?^${}()|[\]\\]/.test(e)?`\\${e}`:e}a(Ls,"escapeGlobLiteral");function al(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+=Ls(t[r+1]),r+=1):o==="*"?t[r+1]==="*"?t[r+2]==="/"?(n+="(?:.*/)?",r+=2):(n+=".*",r+=1):n+="[^/]*":o==="?"?n+="[^/]":n+=Ls(o)}return new RegExp(`^${n}$`)}a(al,"globToRegExp");function et(e,t){return!t||t.length===0?!0:t.some(n=>al(n).test(e))}a(et,"matchesAppliesTo");function il(e){return sl.includes(e)}a(il,"isTier2");function Fs(e){return e.mode==="enforced"&&!il(e.sensor)?{severity:"error",failsStrict:!0}:{severity:"warning",failsStrict:!1}}a(Fs,"severityFor");function Pe(e,t,n,r=1){let{severity:o,failsStrict:s}=Fs(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}}a(Pe,"baseViolation");function bn(e,t,n){if(!n)return!0;let r=n(e);return r?r===t.provenance.layer:!1}a(bn,"isInRuleLayer");function Sn(e,t,n){return t.filter(r=>!(!r.exported||!et(r.file,e.appliesTo)||!bn(r.file,e,n)))}a(Sn,"shapesForRule");function ll(e,t,n){let r=[];for(let o of Sn(e,t,n))(o.hasPublicSetters||o.hasPublicMutableFields)&&r.push(Pe(e,o.file,`Exported class ${o.className} exposes public mutable state (sensor aggregate-private-state).`));return r}a(ll,"evaluateAggregatePrivateState");function cl(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.hasPublicConstructor&&!o.hasStaticFactory){if(!(o.hasPublicMutableFields||o.hasPublicSetters||(o.mutatingMethods?.length??0)>0))continue;r.push(Pe(e,o.file,`Exported class ${o.className} exposes a public constructor without a static factory (sensor always-valid-factory).`))}return r}a(cl,"evaluateAlwaysValidFactory");function dl(e,t,n){let r=[];for(let o of Sn(e,t,n))for(let s of o.mutatingMethods)s.referencesGuardOrPublish||r.push(Pe(e,o.file,`Mutating method ${o.className}.${s.name} does not reference a guard or publish symbol (sensor domain-event-on-mutation).`));return r}a(dl,"evaluateDomainEventOnMutation");function pl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.orchestrationHeavy&&n.push(Pe(e,r,"File appears to embed domain branching beyond guard-and-delegate orchestration (sensor orchestration-only)."));return n}a(pl,"evaluateOrchestrationOnly");function ul(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.adapterThick&&n.push(Pe(e,r,"Adapter module mixes domain branching, persistence, and mapping beyond a thin adapter (sensor thin-adapter)."));return n}a(ul,"evaluateThinAdapter");function fl(e,t){let n=[];for(let r of t.files)et(r,e.appliesTo)&&bn(r,e,t.layerForFile)&&t.fileHints?.[r]?.persistenceWrite&&n.push(Pe(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}a(fl,"evaluateWritesViaAggregate");function gl(e,t,n){let r=[];for(let o of Sn(e,t,n))if(o.dataOnly===!0){let s=Pe(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}a(gl,"evaluateNoAnemicModel");function $s(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(...ll(n,e.classShapes,e.layerForFile));break;case"always-valid-factory":t.push(...cl(n,e.classShapes,e.layerForFile));break;case"domain-event-on-mutation":t.push(...dl(n,e.classShapes,e.layerForFile));break;case"orchestration-only":t.push(...pl(n,e));break;case"thin-adapter":t.push(...ul(n,e));break;case"writes-via-aggregate":t.push(...fl(n,e));break;case"no-anemic-model":t.push(...gl(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))}a($s,"evaluateArkRuleSensors");function Ms(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=>et(c,o.appliesTo)))continue;let{severity:i,failsStrict:l}=Fs(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:i,sensor:o.sensor,failsStrict:l})}for(let o of e.invariants??[]){if(!o.appliesTo||o.appliesTo.length===0||r.some(l=>et(l,o.appliesTo)))continue;let i=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:i?"error":"warning",sensor:"invariant-coverage",failsStrict:i})}return n.sort((o,s)=>o.file.localeCompare(s.file)||o.arkruleId.localeCompare(s.arkruleId)||o.message.localeCompare(s.message))}a(Ms,"collectEmptyAppliesToFindings");var ml=/\bfrom\s+['"](?:@?prisma\/client|@supabase\/|drizzle-orm|typeorm|knex|mongodb|pg|mysql2|mongoose|better-sqlite3|ioredis|redis|kysely|sequelize)['"]|require\(\s*['"](?:@?prisma\/client|pg|knex|typeorm|mongoose)/,yl=/\.(?: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,hl=/\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*=)/,Rl=/(?:^|[;\n])\s*(?:import\s+(?:type\s+)?(?:[^;]{0,512}?\s+from\s+)?|export\s+(?:type\s+)?[^;]{0,512}?\s+from\s+)['"]next\/server(?:\.js)?['"]/,Al=/\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*=/,kl=/\bif\s*\(\s*(?:!)?(?:order|invoice|cart|user|account|policy|aggregate|entity|amount|total|balance|status|state)\b/i;function Il(e,t){if(!t||t.length<40)return null;let n=t.match(new RegExp(Al.source,"g"))??[],r=t.match(new RegExp(kl.source,"g"))??[],o=(t.match(/\bif\s*\(/g)??[]).length,s=(t.match(/\bswitch\s*\(/g)??[]).length,i=n.length>=2||n.length>=1&&r.length>=2||r.length>=3&&o+s>=6,l=ml.test(t),c=hl.test(t)||Rl.test(t),g=n.length>=1||r.length>=2,m=/\b(?:mapTo|toDomain|toDto|fromRow|toEntity|fromPrisma|serialize|deserialize)\w*\s*[(=]/.test(t),h=l&&g||c&&g||l&&m&&(o>=4||n.length>=1)||c&&l,p=l&&yl.test(t);return!i&&!h&&!p?null:{...i?{orchestrationHeavy:!0}:{},...h?{adapterThick:!0}:{},...p?{persistenceWrite:!0}:{}}}a(Il,"deriveArkRuleFileHints");function Ks(e){let t={};for(let[n,r]of Object.entries(e)){let o=Il(n,r);o&&(t[n.replace(/\\/g,"/")]=o)}return t}a(Ks,"buildArkRuleFileHints");function vl(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}}a(vl,"normalizeExtraMergeTeethClassification");function Cn(e){let t=vl(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}a(Cn,"extraMergeTeethAllowed");function Hs(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}}a(Hs,"classifyResolvedLayerCoverage");var El=["createArkKernel","createStrictArkKernel","createArkKernelFromConfig","createStrictArkKernelFromConfig"];var xf=new Set(El);function Gs(e){return e==="@arkgate/runtime"||e.startsWith("@arkgate/runtime/")||e==="arkgate/runtime"||e.startsWith("arkgate/runtime/")}a(Gs,"isArkRunKernelModuleSpecifier");var bl=["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"],_r=new Set(bl);function Us(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;if(_r.has(e))return!0;let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t);if(_r.has(n))return!0;let r=e.indexOf("/",t+1);return r<0?!1:_r.has(e.slice(0,r))}a(Us,"isArkRunTransportBypassSpecifier");var Sl=["arkrun-kernel-in-domain","arkrun-direct-new","arkrun-transport-bypass"],Mf=new Set(Sl);var Vs={"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"},Cl="ARKRUN_INTERACTION_NAME_INCOMPLETE";function Ws(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.")})}a(Ws,"isDomainRoleLayer");function wl(e,t){return e.file.localeCompare(t.file)||e.ruleId.localeCompare(t.ruleId)||e.line-t.line||e.message.localeCompare(t.message)}a(wl,"compareFindings");function ye(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Vs[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:le({ruleId:Vs[t],fromLayer:s?.fromLayer,target:s?.target})}}a(ye,"finding");function xl(e,t){let n=[],r=[],o=[],s=[];for(let i of e)i.file===t&&(n.push(...i.uses),r.push(...i.reactsTo),o.push(...i.raises),s.push(...i.sends));return{uses:new Set(n),reactsTo:new Set(r),raises:new Set(o),sends:new Set(s)}}a(xl,"bagForFile");function js(e){return e==="publisher"||e==="publish"||e==="raise"||e==="send"}a(js,"emitKinds");function Bs(e){return e==="subscribe"||e==="register-handler"}a(Bs,"handleKinds");function Ol(e){return e==="resolve"||e==="resolve-singleton"}a(Ol,"dependKinds");function Pl(e,t,n){let r=[],o=e.kernelRoots??e.compositionRoots;if(o.length===0)return r.push(ye(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 i of t){let l=s.get(i.matchedRoot)??[];l.push(i),s.set(i.matchedRoot,l)}for(let i of o){let l=[...s.get(i)??[]].sort((g,m)=>g.file.localeCompare(m.file));if(l.length===0){r.push(ye(e,"arkrun-missing-root","ark.config.json",1,`ArkRun kernel root ${JSON.stringify(i)} matched no governed files and has no createArkKernel factory.`,{target:i},n));continue}if(l.some(g=>g.hasKernelFactory))continue;let c=l[0];r.push(ye(e,"arkrun-missing-root",c.file,1,`ArkRun kernel root ${JSON.stringify(i)} has no createArkKernel / createStrictArkKernel factory.`,{target:i},n))}return r}a(Pl,"evaluateMissingRoot");function _l(e,t,n,r,o){let s=new Map(t.map(l=>[l.name,l.intentPrefixes??[]])),i=[];for(let l of n){let c=l.specifier;if(!c||!Gs(c))continue;let g=r(l.from);g&&Ws(g,s.get(g)??[])&&i.push(ye(e,"arkrun-kernel-in-domain",l.from,l.line,`${g} must not import kernel module ${JSON.stringify(c)}.`,{fromLayer:g,target:c},o))}return i}a(_l,"evaluateKernelInDomain");function Nl(e,t,n,r,o,s){let i=new Set(e.managedLayers);if(i.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)),g=[];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 p=o(m.file);!p||!i.has(p)||Ws(p,l.get(p)??[])||g.push(ye(e,"arkrun-direct-new",m.file,m.line,`${p} must not construct ${m.typeName} with new outside an ArkRun composition-root factory.`,{fromLayer:p,target:m.typeName},s))}return g}a(Nl,"evaluateDirectNew");function Tl(e,t,n,r,o){let s=[],i=[];if(e.requireDeclarations!==!0)return{findings:s,completenessReasons:i};let l=new Set(e.managedLayers);if(l.size===0)return{findings:s,completenessReasons:i};for(let c of t){if(!js(c.kind)&&!Bs(c.kind)&&!Ol(c.kind))continue;let g=r(c.file);if(!g||!l.has(g))continue;if(!c.nameLiteral){e.mode==="enforced"&&i.push({code:Cl,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=xl(n,c.file);if(js(c.kind)){if(m.raises.has(c.nameLiteral)||m.sends.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-emit",c.file,c.line,`Emit ${JSON.stringify(c.nameLiteral)} is not declared in raises or sends.`,{fromLayer:g,target:c.nameLiteral},o));continue}if(Bs(c.kind)){if(m.reactsTo.has(c.nameLiteral))continue;s.push(ye(e,"arkrun-undeclared-handle",c.file,c.line,`Handle ${JSON.stringify(c.nameLiteral)} is not declared in reactsTo.`,{fromLayer:g,target:c.nameLiteral},o));continue}m.uses.has(c.nameLiteral)||s.push(ye(e,"arkrun-undeclared-depend",c.file,c.line,`Depend ${JSON.stringify(c.nameLiteral)} is not declared in uses.`,{fromLayer:g,target:c.nameLiteral},o))}return{findings:s,completenessReasons:i}}a(Tl,"evaluateUndeclared");function Dl(e,t,n,r){let o=new Set(e.managedLayers);if(o.size===0)return[];let s=[];for(let i of t){if(i.typeOnly)continue;let l=i.specifier;if(!l||!Us(l))continue;let c=n(i.from);!c||!o.has(c)||s.push(ye(e,"arkrun-transport-bypass",i.from,i.line,`${c} must not import broker/queue/emitter ${JSON.stringify(l)}; use the ArkRun kernel transport.`,{fromLayer:c,target:l},r))}return s}a(Dl,"evaluateTransportBypass");function qs(e){let t=e.arkRun;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=Tl(t,e.kernelCalls,e.declarations,e.layerForFile,n),o=[...Pl(t,e.compositionRootHits,n),..._l(t,e.layers,e.dependencies,e.layerForFile,n),...Nl(t,e.layers,e.managedNews,e.compositionRootHits,e.layerForFile,n),...r.findings,...Dl(t,e.dependencies,e.layerForFile,n)].sort(wl),s=[...r.completenessReasons].sort((i,l)=>{let c=`${i.code}\0${i.file??""}\0${i.message}`,g=`${l.code}\0${l.file??""}\0${l.message}`;return c<g?-1:c>g?1:0});return{findings:o,completenessReasons:s}}a(qs,"evaluateArkRunSensors");function zs(e){return e==="arkgate/order"||e.startsWith("arkgate/order/")}a(zs,"isArkOrderModuleSpecifier");var Ys={"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 Ll(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.")})}a(Ll,"isDomainRoleLayer");function he(e,t,n,r,o,s,i){let l=e.mode==="enforced"&&i;return{ruleId:Ys[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:le({ruleId:Ys[t],fromLayer:s?.fromLayer,target:s?.target})}}a(he,"finding");function Xs(e){let t=e.arkOrder;if(!t)return{findings:[],completenessReasons:[]};let n=Cn(e.classification),r=[],o=t.planeRoots;if(t.mode==="enforced"&&o.length===0)r.push(he(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 g of e.planeRootHits){let m=c.get(g.matchedRoot)??[];m.push(g),c.set(g.matchedRoot,m)}for(let g of o){let m=c.get(g)??[];if(m.length===0){r.push(he(t,"arkorder-missing-plane","ark.config.json",1,`ArkOrder plane root ${JSON.stringify(g)} matched no governed files and has no createOrderPlane factory.`,{target:g},n));continue}m.some(h=>h.hasPlaneFactory)||r.push(he(t,"arkorder-missing-plane",m[0].file,1,`ArkOrder plane root ${JSON.stringify(g)} has no createOrderPlane factory.`,{target:g},n))}}let s=new Map(e.layers.map(c=>[c.name,c.intentPrefixes??[]]));for(let c of e.dependencies){let g=c.specifier;if(!g||!zs(g))continue;let m=e.layerForFile(c.from);m&&Ll(m,s.get(m)??[])&&r.push(he(t,"arkorder-kernel-in-domain",c.from,c.line,"Domain-role layer imports arkgate/order; Domain stays plane-free.",{fromLayer:m,target:g},n))}for(let c of e.genericUpdates)r.push(he(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 i=t.xiKeys??[];i.length>t.maxXiKeys&&r.push(he(t,"arkorder-too-many-params","ark.config.json",1,`arkOrder.xiKeys has ${i.length} keys; maxXiKeys is ${t.maxXiKeys} (few slow modes).`,{target:String(i.length)},n));for(let c of e.releaseKeyCounts??[])c.keyCount<=t.maxXiKeys||r.push(he(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(he(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 i.length===0?[]:e.xiFieldWrites??[]){let g=e.layerForFile(c.file);!g||!l.has(g)||r.push(he(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:g,target:c.key},n))}return r.sort((c,g)=>c.file.localeCompare(g.file)||c.ruleId.localeCompare(g.ruleId)||c.line-g.line),{findings:r,completenessReasons:[]}}a(Xs,"evaluateArkOrderSensors");function Z(e,t,n={}){return{ruleId:e,message:t,...n}}a(Z,"configWarning");function wn(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(Z("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(Z("CONFIG_INVALID_SAFETY","safety must be an object."));else if(t.safety)for(let f of["maxTsSuppressions","maxAnyCasts"]){let u=t.safety[f];u!==void 0&&(!Number.isInteger(u)||u<0)&&s.push(Z("CONFIG_INVALID_SAFETY_THRESHOLD",`safety.${f} must be a non-negative integer.`))}let i=Array.isArray(t.layers)?t.layers:[],l=Array.isArray(o?.architecture?.layers)?o.architecture.layers:[],c=new Set([...i.map(f=>f.name).filter(Boolean),...l.map(f=>f.name).filter(f=>!!f)]);i.length===0&&s.push(Z("CONFIG_NO_LAYERS","No file layers are configured; ark-check cannot classify files for import-boundary enforcement."));let g=new Set,m=new Set;for(let f of i){if(!f.name){s.push(Z("CONFIG_LAYER_WITHOUT_NAME","A configured layer is missing a name."));continue}g.has(f.name)&&m.add(f.name),g.add(f.name),f.forbiddenGlobals!==void 0&&(!Array.isArray(f.forbiddenGlobals)||f.forbiddenGlobals.some(y=>typeof y!="string"))&&s.push(Z("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 u=Array.isArray(f.patterns)?f.patterns:[];if(u.length===0){s.push(Z("CONFIG_LAYER_WITHOUT_PATTERNS",`Layer "${f.name}" has no file patterns and will never classify files.`,{layer:f.name}));continue}for(let y of u){let E;try{E=pe(y)}catch(A){s.push(Z("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 b=f.optional===!0||f.reserved===!0||f.allowEmpty===!0;!r.some(A=>E.test(A))&&!b&&s.push(Z("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(Z("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(Z("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(Z("CONFIG_RULE_UNKNOWN_TO_LAYER",`Rule references unknown target layer "${f.to}".`,{fromLayer:f.from,toLayer:f.to}));let h=new Set;if(i.length>1)for(let f of r){let u=-1,y=[];for(let E of i)for(let b of E.patterns??[]){if(!pe(b).test(f))continue;let A=rr(b,f);A>u?(u=A,y=[E.name]):A===u&&!y.includes(E.name)&&y.push(E.name)}y.length>1&&h.add([...y].sort().join(" + "))}h.size>0&&s.push(Z("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 p=r.filter(f=>!ae(f,i));return p.length>0&&s.push(Z("CONFIG_UNCLASSIFIED_FILES",`${p.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,{count:p.length,samples:p.slice(0,5)})),s}a(wn,"collectAnalysisConfigWarnings");function Fl(e,t){return t.some(n=>{try{return pe(n).test(e)}catch{return!1}})}a(Fl,"matchesAny");function $l(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??[],i=t.safetyUses.filter(y=>y.kind==="ts-suppression").map(({file:y,line:E})=>({file:y,line:E})),l=t.safetyUses.filter(y=>y.kind==="any-cast").map(({file:y,line:E})=>({file:y,line:E})),c=t.safetyUses.filter(y=>(y.kind==="dynamic-import"||y.kind==="dynamic-require")&&!Fl(y.file,s)).map(y=>({file:y.file,line:y.line,kind:y.kind==="dynamic-require"?"require":"import"})),g=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:i,anyCasts:l,nonLiteralDynamicImports:c,inMemoryProductionStores:g,disabledPeerIsolationRules:m,thresholds:{maxTsSuppressions:r,maxAnyCasts:o}},p=[],f=c.filter(y=>y.kind==="import");if(f.length>0){let y=f[0];p.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 u=c.filter(y=>y.kind==="require");if(u.length>0){let y=u[0];p.push({ruleId:"DYNAMIC_REQUIRE_NOT_ALLOWLISTED",file:y.file,line:y.line,message:`${u.length} non-literal require call(s) cannot be resolved statically. Add only reviewed files to dynamicImportAllowlist.`})}if(i.length>r){let y=i[0];p.push({ruleId:"TS_SUPPRESSION_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${i.length} @ts-ignore/@ts-nocheck directive(s) exceed safety.maxTsSuppressions (${r}).`})}if(l.length>o){let y=l[0];p.push({ruleId:"ANY_CAST_THRESHOLD_EXCEEDED",file:y.file,line:y.line,message:`${l.length} explicit any cast(s) exceed safety.maxAnyCasts (${o}).`})}if(g.length>0){let y=g[0];p.push({ruleId:"IN_MEMORY_STORE_IN_PRODUCTION_SOURCE",file:y.file,line:y.line,message:`${g.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&&p.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:p}}a($l,"evaluateSafety");function Ml(e,t){return[...t].filter(n=>e===n||e.startsWith(`${n}.`)).sort((n,r)=>r.length-n.length)[0]}a(Ml,"ambientForbiddenGlobal");function Zs(e,t){let n=t.config.layers.filter(r=>(r.intentPrefixes??[]).length>0);return kr(e,n.length>0?n:Ar.map(r=>({name:r.layer,prefixes:r.prefixes})))}a(Zs,"intentLayer");function Kl(e,t,n){let r=[],o=new Map(e.contract.config.layers.map(s=>[s.name,s]));for(let s of t.ambientUses){let i=n.get(s.file);!i||!Ml(s.symbol,o.get(i)?.forbiddenGlobals??[])||r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,message:`${i} must not use the ambient global "${s.symbol}".`})}for(let s of t.capabilityUses){let i=n.get(s.file);if(!i)continue;let l=o.get(i),c=l?.forbiddenGlobals??[],g=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"&&yt(s.symbol,c))){if(s.source==="import-based"){let m=Ie(s.symbol,c);if(m){r.push({ruleId:"FORBIDDEN_GLOBAL",file:s.file,line:s.line,fromLayer:i,target:s.symbol,...g?{edgeKind:g}:{},message:`${i} must not use module "${s.symbol}" because it is the import form of forbidden global "${m}".`});continue}}We(l).includes(s.capability)&&r.push({ruleId:"CAPABILITY_VIOLATION",file:s.file,line:s.line,fromLayer:i,target:s.symbol,capability:s.capability,...g?{edgeKind:g}:{},message:s.source==="import-based"?`${i} denies the ${s.capability} capability; found import of "${s.symbol}".`:`${i} denies the ${s.capability} capability; found ambient "${s.symbol}".`})}}for(let s of t.publishCalls){let i=n.get(s.file);if(!i)continue;for(let c of ht({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:i}:{},message:c.message});if(!s.sourceIntent)continue;let l=Zs(s.sourceIntent,e.contract);!l||l===i||r.push({ruleId:"PUBLISH_SOURCE_LAYER_MISMATCH",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.sourceIntent,message:`Publish source "${s.sourceIntent}" resolves to ${l}, but the publishing file is classified as ${i}.`})}for(let s of t.intentReferences){let i=n.get(s.file);if(!i)continue;let l=Zs(s.intent,e.contract);if(!l)continue;let c=ue(e.contract.config.rules,i,l);c&&r.push({ruleId:"LAYER_INTENT_REFERENCE_VIOLATION",file:s.file,line:s.line,fromLayer:i,toLayer:l,target:s.intent,message:c.message??`${i} must not reference ${l} intent ${s.intent}.`})}return r}a(Kl,"contentViolations");function Hl(e){let{facts:t}=e,n=It(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,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),i=t.files.map(d=>({...d,layer:ae(d.path,e.contract.config.layers)??null})),l=new Map(i.map(d=>[d.path,d.layer])),c=t.dependencies.map(d=>{let N=d.target?l.get(d.target)??ae(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,...N?{toLayer:N}:{}}:{},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}:{}}}),g=wn({config:e.contract.config,rules:e.contract.config.rules,files:i.map(d=>d.path)}),m=$l(e,t),h=e.contract.arkRules??Et(),p=i.map(d=>d.path),u={...e.coverageInputs?.fileContents&&Object.keys(e.coverageInputs.fileContents).length>0?Ks(e.coverageInputs.fileContents):{},...e.fileHints??{}},y=[...$s({arkRules:h,classShapes:e.contract.classShapes??t.classShapes??[],files:p,layerForFile:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),fileHints:u}),...Ms(h,p)],E=y.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:d.ruleId==="ARKRULE_SCOPE_EMPTY"?`Fix appliesTo globs for ${d.arkruleId} in ${d.arkruleSource} so they match governed files, or remove the rule.`:`Fix the structure or invariant for ${d.arkruleId} (declared in ${d.arkruleSource}), then preflight again.`})),b=y.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==="ARKRULE_SCOPE_EMPTY"?`Review appliesTo for ${d.arkruleId} in ${d.arkruleSource} (zero-match scope; advisory).`:`Review ArkRule ${d.arkruleId} in ${d.arkruleSource} (advisory).`})),v=(h.invariants?.length??0)>0?vs({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},P=v.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.`})),j=v.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).`})),k=Hs(i),_=qs({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:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),z=e.contract.config.arkRun?.mode,de=_.findings.filter(()=>z==="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}:{}})),Bt=_.findings.filter(()=>z!=="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})),Ne=Xs({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:a(d=>l.get(d)??ae(d,e.contract.config.layers),"layerForFile"),classification:k}),qn=e.contract.config.arkOrder?.mode,Wt=Ne.findings.filter(()=>qn==="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}:{}})),ao=Ne.findings.filter(()=>qn!=="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})),at=[...v.partial&&v.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."}]:[],..._.completenessReasons,...Ne.completenessReasons],Ee=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.filter(d=>d.layer).map(d=>d.path),contentViolations:[...Kl(e,t,l),...E,...P,...de,...Wt],edges:c,warnings:[...g,...m.warnings,...b,...j,...Bt,...ao],safety:m.report}),qt=o==="complete"&&at.length>0?"partial":o,Yn=qt==="complete"?s:[...s,...at].sort((d,N)=>{let L=`${d.code}\0${d.file??""}\0${d.message}`,te=`${N.code}\0${N.file??""}\0${N.message}`;return L<te?-1:L>te?1:0}),S=Ee.violations.filter(d=>d.failsStrict!==!1),C=qt==="complete"&&S.length===0,R=C&&Ee.warnings.every(d=>d.failsStrict===!1);return{mode:"resolved-candidate-facts",completeness:qt,completenessReasons:Yn,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:i,layers:e.contract.config.layers.map(d=>d.name),edges:c,capabilityUses:t.capabilityUses,violations:Ee.violations,warnings:Ee.warnings}}}a(Hl,"analyzeCanonicalResolvedProject");function wt(e){return Hl({contract:e.contract,facts:ve(e.facts),coverageInputs:e.coverageInputs,fileHints:e.fileHints})}a(wt,"analyzeResolvedProject");function Js(e){return B(F(e.map(({path:t,contentHash:n})=>({path:t,contentHash:n}))))}a(Js,"analysisTreeHash");function Qs(e){let t=Ct(e),n=new Map(t.ir.files.map(u=>[u.path,u])),r=[],o=new Set,s=[];for(let u of e.changes){let y=u.path.replace(/\\/g,"/"),E=Oe(u.path);if(!E||E===".."||E.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(E)){s.push({ruleId:"DUPLICATE_CHANGE_PATH",file:E,line:1,message:`The atomic change set contains more than one operation for ${E}.`});continue}o.add(E),"delete"in u&&u.delete&&!n.has(E)&&s.push({ruleId:"DELETE_TARGET_MISSING",file:E,line:1,message:`Cannot delete ${E} because it is not present in the supplied base tree.`}),r.push("delete"in u&&u.delete?{path:E,delete:!0}:{path:E,content:"content"in u?u.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 i=En({...e,changes:r}),l=new Map(i.ir.files.map(u=>[u.path,u])),c=i.ir.violations.filter(u=>u.ruleId==="CAPABILITY_VIOLATION"||u.ruleId==="FORBIDDEN_GLOBAL").map(u=>{let y=l.get(u.evidence.file)?.layer;return{ruleId:u.ruleId,file:u.evidence.file,line:u.evidence.line,target:u.symbol,...u.capability?{capability:u.capability}:{},...y?{fromLayer:y}:{},edgeKind:"import",message:u.message}}),g=Qe({config:e.contract.config,rules:e.contract.config.rules,files:i.ir.files.map(u=>u.path),contentViolations:c,edges:i.ir.edges.filter(u=>!!u.fromLayer).map(u=>({from:u.from,fromLayer:u.fromLayer,...u.to?{to:u.to}:{},...u.toLayer?{toLayer:u.toLayer}:{},line:u.evidence.line,kind:"import",...u.typeOnly?{typeOnly:!0}:{},...u.namedBindingsTypeOnly?{namedBindingsTypeOnly:!0}:{}}))}),m=r.map(u=>{let y=Oe(u.path),E=n.get(y),b=l.get(y);return{path:y,operation:"delete"in u&&u.delete?"delete":E?"update":"create",...E?{beforeContentHash:E.contentHash}:{},...b?{candidateContentHash:b.contentHash}:{}}}).sort((u,y)=>u.path.localeCompare(y.path)),h=[...s,...g.violations].map(u=>({...u,nextAction:le(u)})),p=h.filter(u=>u.failsStrict!==!1),f=e.changeMap?Je({changeMap:e.changeMap,changes:m,baseDependencies:t.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[]),candidateDependencies:i.ir.edges.flatMap(u=>u.to?[{from:u.from,to:u.to}]:[])}):void 0;return{schemaVersion:"1.0",mode:"lexical-compatibility",valid:t.completeness==="complete"&&i.valid&&p.length===0&&(f?.structurallyConverged??!0),readOnly:!0,policyHash:e.contract.policyHash,compilerOptionsHash:i.ir.compilerOptionsHash,baseTreeHash:Js(t.ir.files),candidateTreeHash:Js(i.ir.files),baseCompleteness:t.completeness,candidateCompleteness:i.completeness,baseCompletenessReasons:t.completenessReasons,candidateCompletenessReasons:i.completenessReasons,...e.changeMap?{changeMapHash:e.changeMap.hash}:{},...f?{convergence:f}:{},changes:m,violations:h,warnings:g.warnings}}a(Qs,"preflightChange");function Gl(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}a(Gl,"canonicalChangePath");function Ul(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}.`}))}a(Ul,"identityViolations");function Vl(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}:{}}}a(Vl,"preparedChange");function ea(e){let t=ve(e.baseFacts),n=ve(e.candidateFacts),r=wt({contract:e.contract,facts:t}),o=wt({contract:e.contract,facts:n}),s=new Map(t.files.map(f=>[f.path,f])),i=new Map(n.files.map(f=>[f.path,f])),l=Ul(t,n),c=new Map,g=[];for(let f of e.changes){let u=Gl(f.path);if(!u){l.push({ruleId:"INVALID_CHANGE_PATH",file:"<change-set>",line:1,message:"Every change requires a canonical project-relative path."});continue}if(c.has(u)){l.push({ruleId:"DUPLICATE_CHANGE_PATH",file:u,line:1,message:`The atomic change set contains more than one operation for ${u}.`});continue}c.set(u,f);let y=s.get(u),E=i.get(u);if("delete"in f&&f.delete)y||l.push({ruleId:"DELETE_TARGET_MISSING",file:u,line:1,message:`Cannot delete ${u} because it is not present in the supplied base facts.`}),E&&l.push({ruleId:"CANDIDATE_DELETE_NOT_APPLIED",file:u,line:1,message:`Candidate facts still contain deleted file ${u}.`});else{let b="content"in f?f.content:"",A=B(b);E?E.contentHash!==A&&l.push({ruleId:"CANDIDATE_CONTENT_HASH_MISMATCH",file:u,line:1,expectedContentHash:A,candidateContentHash:E.contentHash,message:`Candidate facts for ${u} do not match the declared content.`}):l.push({ruleId:"CANDIDATE_CHANGE_MISSING",file:u,line:1,message:`Candidate facts do not contain changed file ${u}.`})}g.push(Vl(f,u,s,i))}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(),...i.keys()])){if(c.has(f))continue;let u=s.get(f),y=i.get(f);u&&y&&F(u)===F(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?Je({changeMap:e.changeMap,changes:g,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:le(f)})),p=h.filter(f=>f.failsStrict!==!1);return{schemaVersion:"1.0",mode:"resolved-candidate-facts",valid:r.completeness==="complete"&&o.strictValid&&p.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:g.sort((f,u)=>f.path<u.path?-1:f.path>u.path?1:0),violations:h,warnings:o.ir.warnings}}a(ea,"preflightResolvedChange");var Nr="docs/diagnostics.md",jl="1.0";function I(e,t,n,r,o,s){return{ruleId:e,title:n,why:r,fix:o,docsAnchor:e,category:t,...s?.oftenAdvisory?{oftenAdvisory:!0}:{}}}a(I,"entry");var xn=Object.freeze([I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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."),I("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}),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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."),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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}),I("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."),I("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}),I("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.")]),Tr=new Map(xn.map(e=>[e.ruleId,e])),Bl=Object.freeze(xn.map(e=>e.ruleId));function Wl(e){return typeof e=="string"&&e.length>0&&Tr.has(e)}a(Wl,"isKnownDiagnosticCode");function ql(e){return typeof e!="string"||e.length===0?!1:Tr.has(e)?!0:e.startsWith("ARKRULE_")}a(ql,"isCataloguedOrArkRuleFamily");function On(e){if(!(typeof e!="string"||e.length===0))return Tr.get(e)}a(On,"getDiagnosticCatalogEntry");function ta(e){return`#${On(e)?.docsAnchor??e}`}a(ta,"diagnosticDocsFragment");function zl(e){return`${Nr}${ta(e)}`}a(zl,"diagnosticDocsPath");function Yl(){return{schemaVersion:"1.0",docsPath:Nr,codes:xn}}a(Yl,"serializeDiagnosticCatalog");function Xl(e){return On(e)?.fix}a(Xl,"catalogFixForRuleId");function Zl(e){return On(e)?.why}a(Zl,"catalogWhyForRuleId");var Jl="1.1";var Ql="1.0";var xt=class{static{a(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 ec(e){return typeof e.initialState=="function"?e.initialState():e.initialState}a(ec,"initialState");var Pn=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(t={}){this.store=t.store??new xt,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)??ec(r),s=await r.project(t,o);await this.store.save(r.name,s);let i=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(i?.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 _n(e){return new Pn(e)}a(_n,"createProjectionRegistry");var Nn="1.0";function tc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(tc,"policyId");var Dr=class{constructor(t){this.data=t}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function Tn(e={}){let t=e.registry,n=e.policyEngine,r=e.metadata,o=e.graph,s=e.profile,i=e.projections,l=e.eventContracts,c=e.observability,g=t?t.list().map(b=>({name:b.name,dependencies:t.getDependencies(b.name),productions:t.getProductions(b.name)})):[],m=t?t.getAllRelationships():[],h=n?n.getPolicies().map(b=>({id:tc(b.name),name:b.name,severity:b.severity,tags:b.tags?[...b.tags]:void 0,owner:b.owner,version:b.version,rationale:b.rationale,enforcementMode:b.enforcementMode,deprecated:b.deprecated,replacedBy:b.replacedBy,description:b.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],p=r?r.toJSON():[],f=o?o.toJSON():{nodes:[],edges:[]},u=p.filter(b=>(b.emits?.length??0)>0||(b.consumes?.length??0)>0).map(b=>({entity:b.name,emits:b.emits,consumes:b.consumes})),y=i?i.list().map(b=>({name:b.name,sourceIntents:b.sourceIntents,checkpoint:i.getCheckpoint(b.name)})):[],E={schemaVersion:"1.0",version:Zn,exportedAt:new Date().toISOString(),intents:g,relationships:m,policies:h,entities:p,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:u}};return new Dr(E)}a(Tn,"createArkManifest");var na=0;function ra(e){return na+=1,`${e}-${Date.now()}-${na}`}a(ra,"createWorkflowId");function Lr(e){return e instanceof Error?e.message:String(e)}a(Lr,"errorMessage");function nc(e){return new Promise(t=>{setTimeout(t,e)})}a(nc,"sleep");async function rc(e,t,n){let r=new AbortController;if(t===void 0)return e(r.signal);let o,s=new Promise((i,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)}}a(rc,"withTimeout");var Ot=class{static{a(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 i=s.expiresAt?new Date(s.expiresAt).getTime()<o:!0;if(!s.ownerId||i){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()}},Fr=class{constructor(t,n={}){this.bus=t;this.options=n;this.store=n.store??new Ot}bus;options;static{a(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(),i={id:r.id??ra(t),version:0,workflowName:t,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:s,updatedAt:s};return await this.store.save(i,r.tx),await this.audit("workflow.started",i,{workflowName:t}),this.executeSnapshot(i,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=Lr(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 i=1;i<=s;i+=1){t.attempts[n.name]=i,await this.store.save(t,r);let l;try{l=await rc(c=>Promise.resolve(n.execute(t.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(i<s){o.delayMs&&await nc(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:i,error:Lr(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:i});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(i=>t.completedSteps.includes(i.name));for(let i=s.length-1;i>=0;i-=1){let l=s[i];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:Lr(c)})}}}async audit(t,n,r){await this.options.auditTrail?.record({type:t,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Pt(e,t){return new Fr(e,t)}a(Pt,"createWorkflowEngine");function oa(e,t,n={}){let r=Pt(t,n),o={name:e.name,steps:e.steps};r.register(o);let s=n.id??ra(e.name),i="idle",l=[];return{id:s,definition:e,get status(){return i},get completedSteps(){return[...l]},async run(c){i="running",l=[];try{let g=await r.start(e.name,c,{id:s});i=g.status==="waiting"?"idle":g.status,l=[...g.completedSteps]}catch(g){let m=await r.get(s);throw i=m?.status==="waiting"?"idle":m?.status??"failed",l=m?.completedSteps??[],g}}}}a(oa,"createSaga");tt();function la(e){return Object.keys(e).sort()}a(la,"sortedKeys");function Gr(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:[],g=Math.max(l.length,c.length);for(let m=0;m<g;m+=1)Gr(l[m],c[m],`${n}[${m}]`,r);return}let o=e,s=t,i=new Set([...la(o),...la(s)]);for(let l of[...i].sort())Gr(o[l],s[l],n?`${n}.${l}`:l,r)}a(Gr,"walk");function ca(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}}))}:{}}}a(ca,"shadowInformationPackage");function Ur(e,t){let n=[];return Gr(e,t,"",n),{equal:n.length===0,diffs:n}}a(Ur,"compareInformationPackages");function da(e){let t=[];for(let n=1;n<e.length;n+=1)t.push(Ur(e[n-1],e[n]));return t}a(da,"replayInformationPackages");Hn();$t();Vt();Vt();async function Wn(e,t={}){let n=Gt({host:t.host,port:t.port,nodeEnv:t.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await Promise.resolve().then(()=>(ba(),Ea));return r(e,{bind:n,sseIntervalMs:t.sseIntervalMs})}a(Wn,"startArkRunInspector");Hn();Vt();tt();$t();tt();var Dc=new Set(["singleton","transient"]);function Sa(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}a(Sa,"cloneComponent");function Lc(e){if(e===void 0)return"singleton";if(typeof e=="string"&&Dc.has(e))return e;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Lc,"closedLifetime");function Ca(){let e=new Map,t=new Map,n=new Set;function r(i){let l=e.get(i);if(!l)throw new Error(`ArkRun component "${i}" is not registered.`);return l}a(r,"mustRecord");function o(i,l){if(!l.factory)throw new Error(`ArkRun component "${i}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(i))throw new Error(`ArkRun component "${i}" has a circular resolve.`);n.add(i);try{return l.factory()}finally{n.delete(i)}}a(o,"instantiate");function s(i,l){if(t.has(i))return t.get(i);let c=o(i,l);return t.set(i,c),c}return a(s,"singleton"),{register(i){let l=typeof i?.id=="string"?i.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=Lc(i.lifetime),g=Kr({id:l,lifetime:c,uses:i.uses,reactsTo:i.reactsTo,raises:i.raises,sends:i.sends,extendedInfo:i.extendedInfo});if(!g)throw new Error("ArkRun component id must be a non-empty string.");let m=typeof i.factory=="function"?i.factory:void 0;return e.set(l,{component:g,factory:m}),Sa(g)},resolve(i){let l=r(i);return l.component.lifetime==="transient"?o(i,l):s(i,l)},resolveSingleton(i){let l=r(i);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${i}" is transient; resolveSingleton requires lifetime "singleton".`);return s(i,l)},snapshotComponents(){return[...e.values()].map(i=>Sa(i.component))}}}a(Ca,"createComponentRegistry");$t();function Fc(e){let t={...e.metadata??{}};if(e.source===void 0)return t;if(t.source&&t.source!==e.source)throw new ke(e.source,t.source);return t.source=e.source,t}a(Fc,"stampMetadata");function $c(){}a($c,"ignoreDetachedFailure");async function to(e,t,n,r={}){let o=Gn({transport:r.transport,ephemeral:r.ephemeral??e.defaultEphemeral,brokerBound:typeof e.broker?.send=="function"}),s=Fc(r),i=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(i));o.awaitHandoff?await l:l.then(void 0,$c)}return o}a(to,"sendOnArkRunTransport");var no=1e3,wa=0;function Mc(){return wa+=1,`ark-kernel-${Date.now()}-${wa}`}a(Mc,"nextKernelInstanceId");function jt(e={}){let t=e.strict??!0,n=e.instanceId??Mc(),r=e.profile??Be,o=e.maxHistorySize??no,s=Yt(),i=cn(),l=e.metadata??hn(),c=e.auditTrail??an({maxRecords:o}),g=e.eventContracts??rn(),m=e.eventBuffer??e.outbox??new Ce,h=e.projections??_n({auditTrail:c}),p=new be([Qt(r),...e.policies??[]]),f=a(()=>{dn(s,i,{requireRegisteredTargets:!0})},"syncGraph"),u=e.ephemeral??!0,y=e.broker,E=new Ue({intentRegistry:s,dependencyGraph:i,policyEngine:p,strictRegistry:!0,validateIntentNaming:!0,auditTrail:c,eventContracts:g,strictEventContracts:e.strictEventContracts??t,requireKnownSource:e.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:e.enforceObservedLayerFlow??(t?"hard":"off"),eventBuffer:m,instanceId:n,maxHistorySize:o,onPublish:e.autoApplyProjections===!1?void 0:async k=>{await h.apply(k)}}),b=Pt(E,{auditTrail:c}),A=on({registry:s,eventBus:E,graph:i}),v=Ca(),P=typeof y?.send=="function",j={instanceId:n,profile:r,registry:s,graph:i,metadata:l,auditTrail:c,eventContracts:g,eventBuffer:m,outbox:m,projections:h,policyEngine:p,eventBus:E,workflowEngine:b,observability:A,publisher(k){let _=E.createPublisher(k);return{source:_.source,publish:_.publish,send(z,de,Bt={}){return to({eventBus:E,broker:y,defaultEphemeral:u},z,de,{...Bt,source:_.source})}}},send(k,_,z={}){return to({eventBus:E,broker:y,defaultEphemeral:u},k,_,z)},register(k){return v.register(k)},resolve(k){return v.resolve(k)},resolveSingleton(k){return v.resolveSingleton(k)},getDependencyInformationPackage(){return Re({kernelInstanceId:n,components:v.snapshotComponents()})},requestGraph(k){return Kn({kernelInstanceId:n,components:v.snapshotComponents()},k)},getInspectorSnapshot(k){return jn({kernelInstanceId:n,host:k?.host,port:k?.port,package:{kernelInstanceId:n,components:v.snapshotComponents()},observability:A.report(),ephemeralDefault:u,brokerBound:P})},startInspector(k){return Wn(j,k)},syncGraph:f,manifest(){return f(),Tn({registry:s,policyEngine:p,metadata:l,graph:i,profile:r,projections:h,eventContracts:g,observability:A})}};return j}a(jt,"createArkKernel");function ro(e={}){return jt({...e,strict:!0,strictEventContracts:e.strictEventContracts??!0,requireKnownSource:e.requireKnownSource??!0,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"hard"})}a(ro,"createStrictArkKernel");function oo(e,t={}){let{profileName:n,...r}=t;return{...r,profile:mn(e,{name:n})}}a(oo,"createOptionsFromConfig");function xa(e,t={}){return jt(oo(e,t))}a(xa,"createArkKernelFromConfig");function Oa(e,t={}){return ro(oo(e,t))}a(Oa,"createStrictArkKernelFromConfig");function Pa(e,t={}){return so(oo(e,t))}a(Pa,"createLenientArkKernelFromConfig");function so(e={}){return jt({...e,strict:!1,strictEventContracts:e.strictEventContracts??!1,enforceObservedLayerFlow:e.enforceObservedLayerFlow??"off"})}a(so,"createLenientArkKernel");export{Er as ANALYSIS_IR_SCHEMA_VERSION,ja as ARK_ANALYSIS_RESULT_SCHEMA,Qn as ARK_ANALYSIS_RESULT_SCHEMA_VERSION,Ql as ARK_DESIGN_DELTA_SCHEMA_VERSION,Jl as ARK_ENFORCEMENT_STATE_SCHEMA_VERSION,$r as ARK_RUN_COMPONENT_LIFETIMES,rt as ARK_RUN_EPHEMERAL_DEFAULT,Wr as ARK_RUN_GRAPH_DEFAULT_SLICE,ma as ARK_RUN_GRAPH_NODE_KINDS,ya as ARK_RUN_GRAPH_PROCESS_EDGE_KINDS,Br as ARK_RUN_GRAPH_SCHEMA_VERSION,qr as ARK_RUN_GRAPH_SLICES,ha as ARK_RUN_GRAPH_TECHNICAL_EDGE_KINDS,Dn as ARK_RUN_INFORMATION_PACKAGE_SCHEMA_VERSION,Un as ARK_RUN_INSPECTOR_DEFAULT_HOST,Jr as ARK_RUN_INSPECTOR_DEFAULT_PORT,Kt as ARK_RUN_INSPECTOR_EVENTS_PATH,Ht as ARK_RUN_INSPECTOR_GRAPH_PATH,Zr as ARK_RUN_INSPECTOR_SCHEMA_VERSION,Mt as ARK_RUN_INSPECTOR_SNAPSHOT_PATH,Qr as ARK_RUN_INSPECTOR_SSE_EVENT,eo as ARK_RUN_INSPECTOR_TRANSPORT_FALLBACK,Ft as ARK_RUN_TRANSPORT_KINDS,se as ArkRunInspectorBindError,ot as ArkRunInspectorProductionError,no as DEFAULT_MAX_HISTORY_SIZE,xn as DIAGNOSTIC_CATALOG,jl as DIAGNOSTIC_CATALOG_SCHEMA_VERSION,Nr as DIAGNOSTIC_DOCS_RELATIVE_PATH,Bl as DIAGNOSTIC_RULE_IDS,pt as EventContractRegistryImpl,Me as EventContractViolationError,ut as InMemoryAuditStore,Ce as InMemoryEventBuffer,Ko as InMemoryOutboxStore,xt as InMemoryReadModelStore,Ot as InMemoryWorkflowStore,Te as IntentRegistry,J as InvalidArkRunGraphQueryError,nt as InvalidArkRunSendOptionError,Fe as InvalidIntentNameError,$e as LayerPolicyContextError,Nn as MANIFEST_SCHEMA_VERSION,Ke as ObservedLayerFlowViolationError,wr as POLICY_DELTA_SCHEMA_VERSION,be as PolicyEngine,Ae as PolicyViolationError,vr as RESOLVED_CANDIDATE_FACTS_SCHEMA,xe as RESOLVED_CANDIDATE_FACTS_SCHEMA_VERSION,ke as SourceMetadataOverrideError,Se as UnknownEventSourceError,Le as UnregisteredIntentError,Je as analyzeArchitectureConvergence,En as analyzeChange,Ts as analyzePolicyDelta,Ct as analyzeProject,wt as analyzeResolvedProject,ia as appendDecisionTape,er as architecturalPolicies,Mn as arkRunGraphQueryFromSearchParams,_e as arkRunInspectorUrl,jn as buildArkRunInspectorSnapshot,Re as buildDependencyInformationPackage,en as buildPublishPolicyContext,Xl as catalogFixForRuleId,Zl as catalogWhyForRuleId,cr as checkAdapterGovernance,ss as checkContract,xr as classifyArkPolicyDelta,$n as closeArkRunGraphQuery,Xr as closedArkRunEphemeral,Yr as closedArkRunTransportKind,wn as collectAnalysisConfigWarnings,Ye as collectForbiddenCapabilityUses,Ur as compareInformationPackages,fs as createAICodeGate,os as createAdapter,Va as createAdapterResult,gn as createArchitectureProfile,mn as createArchitectureProfileFromArkConfig,jt as createArkKernel,xa as createArkKernelFromConfig,Tn as createArkManifest,Uo as createArkTestHarness,an as createAuditTrail,cn as createDependencyGraph,ns as createElevenLayerArkConfig,Do as createEventBus,rn as createEventContractRegistry,Yt as createIntentRegistry,so as createLenientArkKernel,Pa as createLenientArkKernelFromConfig,hn as createMetadataRegistry,on as createObservabilityReporter,_n as createProjectionRegistry,Ir as createResolvedCandidateFacts,oa as createSaga,ro as createStrictArkKernel,Oa as createStrictArkKernelFromConfig,Pt as createWorkflowEngine,go as defaultIntentRegistry,Qt as defineArchitectureProfilePolicy,fo as defineIntent,Zt as defineLayerPolicy,De as definePolicy,rs as definePort,ho as definePublishPolicy,Pr as detectArchitectureCycles,B as deterministicHash,ta as diagnosticDocsFragment,zl as diagnosticDocsPath,Be as elevenLayerProfile,Qe as evaluateArchitectureGraph,Ds as explainViolation,ze as extractSemanticDependencies,zr as formatArkRunGraphMermaid,Ut as formatArkRunInspectorSseEvent,On as getDiagnosticCatalogEntry,st as isArkRunInspectorLoopbackHost,Vn as isArkRunInspectorProductionEnv,ql as isCataloguedOrArkRuleFamily,Wl as isKnownDiagnosticCode,Jt as isLayerPolicy,vn as loadContract,ve as loadResolvedCandidateFacts,Or as policyDeltaAcknowledgementMatches,Qs as preflightChange,ea as preflightResolvedChange,da as replayInformationPackages,Kn as requestArkRunGraph,Gt as resolveArkRunInspectorBind,Gn as resolveArkRunSendPlan,It as resolvedFactsEvidenceRequirementsHash,Yl as serializeDiagnosticCatalog,ca as shadowInformationPackage,F as stableSerialize,Wn as startArkRunInspector,dn as syncRegistryToGraph,Jn as toAdapterDiagnostic,Xt as validateIntentName,Zn as version};
|